Monday, September 27, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


I am New to Python and I am getting a Syntax error in a code I thought was correct

Posted: 27 Sep 2021 08:17 AM PDT

num_1 = int(input("enter a num below 20 : ")    if (20 < num_1):      print ("To high")  else:      print ("Thank you")  

Please what is wrong with this code?

AJAX request sending null to controller

Posted: 27 Sep 2021 08:16 AM PDT

I have the following Ajax request

var csrfName = '<?php echo $this->security->get_csrf_token_name();?>';          var csrfHash = '<?php echo $this->security->get_csrf_hash();?>';          var searchTerm = $("#mastheadSearch").val();          var data = {};          data['Search'] = searchTerm;          data[csrfName] = csrfHash;          $.ajax({              type: 'POST',              url:'<?=base_url()?>news/support',              contentType : 'application/json',              data:JSON.stringify(data),          });  

But I can not access this information from the controller.

$rawData = file_get_contents("php://input");  $newData = json_decode($rawData);  

The strange thing is that if I insert a breakpoint with xdebug, it says the variable $newData has a value (which is the value I expected it to be). However if I try and access this variable within my code I get an error message (Severity: Notice

Message: Trying to access array offset on value of type null).

I have read posts of people with similar issues and tried the suggested fixes but none seem to work for me.

Variable not defined even though I did define it [closed]

Posted: 27 Sep 2021 08:16 AM PDT

I'm making a paint program and there's an option to change the color of the paint.

Here's my example ->


VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

from tkinter import *  from tkinter.colorchooser import askcolor  root = Tk()  root.title("Paint Application")  root.geometry("500x350")  # askcolor(color=None)      x = Toplevel()    global material    def b1f() :      exec('material = "white"')  def b2f() :      exec('material = "green"')  def b3f() :      exec('material = "red"')    b1 = Button(x, text="Tiles", command=b1f)    b2 = Button(x, text="Grass", command=b2f)    b3 = Button(x, text="Flowers", command=b3f)    b1.pack()  b2.pack()  b3.pack()      def paint(event):      # get x1, y1, x2, y2 co-ordinates      x1, y1 = (event.x-3), (event.y-3)      x2, y2 = (event.x+3), (event.y+3)      exec('color =' +  material)      # display the mouse movement inside canvas      wn.create_oval(x1, y1, x2, y2, fill=color, outline=color)      wn = Canvas(root, width=500, height=350, bg='white')  fr = Frame(root, bg="black")  fr.pack(side=RIGHT)        colorc = Button(fr, text="color")  colorc.pack()  # bind mouse event with canvas(wn)  wn.bind('<B1-Motion>', paint)  wn.pack()  root.mainloop()  

fix javascript navigation probleme

Posted: 27 Sep 2021 08:16 AM PDT

please can you help me with this pages navigation script. on mobile when I click on the next page number 2 or 3.. it stays on the first page. on desktop it works very well and I navigate from one page to another without any problem, but on the phone the navigation does not work. the page numbers are displayed but when I click on a next page number it stays on the first page. can you, please, find a slolution to this.

I suck at javascript, I hope someone shows me where the problem is, and offers me a solution. thank you from the bottom of my heart. here is the code :

function showpageCount(json){var thisUrl=home_page_url;var htmlMap=new Array();var thisNum=1;var postNum=1;var itemCount=0;var fFlag=0;var eFlag=0;var html='';var upPageHtml='';var downPageHtml='';for(var i=0,post;post=json.feed.entry[i];i++){var timestamp1=post.published.$t.substring(0,19)+post.published.$t.substring(23,29);timestamp=encodeURIComponent(timestamp1);var title=post.title.$t;if(title!=''){if(itemCount==0||(itemCount%pageCount==(pageCount-1))){if(thisUrl.indexOf(timestamp)!=-1){thisNum=postNum}if(title!='')postNum++;htmlMap[htmlMap.length]='/search?updated-max='+timestamp+'&max-results='+pageCount}}itemCount++}for(var p=0;p<htmlMap.length;p++){if(p>=(thisNum-displayPageNum-1)&&p<(thisNum+displayPageNum)){if(fFlag==0&&p==thisNum-2){if(thisNum==2){upPageHtml=''+upPageWord+''}else{upPageHtml=''+upPageWord+''}fFlag++}if(p==(thisNum-1)){html+=''+thisNum+''}else{if(p==0){html+='1'}else{html+=''+(p+1)+''}}if(eFlag==0&&p==thisNum){downPageHtml=' '+downPageWord+'';eFlag++}}}if(thisNum>1){html=''+upPageHtml+' '+html+' '}html=' Pages '+(postNum-1)+''+html;if(thisNum<(postNum-1)){html+=downPageHtml}if(postNum==1)postNum++;html+='';var pageArea=document.getElementsByName("pageArea");var blogPager=document.getElementById("blog-pager");if(postNum<=2){html=''}for(var p=0;p<pageArea.length;p++){pageArea[p].innerHTML=html}if(pageArea&&pageArea.length>0){html=''}if(blogPager){blogPager.innerHTML=html}}function showpageCount2(json){var thisUrl=home_page_url;var htmlMap=new Array();var isLablePage=thisUrl.indexOf("/search/label/")!=-1;var thisLable=isLablePage?thisUrl.substr(thisUrl.indexOf("/search/label/")+14,thisUrl.length):"";thisLable=thisLable.indexOf("?")!=-1?thisLable.substr(0,thisLable.indexOf("?")):thisLable;var thisNum=1;var postNum=1;var itemCount=0;var fFlag=0;var eFlag=0;var html='';var upPageHtml='';var downPageHtml='';var labelHtml='';var thisUrl=home_page_url;for(var i=0,post;post=json.feed.entry[i];i++){var timestamp1=post.published.$t.substring(0,19)+post.published.$t.substring(23,29);timestamp=encodeURIComponent(timestamp1);var title=post.title.$t;if(title!=''){if(itemCount==0||(itemCount%pageCount==(pageCount-1))){if(thisUrl.indexOf(timestamp)!=-1){thisNum=postNum}if(title!='')postNum++;htmlMap[htmlMap.length]='/search/label/'+thisLable+'?updated-max='+timestamp+'&max-results='+pageCount}}itemCount++}for(var p=0;p<htmlMap.length;p++){if(p>=(thisNum-displayPageNum-1)&&p<(thisNum+displayPageNum)){if(fFlag==0&&p==thisNum-2){if(thisNum==2){upPageHtml=labelHtml+upPageWord+''}else{upPageHtml=''+upPageWord+''}fFlag++}if(p==(thisNum-1)){html+=''+thisNum+''}else{if(p==0){html=labelHtml+'1'}else{html+=''+(p+1)+''}}if(eFlag==0&&p==thisNum){downPageHtml=' '+downPageWord+'';eFlag++}}}if(thisNum>1){if(!isLablePage){html=''+upPageHtml+' '+html+' '}else{html=''+upPageHtml+' '+html+' '}}html=' Pages ('+(postNum-1)+')'+html;if(thisNum<(postNum-1)){html+=downPageHtml}if(postNum==1)postNum++;html+='';var pageArea=document.getElementsByName("pageArea");var blogPager=document.getElementById("blog-pager");if(postNum<=2){html=''}for(var p=0;p<pageArea.length;p++){pageArea[p].innerHTML=html}if(pageArea&&pageArea.length>0){html=''}if(blogPager){blogPager.innerHTML=html}}var home_page_url=location.href;var thisUrl=home_page_url;if(thisUrl.indexOf("/search/label/")!=-1){if(thisUrl.indexOf("?updated-max")!=-1){var lblname1=thisUrl.substring(thisUrl.indexOf("/search/label/")+14,thisUrl.indexOf("?updated-max"))}else{var lblname1=thisUrl.substring(thisUrl.indexOf("/search/label/")+14,thisUrl.indexOf("?&max"))}}var home_page="/";if(thisUrl.indexOf("?q=")==-1){if(thisUrl.indexOf("/search/label/")==-1){document.write('</script>')}else{document.write('</script>')}}

Vue Cli Electron: env file missing in release

Posted: 27 Sep 2021 08:16 AM PDT

I'm building an app with Electron, using Vue-Cli-Electron.

Locally I've got access to the .env.local file, but when I publish, the file .env.production, is not packaged and the variables in it are missing.

Reading around there is no much (nothing) I have to do about this file, it should simply be there and picked automatically... or I'm missing something.

I'm using the following command to publish:

"publish": "vue-cli-service electron:build --p always"  

and the release works well but the env variables are not there.

Any idea? Thanks!

Count unique rows GROUP(ed) BY different columns than used in DISTINCT ON

Posted: 27 Sep 2021 08:16 AM PDT

I'm sure this has been asked over and over, but I can't quite find a simple example that I can fully grok.

I'm trying to deduplicate (do a DISTINCT ON) by one column and COUNT records GROUPed By columns that differ from the column used to deduplicate.

Let's say I have a table with the following information:

order_num date region timestamp_updated
001 2021-09-01 Murica 2021-09-02T19:00:01Z
001 2021-09-01 Murica 2021-09-03T19:00:01Z
002 2021-09-01 Yurop 2021-09-02T19:00:01Z
003 2021-09-01 Yurop 2021-09-03T19:00:01Z
004 2021-09-02 Yurop 2021-09-03T19:00:01Z

I would like to first get unique records with different order_num (keeping the most recently updated) ones AND then count groups or orders by date and region.

  • De-duplicate (gets rid of the oldest order_num='001A'):

    order_num date region timestamp_updated
    001 2021-09-01 Murica 2021-09-03T19:00:01Z
    002 2021-09-01 Yurop 2021-09-02T19:00:01Z
    003 2021-09-01 Yurop 2021-09-03T19:00:01Z
    004 2021-09-02 Yurop 2021-09-03T19:00:01Z
  • Then group by and count:

    date region count
    2021-09-01 Murica 1
    2021-09-01 Yurop 2
    2021-09-02 Yurop 1

I know how to do those two things separately (distinct on(order_num) + order by timestamp_updated desc) to deduplicate and then select count(*) + group by date, region ) And even together with subqueries. But I'd like to try to avoid subqueries as much as possible and here's where window functions (seem) to come in handy and I don't know ~much~ about those.

The closest thing I've been able to get are groups, but they show one record by each order_num. The records are correct, but they are duplicated:

select distinct on (order_num) date, region, count(1)over (      partition by order_num  )  from orders_table  order by order_num, timestamp_updated desc;  

That query ^^ shows: | date | region | count | | |:------:|:-----:|:------------:|:-----:| | 2021-09-01 | Murica | 1 | I think this is the first 001 | 2021-09-01 | Murica | 1 | I think this is the second 001 | 2021-09-01 | Yurop | 2 | I think this is the first Yurop: 002 | 2021-09-01 | Yurop | 2| I think this is the second Yurop: 003 | 2021-09-02 | Yurop | 1

Count how many times a category appears with other categories

Posted: 27 Sep 2021 08:16 AM PDT

I have a pandas dataframe with

ID Category
1 A
1 B
1 C
2 A
2 B
3 A
3 B
3 C
4 A
4 C

I want to create two tables: one in absolute values and another with the percentages of how many times a category appears in the same ID with other categories

Category A and C appear together 3 times (75%) Category A and B the same. And so on..

List of Lists of Lists to dataframes R

Posted: 27 Sep 2021 08:16 AM PDT

I need to convert a triple nested list to data frames. The outer list is a list of lists of lists.

typeof(outter_list)  [1] "list"  typeof(outter_list[1])  [1] "list"  typeof(outter_list[[1]])  [1] "character"  

using returned_obj[1] and then an answer to a list of lists to df question has not worked for me.

jQuery counter starts only in viewport

Posted: 27 Sep 2021 08:16 AM PDT

I have a counter stats, which works fine, but how can I write a condition that it should start only if the parent is in viewport? Maybe my syntax is wrong or I don't understand how to connect what I got. Any advice is appreciated.

This is what I got for now:

$(window).scroll(function() {    if ($('.numbers-inner').isInViewport()) {      //then what?;      } else {      //else what?;    }  });  $('.magPub, .pplHired, .yrsExp').each(function() {    $(this).prop('Counter', 0).animate({      Counter: $(this).text()    }, {      duration: 1500,      easing: 'swing',      step: function(now) {        $(this).text(Math.ceil(now));      }    });  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    <div class="numbers-inner stats">    <ul>      <li><span class="magPub">33708</span>+</li>      <li>magazines published</li>    </ul>      <ul>      <li><span class="pplHired">247</span></li>      <li>people hired</li>    </ul>      <ul>      <li><span class="yrsExp">17</span></li>        <li>years of experience</li>    </ul>    </div>

Error to retrieve data in PHP received object array from android retrofit2

Posted: 27 Sep 2021 08:16 AM PDT

  1. Sending list from android using retrofit2 but unable to fetch data in php. when sending field working ok but in array could not. from web server to android working ok.
  2. Please Help I have worked on this problem too much from web server receive data perfect sending with field also ok but cant send array and retrieve
  3. dont know what to write in PHP and how to retrieve data received success message from web server but could not retrieve data could not confirm whether data received or not
        <?php      $a = $_POST[ ??];       $mdata=array();      $mdata['response'] = 'success';      echo json_encode($mdata);      ?>  

in android studio debug shows data as follows

Object->0-ArrayList->CartModel->ur_id=1,mrk_id=2,gm_id=3,game_type=test,gameName=name;

    public interface Api {      @POST("play.php")      Call<ResultResponse> playFinalGame(@Body List<CartModel> list);      }      public class NetworkClient {      private static final String BASE_URL = "http://example.com/xxx/";      private static NetworkClient mInstance;      private Retrofit retrofit = new            Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())      .build();        private NetworkClient() {      }        public static synchronized NetworkClient getmInstance() {      NetworkClient networkClient;      synchronized (NetworkClient.class) {          if (mInstance == null) {              mInstance = new NetworkClient();          }          networkClient = mInstance;      }      return networkClient;      }        public Api getApi() {      return (Api) this.retrofit.create(Api.class);      }      public class CartModel{      String ur_id;      String mrk_id;      String gm_id;      String game_type;      String gameName;      public CartModel(String str, String str2, String str3, String str4, String str5){      this.ur_id = str;       this.mrk_id = str2;       this.gm_id = str3;       this.game_type = str4;      this.gameName = str5;      }      public String getUr_id(){        return this.ur_id;      }      public void setUr_id(String str){           this.ur_id = str;      }      public String getMrk_id(){           return this.mrk_id;      }      public void setMrk_id(String str){          this.mrk_id = str;        }      public String getGm_id(){           return this.gm_id;      }      public void setGm_id(String str){            this.gm_id = str;       }      public String getGame_type(){           return this.game_type;      }      public void setGame_type(String str){            this.game_type = str;       }      public String getGameName(){           return this.gameName;      }      public void setGameName(String str){           this.gameName = str;       }      }            public class CartModelList {      List<CartModel> cartModelList;      public CartModelList(List<CartModel> list){          this.cartModelList = list;      }        public List<CartModel> getCartModelList(){          return this.cartModelList;      }        public void setCartModelList(List<CartModel> list){          this.cartModelList = list;      }      }      MainActivity      List<CartModel> cartModelList;      this.cartModelList = new ArrayList();      this.cartModelList.add(new CartModel("1","2","3","Name","Test"));      NetworkClient.getmInstance().getApi().playFinalGamePlay(this.cartModelList).enqueue(new       Callback<ResultResponse>() {      @Override      public void onResponse(Call<ResultResponse> call, Response<ResultResponse> response) {      if (response.body() != null && response.body().getResponse().equals("success")) {      **message received success      }      }      @Override      public void onFailure(Call<ResultResponse> call, Throwable t) {          Log.d("","Fail");      }      });      dependencies {      implementation 'com.squareup.retrofit2:retrofit:2.3.0'      implementation 'com.squareup.retrofit2:converter-gson:2.3.0'      implementation 'com.google.code.gson:gson:2.6.2'      }   '''  

LOGGING in .NET 5 multiple constructors with dependency injection

Posted: 27 Sep 2021 08:16 AM PDT

Background

I am new to C# dotnet and I need to enable logging into my project. Therefore, I followed some online materials including Microsoft documentation. My implementation is slightly different than the example in the document as I have another constructor with dependency injection. Then I found Stackoverflow article that explains how to handle dependency injection with multiple constructors. After that, I implemented the code as below.

in Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>      Host.CreateDefaultBuilder(args)          .ConfigureLogging(builder =>          {                 builder.ClearProviders();                 builder.AddConsole();          })          .ConfigureWebHostDefaults(webBuilder =>          {                 webBuilder.UseStartup<Startup>();          });  

Then I created a sample controller and implemented the logger as below.

private ILogger<HomeController> _logger;  public HomeController(ILogger<HomeController> logger)  {        _logger = logger;  }    [HttpGet]  public IActionResult Index()  {        _logger.LogInformation("Test");        return Ok("Home controller");  }  

It does work only when the

builder.ClearProviders();  builder.AddConsole();  

are commented in the Program.cs

Then I implemented a logger in a class that has a constructor already with dependency injection.

private ICachingService _cashService;  private readonly ILogger<ExampleHelper> _logger;                      public ExampleHelper(ICachingService cachingService)  {       _cashService = cachingService;  }    [ActivatorUtilitiesConstructor]  public ExampleHelper(ILogger<ExampleHelper> logger)  {      _logger = logger;      _logger.LogInformation("Example Logger");  }  

Results are breakpoint of the _logger.LogInformation("Example Logger"); does not hit and throws the following exception.

Exception thrown: 'System.ArgumentNullException' in Microsoft.Extensions.Logging.Abstractions.dll

If further information is needed, I can provide them.

Question 1: Why Homecontroller logger is not working when clear providers and add console in program.cs ?

Question 2: How to avoid exception and print the log in the ExampleHelper class ?

How to replace string occurrences in python file?

Posted: 27 Sep 2021 08:16 AM PDT

I have a CSV file which contains lines of sql entries. Each sql entry, contains message which are SOH delimited and are tag=value pairs.

8=Fix1.1<SOH>9=70<SOH>35=AE<SOH>10=237   8=Fix1.1<SOH>9=71<SOH>35=AE<SOH>10=238  8=Fix1.1<SOH>9=72<SOH>35=AE<SOH>10=239  8=Fix1.1<SOH>9=73<SOH>35=AE<SOH>10=240   

Issue:

  • The below code snippet removes SOH to "," as expected, however, having trouble removing the tag part from the lines.
# Read in the file  with open('file.txt', 'r') as file :    filedata = file.read()    # Replace the target string  filedata = filedata.replace('x01', ',')   filedata2 = filedata.replace("=", ",")   # Write the file out again  with open('file.txt', 'w') as file:    file.write(filedata2)  

Output:

8,Fix1.1,9,70,35,AE,10,237  8,Fix1.1,9,71,35,AE,10,238  8,Fix1.1,9,72,35,AE,10,239  8,Fix1.1,9,73,35,AE,10,240  

I've also tried regex = re.compile ("[=]") and then loop into line reader and modify, but just returns all [=] in the print.

Desired output:

Fix1.1,70,AE,237    Fix1.1,71,AE,238    Fix1.1,72,AE,239    Fix1.1,73,AE,240  

how to calculate number of values appeared in a string of list of lists

Posted: 27 Sep 2021 08:17 AM PDT

how to calculate number of values appeared in a string of list of lists

a=['1000','10,8,6','9,76,9.0','1,2']  

required output

b=[1,3,3,2]  

a is in my input, the required output is b how to do it using python

Share with anyone on the web interactive python jupyter notebook with dependent files and functions in another file (.py): Colab or something else?

Posted: 27 Sep 2021 08:17 AM PDT

What are the free solutions for sharing an interactive python Jupyter notebook with user-defined module and dependent input files?

I have python Jupyter notebook that serves as a code interface for non-technical users. The code itself is in another file code.py that contains many functions that are called from the python Jupyter notebook as needed. Running these functions reqires about ten input files with a size of 100 mb. I want anyone on the web to open this notebook in an executable environment such that the user can run the code with different user choices.

One approach I consider implementing is to use Google Colab, Google Drive, GitHub, and
the Python Package Index (PyPI) as follows:

  1. Package the code.py as PyPI module
  2. Add dependent input files on Google Drive and get their shared link id
  3. Add Colab notebook on GitHub
  4. Once the user run the Colab notebook then it will pip install code.py and download the dependent input files from Google Drive

How to improve or simplify this approach?
What would be a better Colab-based approach to do this job?
Is there any other environments (e.g., Binder) that are more suitable than Colab for this job ?

Could not cast value of type '__NSDictionaryI'

Posted: 27 Sep 2021 08:16 AM PDT

I m using this code to call my rest web service. But if I try to decode the result of web service call I received error.

class func callPostServiceReturnJson(apiUrl urlString: String, parameters params : [String: AnyObject]?,  parentViewController parentVC: UIViewController, successBlock success : @escaping ( _ responseData : AnyObject, _  message: String) -> Void, failureBlock failure: @escaping (_ error: Error) -> Void) {                    if Utility.checkNetworkConnectivityWithDisplayAlert(isShowAlert: true) {              var strMainUrl:String! = urlString + "?"                for dicd in params! {                  strMainUrl.append("\(dicd.key)=\(dicd.value)&")              }              print("Print Rest API : \(strMainUrl ?? "")")                  let manager = Alamofire.SessionManager.default              manager.session.configuration.timeoutIntervalForRequest = 120              manager.request(urlString, method: .get, parameters: params)                  .responseJSON {                      response in                      switch (response.result) {                      case .success:                          do{                                                                                                                      let users = try JSONDecoder().decode(OrderStore.self, from: response.result.value! as! Data)                                                        }catch{                              print("errore durante la decodifica dei dati: \(error)")                          }                          if((response.result.value) != nil) {                              success(response as AnyObject, "Successfull")                          }                          break                      case .failure(let error):                          print(error)                          if error._code == NSURLErrorTimedOut {                              //HANDLE TIMEOUT HERE                              print(error.localizedDescription)                              failure(error)                          } else {                              print("\n\nAuth request failed with error:\n \(error)")                              failure(error)                          }                          break                      }              }          } else {              parentVC.hideProgressBar();              Utility.showAlertMessage(withTitle: EMPTY_STRING, message: NETWORK_ERROR_MSG, delegate: nil, parentViewController: parentVC)          }      }  

This is the error that I can print:

Could not cast value of type '__NSDictionaryI' (0x7fff86d70b80) to 'NSData' (0x7fff86d711e8).  2021-09-27 16:34:49.810245+0200 ArrivaArrivaStore[15017:380373] Could not cast value of type '__NSDictionaryI' (0x7fff86d70b80) to 'NSData' (0x7fff86d711e8).  Could not cast value of type '__NSDictionaryI' (0x7fff86d70b80) to 'NSData' (0x7fff86d711e8).  CoreSimulator 732.18.6 - Device: iPhone 8 (6F09ED5B-8607-4E47-8E2E-A89243B9BA90) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 8  

I generated OrderStore.swift class from https://app.quicktype.io/

//EDIT enter image description here

PyInstaller + tkdnd/tkinterdnd2 "Unable to load tkdnd library" when launching frozen exe. Works when launched from script

Posted: 27 Sep 2021 08:16 AM PDT

In my script I am using tkinterdnd2 library to achieve drag and drop functionality from Windows explorer into my tkinter UI.

from tkinterdnd2 import TkinterDnD, DND_FILES  import tkinter as tk    class TkWindow:      def __init__(self):          self.window = TkinterDnD.Tk()          self.tbox = tk.Listbox(self.window)          self.tbox.pack(fill=tk.BOTH)          self.tbox.drop_target_register(DND_FILES)          self.tbox.dnd_bind('<<Drop>>', self.tk_files_dropped)          self.window.mainloop()        def tk_files_dropped(self, event):          messagebox.showinfo("x", event.data)    TkWindow()  

When I launch the script - everything works.

But when I freeze the project to a single EXE with PyInstaller, and run it, I get this error:

Unable to load tkdnd library.

I tried this solutions already:

  1. I added the pyinstaller-hook as instructed in the tkinterdnd2 repository:

    from PyInstaller.utils.hooks import collect_data_files, eval_statement
    datas = collect_data_files('tkinterdnd2')

  2. I add --collect-all tkinterdnd2 when executing build command.

  3. I tried copying tkdnd2.8 to tcl8.6 as mentioned in this answer

  4. I tried getting rid of venv and installing all the packages directly into base python interpreter.

(JavaScript/CEP) Is it possible to get the origin of my page on InDesign?

Posted: 27 Sep 2021 08:17 AM PDT

I'm working on an InDesign plugin and I would like to know if it is possible to get the origin of my page?

I was thinking about something like this :

var origin = app.activeDocument.pages[0].getOrigin();  

Thank you in advance for your help !

Implementing a "temporarily suspendable" concurrent loop in C++

Posted: 27 Sep 2021 08:16 AM PDT

I'm writing a program whose main thread spawns a worker thread that performs some work, sleeps for a set amount of time in an infinite loop, i.e. the worker thread executes:

void do_work() {    for (;;) {      // do some work            std::this_thread::sleep_for(100ms);    }  }  

Now, I would additionally like to be able to temporarily completely disable this worker thread from the main thread, i.e. I would like to write the following functions:

  • disable_worker(): disable the worker thread
  • enable_worker(): enable the worker thread again

What I've come up with is the following:

#include <chrono>  #include <condition_variable>  #include <mutex>  #include <thread>    using namespace std::literals::chrono_literals;    bool enabled;  std::mutex mtx;  std::condition_variable cond;    void disable_worker() {    std::lock_guard<std::mutex> lock(mtx);    enabled = false;  }    void enable_worker() {    {      std::lock_guard<std::mutex> lock(mtx);      enabled = true;    }      cond.notify_one();  }    void do_work() {    for (;;) {      std::unique_lock<std::mutex> lock(mtx);      cond.wait(lock, []{ return enabled; });        // ... do some work ...        std::this_thread::sleep_for(100ms);    }  }      int main() {    std::thread t(do_work);      // ... enable/disable t as necessary ...  }  

I suppose this works (at least I can't spot any issues), however, I would also like to guarantee that when either of enable_worker and disable_worker return (in the main thread), the working thread is guaranteed to be either blocking on the condition variable or sleeping, i.e. not performing any work. How can I implement this without any race conditions?

pass the two zone_id values dynamicaly into the resource "aws_route53_record" "cert_validation"

Posted: 27 Sep 2021 08:16 AM PDT

I need to get the two zone_id values into the resource "aws_route53_record" "cert_validation"? I need to create those resources dynamicaly from the snippet provided in the yaml file at the bottom of my post. Currently I'm stucked. How can I convert the variable type?

I get this error

│ Error: Invalid function argument  │   │   on certificate.tf line 44, in resource "aws_route53_record" "cert_validation":  │   44:           zone_id = contains(keys(d.apex_name), dvo.domain_name) ? aws_route53_zone.this[d.apex_name].id : null  │     ├────────────────  │     │ d.apex_name is "elastic2ls.com"  │   │ Invalid value for "inputMap" parameter: must have map or object type.  ╵  ERRO[0009] 1 error occurred:          * exit status 1    

Any help is highly appreciated.

locals {    zone_records = flatten([      for d in var.source_domains : [        for r in d.records : {          zone_name = d.apex_name          zone_id   = aws_route53_zone.this[d.apex_name].id          record    = r        }      ]    ])    subject_alternative_names = flatten([      for d in var.source_domains :        contains(keys(d), "records")    ])  }    resource "aws_route53_zone" "this" {    for_each = {      for d in var.source_domains : d.apex_name => d    }      name = each.value.apex_name  }    resource "aws_acm_certificate" "cert" {    provider                  = aws.certificate_region    domain_name               = var.target_domain    subject_alternative_names = local.subject_alternative_names    validation_method         = "DNS"    }    resource "aws_route53_record" "cert_validation" {    for_each = {    for dvo in aws_acm_certificate.cert.domain_validation_options : dvo.domain_name => {      name = dvo.resource_record_name      record = dvo.resource_record_value      type = dvo.resource_record_type      zone_id = flatten([        for d in var.source_domains : [          for r in d.records : {            zone_id = contains(keys(d.apex_name), dvo.domain_name) ? aws_route53_zone.this[d.apex_name].id : null          }        ]      ])    }    }    allow_overwrite = true    name            = each.value.name    records         = [each.value.record]    ttl             = 60    type            = each.value.type    zone_id         = each.value.zone_id  }  
source_domains:    - apex_name: elastic2ls.com      records:        - elastic2ls.com        - www.elastic2ls.com    - apex_name: elastic2ls.ch      records:      - elastic2ls.ch      - www.elastic2ls.ch      - image.elastic2ls.ch      - m.elastic2ls.ch      - static.elastic2ls.ch  

install pytorch c++ api CUDA11.4 for ubuntu

Posted: 27 Sep 2021 08:16 AM PDT

I'm trying to use the PyTorch c++ API on an ubuntu 18.04. I've installed CUDA 11.4 and cuDNN 8.2.4.15. The source I'm compiling is available here. compiling CUDA with nvcc works and the cuDNN installation test succeeds. But I am unable to find a good documentation for installing and compiling projects with PyTorch c++ api on Ubuntu. Do you know any god ones?

system configurations:
OS: ubuntu 18.04
GPU: 1 x NVIDIA Tesla P4
Machine Type: n1-standard-2 (2 vCPUs, 7.5 GB memory) on google cloud console
CUDA: 11.4
cuDNN: 8.2.4.15

Update existing rows with values of new row if given field is identical

Posted: 27 Sep 2021 08:16 AM PDT

Sorry everybody, my MySql-knowledge is a bit shaky ... I have a table with (among others) the following columns/values:

ID | importID | distID | email     | street       | city  -----------------------------------------------------------  25 | 5        | 2      | abc@d.com | Main Road    | London  -----------------------------------------------------------  26 | 5        | 2      | mno@e.com | Oak Alley    | York  -----------------------------------------------------------  27 | 5        | 2      | pqr@s.com | Tar Pits     | London  -----------------------------------------------------------  28 | 5        | 2      | xyz@a.com | Fleet Street | London  -----------------------------------------------------------  ...  -----------------------------------------------------------  99 | -1       | 2      | abc@d.com | New Street   | Exeter  

I do some checks when new rows are inserted: validate email addresses, find doublets with different dist(ributor)ID etc.

One of the tasks is "update existing rows with data of the freshly imported row when column "email" is identical" (yes, there can be multiple rows with identical email addresses).

At the time this task is performed, the importID of the currently inserted rows is always -1. I tried aliasing with all kinds of variations of

UPDATE table orig table dup  SET orig.street = dup.street, orig.city = dup.city  WHERE orig.email = dup.email  

or joining with numerous variations of

UPDATE table orig  JOIN     (SELECT email FROM table    WHERE importID != -1) dup  ON orig.email = dup.email  SET orig.street = dup.street, orig.city = dup.city  

I'm pretty sure one of you can help me find my mistake in thinking/coding ... thank you!

Application logs in, but redirects back to login

Posted: 27 Sep 2021 08:17 AM PDT

I have a piece of code that do not work, and I cannot understand why. As the subject says, it logs in to Twitter, but redirects back to the sign in button. setupTimeline(); is never executed.

I am using twitter4j library, it is at the latest version, 4.0.7.

@Override  public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      // Get the preferences for the app.      tweetzPrefs = getSharedPreferences("TweetzPrefs", 0);      // Find out if the user preferences are set.      if (tweetzPrefs.getString("user_token", null) == null) {          // No user preferences so prompt to sign in.          setContentView(R.layout.activity_main);          // Get a twitter instance for authentication.          tweetzTwitter = new TwitterFactory().getInstance();          // Pass developer key and secret.          tweetzTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);          // Try to get request token.          try {              new Thread(new Runnable() {                  @Override                  public void run() {                      try {                          // Get authentication request token.                          tweetzRequestToken = tweetzTwitter.getOAuthRequestToken(TWIT_URL);                          Log.e(LOG_TAG, "Are we there Yeti?");                      } catch (TwitterException e) {                          e.printStackTrace();                          Log.e(LOG_TAG, "TwitterException: " + e.getMessage());                      }                      if (tweetzRequestToken == null) {                          Log.e(LOG_TAG, "tweetzRequestToken == null.");                      }                  }              }).start();              // Get authentication request token.              // tweetzRequestToken = tweetzTwitter.getOAuthRequestToken(TWIT_URL);          } catch (Exception e) {              e.printStackTrace();              Log.e(LOG_TAG, "Exception: " + e.getMessage());          }          // Setup button for click listener.          Button signIn = (Button) findViewById(R.id.signin);          signIn.setOnClickListener(this);      } else {          // User preferences are set, get timeline.          setupTimeline();      }  }  

Any ideas anyone?

Regards.

How to read XML data and write to Excel sheet in Python for Selenium Automation

Posted: 27 Sep 2021 08:16 AM PDT

I have a scenario where I need to get the data from XML file and write the same to Excel sheet and use the same sheet for data processing. I am able to read the data from XML, but not able to insert the same data (records) to an excel file I am using OpenPyExcel for this, please suggest any alternative and help me here. I am not seeing any error though, but nothing is being written to excel sheet

import xml.etree.ElementTree as ET  import openpyexcel    tree = ET.parse("Test_Cust.xml")  root = tree.getroot()  workbook = openpyexcel.load_workbook("xml_excel.xlsx")  sheet = workbook["Sheet1"]    for items in root.iter():      if items.tag == "Email":          cust_email = items.text      elif items.tag == "CompanyName":          cust_cn = items.text      elif items.tag == "FirstName":          cust_fn = items.text      elif items.tag == "LastName":          cust_ln = items.text            rownum = (sheet.max_row)          print(rownum)          colnum = (sheet.max_column)          print(colnum)            for r in range(2, rownum+1):              for c in range(1, colnum+1):                    sheet.cell(row = r, column = c).value = cust_email                  sheet.cell(row=r, column=c).value = cust_email                  sheet.cell(row=r, column=c).value = cust_email                  sheet.cell(row=r, column=c).value = cust_email                  workbook.save("xml_excel.xlsx")  print("Done")  

Python not finding own directory, "ModuleNotFoundError: No module named ..." (Spyder IDE)

Posted: 27 Sep 2021 08:17 AM PDT

I'm currently trying to run an old github project and am running into an error with Python 3 in Spyder. I have

from nmap_visualizer.db import Savednmap, User, db

in my code and am getting a "ModuleNotFoundError: No module named 'nmap_visualizer'"

However, the folder that contains db.py is called 'nmap_visualizer. This is my working directory and the file I'm trying to run this code in 'nmap.py' is in the same folder alongside db.py. In PYTHONPATH manager I've selected the nmap_visualizer folder for my path. In 'Preferences' under 'Run' I have 'Default working directory is:' 'The directory of the file being executed'.

When I try from .db import Savednmap, User, db I get the error "ModuleNotFoundError: No module named 'main.db'; 'main' is not a package"

I do have an init.py file which runs and imports db perfectly fine with from . import db, but I'm not sure why my 'nmap.py' file is failing.

spring core aws messaging Notification template not binding the message properly

Posted: 27 Sep 2021 08:16 AM PDT

I am using spring-boot-2.2.1 along with AWS SNS & SQS. I was publishing a message from SNS to SQS. I am able to receive the message using String but @NotificationMessage is returning null instead of the message body. The same code was working fine when I was using spring-boot-1.5.19

pom.xml

 <parent>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-parent</artifactId>          <version>2.2.1.RELEASE</version>          <relativePath/> <!-- lookup parent from repository -->      </parent>        <dependency>              <groupId>org.springframework.cloud</groupId>              <artifactId>spring-cloud-starter-aws-messaging</artifactId>          </dependency>  

Main file

        @SpringBootApplication  public class AwsApplication {        public static void main(String[] args) {          SpringApplication.run(AwsApplication.class, args);      }        @Bean      public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSqs) {          return new QueueMessagingTemplate(amazonSqs);      }        @Bean      public NotificationMessagingTemplate notificationMessagingTemplate(              AmazonSNS amazonSNS) {          return new NotificationMessagingTemplate(amazonSNS);      }        @Bean      public IotClient getIotClient() {          return IotClient.builder()                  .credentialsProvider(() -> AwsBasicCredentials.create(AWS_ACCESSKEY, AWS_SECRETKEY))                  .credentialsProvider(() -> InstanceProfileCredentialsProvider.create().resolveCredentials())                  .region(Region.US_EAST_2)                  .build();      }     }  

SQS listener class

@SqsListener(value = "${sqs.consumer.name}")  public void receiveSnsSqs(String message, @NotificationMessage Employee employee) {      System.out.println("SNS Consumer received the message::"+message);      System.out.println("SNS Consumer received the notificationMessage::"+employee);      }  

In the above listener class, I am able to receive the message but the employee is getting as null. I am sending a message from AWS SNS directly.

As I mentioned it was working fine before it stopped working after migrating the spring version to 2.2.1 release.

Any help would be really appreciated.

Why Electron spawns a process per each window?

Posted: 27 Sep 2021 08:16 AM PDT

I'm working on electron app with multiple windows. Let say I have the main one and a few child windows.

If I create 20 child windows with google.com open from the main process it spawns around 23 Electron processes(one per each window + GPU process + something else) and consumes around 800 MB in total of memory on my Windows 10 machine. Which is obviously a lot.

const {app, BrowserWindow} = require('electron')    let mainWindow    const webPreferences = {    sandbox: true  };    function createWindow () {    mainWindow = new BrowserWindow({      width: 800,      height: 600,      webPreferences    })      mainWindow.loadFile('index.html')      for (var t = 0; t < 20; t++) {      const childWindow = new BrowserWindow({        webPreferences      })        childWindow.loadURL('https://google.com')    }  }    app.on('ready', createWindow)  

Task Manager with 23 Electron processes

I know this is the way Chromium works - each tab is a separate process so if one is broken the whole browser and other tabs are alive. I have no doubt about that but I've noticed one interesting thing. If I use native window.open as described here it mysteriously spawns only 4 processes. Somehow it combines all "window" processes into a single one + GPU + something else which consumes 400 MB in total which is much better result.

const {app, BrowserWindow} = require('electron')    let mainWindow    const webPreferences = {    sandbox: true // without sandboxing it spawns 23 processes again :(  };    function createWindow () {    mainWindow = new BrowserWindow({      width: 800,      height: 600,      webPreferences    })      mainWindow.loadFile('index.html')      mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options) => {      event.preventDefault()      const win = new BrowserWindow({        ...options,        show: false,        webPreferences      })      win.once('ready-to-show', () => win.show())      if (!options.webContents) {        win.loadURL(url) // existing webContents will be navigated automatically      }      event.newGuest = win    })  }    app.on('ready', createWindow)  

And index.html

<!DOCTYPE html>  <html>    <head>      <meta charset="UTF-8">      <title>Hello World!</title>    </head>    <body>      <h1>Hello World!</h1>      <script>          for (var t = 0; t < 20; t++) {              window.open('https://google.com');          }      </script>    </body>  </html>  

Task Manager with 4 Electron processes

Is there any way to have only single process for all child windows if I create them from the main process(first snippet)? It would be great if someone could explain why it works that way.

P.S. I'm using electron fiddler with Electron 6.0.2 runtime to run these snippets

SignalR in ReactJS page works just with reload

Posted: 27 Sep 2021 08:17 AM PDT

I use signalr in React.Js and have a problem that when I go to the pages by clicking the menu link and redirect with Route, it is not working. The back-end singleton class constructor is not called, but when I refresh a page or type the route manually in the address bar, it is works and connects to the back-end.

    import $ from "jquery";      window.jQuery = $;      require("signalr");        {componentDidMount() {          var connection = $.hubConnection("http://localhost:1425/");          proxy = connection.createHubProxy("myHub");            connection              .start({ withCredentials: false })              .done(function () {                  console.log("Now connected, connection ID=" + connection.id);              })              .fail(function () {                  console.log("Could not connect");              });        }  

Why does this happen and can anyone guide me on how should I fix that?

Paginate result using select 2 ajax remote data

Posted: 27 Sep 2021 08:17 AM PDT

Trying to paginate ajax data using Select2 (v 4.0.6.rc1) so that the user can find more results if not present in the first limit ,using the following but not retrieving data.I 'll appreciate if someone helps me out,there is not much of examples about pagination.

i was trying to paginate data using the help of this question Select2 v4 how to paginate results using AJAX its not seems to be working,getting the array but not correct format.

JS:

  $('#compose_username').select2({          dropdownParent: $("#modal-compose") ,          placeholder: "Search Username...",          minimumInputLength: 1,          ajax: {              url: "username.php",              dataType: 'json',              delay: 250,              cache: false,              data: function (params) {                  return {                      term: params.term,                      page: params.page || 1                                            //a: params.term, // search term                      //psf: params.page                  };              },              processResults: function(data) {                  console.log(data);                  var result = $.map(data, function (item) { return { id: item.id, text: item.username }});                  return { results: result };              }          }    });  

PHP

    try{           $page= $_GET['page'];          // $resultCount = 10;          // $offset = ($page - 1) * $resultCount;    $pageLength = 20;    $pageStart = ($page - 1) * $pageLength;    $pageEnd = $pageStart + $pageLength;              $stmt = $db_con->query("SELECT id,first_name FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}");          $count = $db_con->query("SELECT count(first_name) FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}")->fetchColumn();;          $stmt->execute();              $json = [];              while($row = $stmt->fetch(PDO::FETCH_ASSOC)){                   $json[] = ['id'=>$row['id'], 'username'=>$row['first_name']];              }      $endCount = $pageStart + $pageLength;      $morePages = $endCount > $count;              $results = array(    "results" => $json,    "pagination" => array(      "more" => $morePages    )  );                        echo json_encode($results);      }      catch(PDOException $e){          echo $e->getMessage();      }  

Can't see indexedDB database in mozilla developer tools

Posted: 27 Sep 2021 08:17 AM PDT

I can't see the DB I created in indexedDB in Mozilla developer tools. The DB is properly created and with data stored in it because it's possible to retrive them, but doesn't appear in the tools section for indexedDB. Does anybody know why is that and/or how to solve it? Is Mozilla v.40 Thanks in advance.

Javascript remove all occurrence of duplicate element, leaving the only one that is unique

Posted: 27 Sep 2021 08:16 AM PDT

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 which is only unique in the array(removing both 2s, because they occur more than once).

I have tried with following code, but surely it doesnot work as expected.

var firstArrTemp = [2,3,2];  var sorted_arr = firstArrTemp.sort();  var unique_element;  for (var i = 0; i < sorted_arr.length - 1; i++) {      if (sorted_arr[i + 1] != sorted_arr[i]) {          unique_element=sorted_arr[i];      }  }    alert(unique_element);  

Thanks!

No comments:

Post a Comment