Saturday, March 27, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


how can i rung a single .py file when i have multiple .py files in a single project file?

Posted: 27 Mar 2021 08:19 AM PDT

I've been working on OpenCV by PyCharm.</ Since I'm practicing, I had to generate a lot of project files in order to study a lot of different tasks. But making a new project file whenever I start a file is quite a hassle... Is there any way to run a single .pv file in a project file which has one or more .py files?

How to resolve Abort trap: 6 ERROR - xcode 12

Posted: 27 Mar 2021 08:19 AM PDT

We have faced the issue of "abort trap 6" in Xcode 12. Due to this reason app not running using Xcode 12. We are using the swift 5 versions and jsqmessageviewcontroller objective c library. Below errors getting in Xcode 12. :0: error: fatal error encountered while reading from module 'wwww'; please file a bug report with your project and the crash log :0: note: module 'wwww' full misc version is '5.3.2(5.3.2)/Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)' top-level value not found Cross-reference to module 'JSQMessagesViewController' ... JSQMessageMediaData error: Abort trap: 6 (in target 'zapwww' from project 'zapwww')

if anyone has a solution then please help us.

Thank you

Spring Entity Manager with H2 error: NULL not allowed for column “EMPLOYEE_ID” error

Posted: 27 Mar 2021 08:19 AM PDT

I got this error when I tried to insert a value using the POST method in soapUI. Values are inserted in Database when I write insert queries but the POST method does not work in soapUI.

NULL not allowed for column "EMPLOYEE_ID"; SQL statement:

I have both my entity classes here

Employee.java:

@Entity  @Table(name="EMPLOYEE")  public class Employee{    @Id  @GeneratedValue(strategy=Generation.IDENTITY)  @Column(name="EMPLOYEE_ID", updatable= false, nullable= false)  private long employeeId;    @Column(name="NAME")  private String name;    @Column(name="EMAIL_ID")  private String email;    @OneToMany(cascade=cascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "employee")  private List<Address> address = new ArrayList<Address>();    //Getters and Setters  

Address.java:

@Entity  @Table(name="ADDRESS")  public class Address{    @Id  @GeneratedValue(strategy=Generation.IDENTITY)  @Column(name="ADDRESS_ID")  private long addressId;    @Column(name="ADDRESS_LINE_1")  private String addressLine1;    @Column(name="CITY")  private String city;    @Column(name="STATE")  private String state;    @Column(name="COUNTRY")  private String country;    @Column(name="PINCODE")  private int pincode;    @ManyToOne(fetch = FetchType.LAZY)  @JoinColumn(name="EMPLOYEE_ID", nullable = false)  private Employee employee;        //Getters and Setters  

I tried to post the below value through soapUI POST method.

{     "name": "Ron",   "email": "ron@gmail.com",   "address": [           {             "addressLine1": "No 21",             "city": "Chennai",             "state": "Tamil Nadu",             "country": "India",             "pincode": 187            },                {             "addressLine1": "No 90",             "city": "Banglore",             "state": "Karnataka",             "country": "India",             "pincode": 187            }          ]  }  

When I try to insert the above, I get the error that NULL not allowed for column "EMPLOYEE_ID"; SQL statement. When I remove nullable = false, the values are inserted without the foreign key i.e. EMPLOYEE_ID being inserted as null.

PrimeNG missing date value after export as EXCEL

Posted: 27 Mar 2021 08:19 AM PDT

I have a nice looking table result with dates enter image description here

The export feature reference the official doc https://www.primefaces.org/primeng/showcase/#/table/export. Sadly there ain't any example on date field.

Below is my template

<p-table [columns]="appResults.output.cols" [value]="appResults.output.data">                  <ng-template pTemplate="caption">                  <div class="p-d-flex">                    <button type="button" pButton pRipple icon="pi pi-file-excel" (click)="exportExcel()"                      class="p-button-success p-mr-2" pTooltip="XLS" tooltipPosition="bottom"></button>                  </div>                </ng-template>                  <ng-template pTemplate="header" let-columns>                  <tr>                    <th *ngFor="let col of columns">                      {{col.header}}                    </th>                  </tr>                </ng-template>                <ng-template pTemplate="body" let-rowData let-columns="columns">                  <tr>                    <td *ngFor="let col of columns" [ngSwitch]="col.type">                      <div *ngSwitchCase="'currency'" align="right">{{rowData[col.field].toFixed(2)}}                      </div>                      <div *ngSwitchCase="'number'" align="right">{{rowData[col.field]}}</div>                      <div *ngSwitchCase="'string'">{{rowData[col.field]}}</div>                      <div *ngSwitchCase="'boolean'">{{rowData[col.field]? "Y":"N"}}</div>                      <div *ngSwitchCase="'date'">{{rowData[col.field].seconds * 1000|date:'MMM d, yyyy' }}</div>                      <div *ngSwitchCase="'timestamp'">{{rowData[col.field].seconds * 1000|date:'MMM d, yyyy HH:mm:ss' }}                      </div>                      <div *ngSwitchCase="'checkbox'" align="center">{{rowData[col.field]? "Y":"N"}}</div>                        <!-- note: geoPoints is currently not supported in export. Content will be BLANK in exported file, expected behaviour -->                      <div *ngSwitchCase="'geopoints'" align="center">                        <div *ngIf="rowData[col.field]">                          <a href="https://www.google.com/maps/place/{{rowData[col.field].latitude}},{{rowData[col.field].longitude}}/@18"                            target="_blank">location</a>                        </div>                      </div>                      <div *ngSwitchCase="'link'">                        <a href="{{rowData[col.field]}}" target="_blank">{{col.label}}</a>                      </div>                    </td>                  </tr>                </ng-template>              </p-table>  

Sorry for the lengthy code chunk and the only focus is the date field

 <div *ngSwitchCase="'date'">{{rowData[col.field].seconds * 1000|date:'MMM d, yyyy' }}</div>  

The data are displayed correctly in the webpage. But once downloaded into EXCEL the date field just BLANK enter image description here

Below is the export logic

exportExcel() {      import("xlsx").then(xlsx => {        const worksheet = xlsx.utils.json_to_sheet(this.appResults.output.data);        const workbook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };        const excelBuffer: any = xlsx.write(workbook, { bookType: 'xlsx', type: 'array' });        this.saveAsExcelFile(excelBuffer, "Results");      });    }  

What's a way to store a boolean expression for an object? It has to store references to booleans, and need to be able to be changed programatically

Posted: 27 Mar 2021 08:19 AM PDT

tl;dr: I want a class that holds booleans (i.e. A = true, B = false, C = false). I want objects that evaluate to true or false based on combinations of the booleans of that class (e.g. A = true, A & B = false, A & !B = true). I want the objects to hold the expressions themselves, not the result, as the main class won't define A, B or C until later on. I want the objects to be able to change their expression (e.g. take A & B and add it B & !C so the expression is now (A & B) & (B & !C). And finally, I want to be able to calculate the probability of these objects evaluating to true, assuming each boolean is a 50/50.

Long version:

Ok, this problem is a bit specific, a bit odd and a bit long so let me explain:

I have a class (let's call it "universe") that holds n number of bool variables in a dictionary. Now, we have a class (let's call it "object") which has a method Evaluate() that will evaluate to true if its boolean expression is true.

In practice, this means that we have a universe with booleans A, B and C. And we have a series of objects with different boolean expressions:

object1: A (will evaluate to true if A is true);

object2: !A (will evaluate to true if A is false);

object3: A & B (will evaluate to true if both A and B are true);

object4: A & (!B & !C) (will evaluate to true if A is true and if both B and C are false.

object5: A & !(!B & !C) (will evaluate to true if A is true, and (both B and C being false) is false itself.

Now, it is also possible for us to modify the boolean expression of any of those objects at any point (for example, we can change object3 to be the inverse of what it is now A & B -> !(A & B), and we can change it once more to also require C & B -> (C & B) & (A & B).

Remember that those A B and C values are actually entries in a dictionary of bools. My original idea was to implement two classes, BoolValue and BoolPair, that would work as such:

BoolValue has the ID of the bool (for example A) and whether it's equal or not equal (it can be A or !A), and a function Evaluate() that will search the bool in the dictionary and return its value (or its reverse if it's not equal).

BoolPair inherits from BoolValue (so it's a value itself) and takes two BoolValues instead of a reference, and will Evaluate() to true if both BoolValues evaluate to true.

Now, applying this implementation, these are the boolean fields of the objects:

object1: new BoolValue("A", true);

object2: new BoolValue("A", false);

object3: new BoolPair(new BoolValue("A", true), new BoolValue("B", true), true);

object4: new BoolPair(new BoolValue("A", true), new BoolPair(new BoolValue("B", false), new BoolValue("C", false), true), true)

object5: new BoolPair(new BoolValue("A", true), new BoolPair(new BoolValue("B", false), new BoolValue("C", false), false), true)

This implementation works, but I feel like I'm making it too complex and there must be a far easier solution for this. It also has the problem that I have absolutely no idea how I'd calculate the probability of an expression being true (each boolean being true or false is a 50/50).

The programming language is irrelevant as long as it can be translated to common languages.

How does Python Tkinter Pyscard realize real-time recognition of PCSC card readers?

Posted: 27 Mar 2021 08:18 AM PDT

This problem may be unprofessional, but I can't solve it. I use python tkinter gui to connect pcsc card reader on win10 system, every time I need to insert the card reader first and then run python program to work normally. But I need to run the python program first, and then insert the card reader, the program can detect the change of the card reader.

            # imports              import tkinter as tk              import tkinter.scrolledtext as tkst              from tkinter import Menu              from tkinter import ttk              from tkinter import messagebox                            from smartcard.System import readers              from smartcard.util import toHexString, toBytes                                          # Click a exit menu              def clickExit():                  win.quit()                  win.destroy()                  exit()                                          # Click a abount menu              def clickAbout():                  messagebox.showinfo('About', 'About...')                                          # Click a reset button              def clickReset():                  try:                      for r in readers():                          if r.name == reader_name.get():                              connection = r.createConnection()                              connection.connect()                              stLog.insert(tk.INSERT, 'ATR: ' + toHexString(connection.getATR()) + '\n')                              stLog.see(tk.END)                              return connection                  except:                      messagebox.showinfo('Error', 'Please check a card or readers...')                      return                                          # Click a send button              def clickSend(connection):                  apdu = toBytes(entryCommand.get())                  response, sw1, sw2 = connection.transmit(apdu)                  # print('response: ', response, ' status words: ', "%x %x" % (sw1, sw2))                  capdu = '< ' + toHexString(apdu) + '\n'                  rapdu = '> ' + toHexString(response) + '\n> {:02X}'.format(sw1) + ' {:02X}'.format(sw2) + '\n'                  stLog.insert(tk.INSERT, capdu + rapdu)                  stLog.see(tk.END)                                          if __name__ == '__main__':                  connection = None                  win = tk.Tk()  # Create instance                  win.title('Manager')  # Add a title                                labelReader = ttk.Label(win, text='Reader')                  labelReader.grid(column=0, row=0)                                reader_name = tk.StringVar()  # String variable                  comboReader = ttk.Combobox(win, width=30, state='readonly', textvariable=reader_name)  # Create a combobox                  comboReader.grid(column=1, row=0)                  comboReader['values'] = readers()                  try:                      comboReader.current(0)                  except:                      pass                                buttonReset = ttk.Button(win, text='Reset...', command=clickReset)  # Create a button                  buttonReset.grid(column=2, row=0)                                stLog = tkst.ScrolledText(win, width=50, height=20, wrap=tk.WORD)  # Create a scrolledtext                  stLog.grid(column=0, row=1, columnspan=3)                                entryCommand = tk.Entry(win, width=40)  # Create a entry                  entryCommand.grid(column=0, row=2, columnspan=2)                  entryCommand.focus_set()                                buttonCommand = ttk.Button(win, text='Send...', command=lambda: clickSend(connection))  # Create a button                  buttonCommand.grid(column=2, row=2)                                menuBar = Menu(win)  # Create a menu                  win.config(menu=menuBar)                                fileMenu = Menu(menuBar, tearoff=0)  # Create the File Menu                  fileMenu.add_command(label="Exit", command=clickExit)  # Add the "Exit" menu and bind a function                  menuBar.add_cascade(label="File", menu=fileMenu)                                helpMenu = Menu(menuBar, tearoff=0)                  helpMenu.add_command(label="About", command=clickAbout)  # Add the "About" menu and bind a function                  menuBar.add_cascade(label="Help", menu=helpMenu)                                connection = clickReset()                                win.resizable(0, 0)  # Disable resizing the GUI                  win.mainloop()  # Start GUI  

Android 11 - Anyone else noticed SetFitsSystemWindows not working?

Posted: 27 Mar 2021 08:18 AM PDT

I have a simple code, I ran it on all android versions (from Lollipop and greater) and it works

if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)  {     Window.AddFlags(WindowManagerFlags.LayoutNoLimits);     Window.AddFlags(WindowManagerFlags.LayoutInScreen);                     Window.DecorView.SetFitsSystemWindows(true);  }  

Result:

enter image description here

When I ran it on Android 11, the Results are the following

enter image description here

Did anyone else notice that?

Any idea of how to correct this behaviour?

Why is my data is not updating in my flask sqlalchemy?

Posted: 27 Mar 2021 08:18 AM PDT

I used wtforms for my input data. Now, When I am calling the edit route, the data I want to edit is showing to my inputs, but when I submitting it, it keeps adding a data not updating the specific data.

routes.py:

@app.route("/edit/<int:expense_id>", methods=['GET', 'POST'])  def edit(expense_id):      form = ExpenseForm()      expense = Expenses.query.get(expense_id)      budget = Budgets.query.filter_by(id=expense.budget_id).first()      posted_expenses = Expenses.query.filter_by(budget_id=budget.id)      form.categories.data = expense.categories      form.cost.data = expense.category_cost      if form.validate_on_submit():          expense.categories = form.categories.data          expense.category_cost = form.cost.data          db.session.commit()        return render_template("expenses.html", budget=budget, form=form, posted_expenses=posted_expenses, expense=expense)  

html:

                        {% for post in posted_expenses %}                              <tr>                                  <td>{{ post.id }}</td>                                  <td>{{ post.categories }}</td>                                  <td>{{ "{:,.2f}".format(post.category_cost|float) }}</td>                                  <td>{{ post.category_date.strftime('%Y-%m-%d') }}</td>                                  <td><a href="{{ url_for('edit', expense_id=post.id )}}">Edit</a><a href="">Delete</a></td>                              </tr>                          {% endfor %}                      </tbody>                      <form action="{{ url_for('expenses', budget_id=budget.id )}}" method="POST">                          {{ form.csrf_token }}                          <tbody class="table-input">                              <tr>                                  <td>                                      {{ form.categories.label }}                                  </td>                                  <td>                                      {{ form.categories }}                                  </td>                                  <td>                                      {{ form.cost.label }}                                  </td>                                  <td>                                      {{ form.cost }}                                  </td>                                  <td>                                      {{ form.submit }}                                  </td>                              </tr>                          </tbody>                      </form>   

I also try to use return redirect in my if but nothing happens.

R ggmap overlay geom_contour

Posted: 27 Mar 2021 08:18 AM PDT

given this reproducible example

# set the origin of the grid   # in cartesian coordinates (epsg 32632)  xmin<-742966  ymin<-5037923    # set x and y axis  x<-seq(xmin, xmin+25*39, by=25)  y<-seq(ymin, ymin+25*39, by =25)    # define a 40 x 40 grid  mygrid<-expand.grid(x = x, y = y)    # set the z value to be interpolated by the contour  set.seed(123)  mygrid$z<- rnorm(nrow(mygrid))    library(tidyverse)    # plot of contour is fine  ggplot(data=mygrid, aes(x=x,y=y,z=z))+    geom_contour()    library(ggspatial)    # transform coordinates to wgs84 4326  # (one of the possible many other ways to do it)  mygrid_4326<-xy_transform(mygrid$x, mygrid$y, from = 32632, to = 4326)    # create new grid with lon and lat   # (geographical coordinates espg 4326)  mygrid_4326<-mygrid_4326%>%    mutate(z=mygrid$z)    # define the bounding box  my_bb<-c(min(mygrid_4326$x), min(mygrid_4326$y),            max(mygrid_4326$x), max(mygrid_4326$y))  names(my_bb)<-c('left', 'bottom', 'right', 'top')    library(ggmap)    # get the background map (by a free provider)  mymap<-get_stamenmap(bbox = c(left = my_bb[['left']],                                 bottom = my_bb[['bottom']],                                 right = my_bb[['right']],                                 top = my_bb[['top']]),                        zoom = 15,                        maptype = 'toner-lite')    # plot of the map is fine  mymap%>%    ggmap()    # overlay the contour of z is failing  mymap%>%    ggmap()+    #geom_contour(data=mygrid_4326, mapping=aes(x = x, y = y, z = z))    stat_contour(data=mygrid_4326, mapping=aes(x = x, y = y, z = z))    Warning messages:  1: stat_contour(): Zero contours were generated   2: In min(x) : no non-missing arguments to min; returning Inf  3: In max(x) : no non-missing arguments to max; returning -Inf  

Now I'm searching for a viable solution to accomplish the overlay of a contour plot made with ggplot to a base map made with ggmap; it seems not possible for some reasons I do not fully understand;

might it be related to the transformation of coordinates affecting somehow the shape of the grid (becoming not perfectly regular)?

This post: Plotting contours on map using ggmap seems close to the core of the problem but not yet giving a definitive solution (if it exists)

If possibile I would like to stay within the ggplot (tidyverse) facilities without resorting to the base R's functions (e.g. contourLines).

Thank you for your help

What is the difference between arrow function and normal function? [duplicate]

Posted: 27 Mar 2021 08:19 AM PDT

I am still new to Javascript and right now I am in arrow function and high order function. When I see arrow function, they give me example like var Multiply = function(x,y) => .... ,

What is the difference between the code that I gave and the normal code which is Multiply(x,y). What is the difference in usage and when should I use the arrow function instead of the normal function?

Predefined layout not being used by advance slides api on slide create

Posted: 27 Mar 2021 08:18 AM PDT

This is my first almost successful addon. It is a standalone script. I have tested it on several slide decks created by others. In the latest test the Table of Contents which my code creates used a master/layout from the deck rather than the BLANK predefined one I called for in my code?

/**      not using blank predefined blank master      MINI TEST   */  function miniTest()  {    const pres = SlidesApp.getActivePresentation();    const presId = pres.getId();    let updtReqArr = [];    // create request for a Slide to hold the table of contents    let insertIdx = 0;    pageId = miniPage(updtReqArr, insertIdx);     if (updtReqArr.length > 0) {      response = Slides.Presentations.batchUpdate({ 'requests': updtReqArr }, presId);    }  }    /**   * create request for a Slide to hold the table of contents   */  function miniPage(updtReqArr, insertIdx) {    //  console.log('Begin createTocPage - insertIdx: ', insertIdx );     pageId = Utilities.getUuid();    //  console.log('pageId: ', pageId);      //  base slide object request    slideObj = [{      'createSlide': {        'objectId': pageId,        'insertionIndex': insertIdx,        'slideLayoutReference': {          'predefinedLayout': 'BLANK'   // name of master        }      }    }];    //  console.log('slideObj: ', JSON.stringify(slideObj));      updtReqArr.push(slideObj);    //  console.log('updtReqArr.length: ', updtReqArr.length);  //  code that creates page elments, background, etc. removed for simplicity         return pageId;  }  

The presentation upon which I encountered this problem was a copy of the GEG Eduprotocols presentation. This is the link to my copy. https://docs.google.com/presentation/d/1EEUDz0fBXnI4IBT8xlcKJrfPs_KMr5HIY2YfCjDLiuQ/edit?usp=sharing This is the publicly available source https://docs.google.com/presentation/d/1i5Hhod8ERu8dfmMk5f-pcuFGHZ6bc96JAe3Pca_rbxY/edit#slide=id.p

The creators used Slidesmania masters and those masters are showing up in the Table of Contents which I added even though I said use BLANK. What am I doing wrong?

How can I produce matrixes automatically in Python?

Posted: 27 Mar 2021 08:19 AM PDT

I have

x = np.linspace(0, 1, 6)  y = np.linspace(0, 1, 9)  

How can I have a matrix 7x10 from (x,y) but each row becomes from the previous one by adding 1? For example, the first row is

0,1,2,3,4,5,6

the second row

1,2,3,4,5,6,7

and so on

How to print with awk the number of consonants and vowels from files?

Posted: 27 Mar 2021 08:19 AM PDT

I am trying to count the occurrences of consonants and vowels in files with awk.I want to use awk for al three files. For example for these 3 files
file1:
hallO Rt
bye r

dfgT12

file2:
234
j tr
aEI

file3:
rtg


byye
the output should look like this:
file1 12 3
file2 3 3
file3 6 1
the first number represents the occurrences of the consonants and the second stands for the vowels.

right-shifting unsigned char is filling with ones?

Posted: 27 Mar 2021 08:20 AM PDT

On my system, (unsigned char) -1 is (expectedly for chars of 8 bits) 1111 1111 in binary (255 decimal).

Similarly, (unsigned char) -1 >> 1 is as expected 0111 1111. The left was filled with a zero.

~((unsigned char) -1 >> 1) is 1000 0000 as expected.

Now I want to generate the unsigned char 0010 0000 for example.

I tried ~((unsigned char) -1 >> 1) >> 2, but this outputs 1110 0000 .... what the? Why is the left being filled with ones all of a sudden?


How can I generate an unsigned char with the nth bit (from the left) enabled?

I would like

n   unsigned char  0   1000 0000  1   0100 0000  2   0010 0000  3   0001 0000  ...   7   0000 0001  

At the moment, ~((unsigned char) -1 >> 1) >> n is giving me

n   unsigned char  0   1000 0000  1   1100 0000  2   1110 0000  3   1111 0000  ...   7   1111 1111  

This problem exists for uint8_t, uint16_t, but no longer happens at uint32_t and greater.

how to solve the problem with the code in the image?

Posted: 27 Mar 2021 08:19 AM PDT

anyone can help me to solve this problem androidmanifest.xml

MainActivity.kt

Is it possible to change the libc for cpp program without source?

Posted: 27 Mar 2021 08:19 AM PDT

I have built and installed another glibc from source, and I want to have existing executables written in c++ to run with the custom glibc. In order to do this, i tried to change the loader of the executable. Firstly, a link named ld_linux-x86-64.so.2 was created under /lib64 , with its path pointing to the new loader

-rwxr-xr-x 2 ubuntu ubuntu 2203752 Mar 20 11:34 /lib64/ld_linux-x86-64.so.2  lrwxrwxrwx 1 root   root        32 Dec  8 00:38 /lib64/ld-linux-x86-64.so.2 -> /lib/x86_64-linux-gnu/ld-2.27.so  

Secondly, the loader path in the executable was modified via text editor, changing '/lib64/ld-linux-x86-64.so.2' into '/lib64/ld_linux-x86-64.so.2'. I launched the executable and got the following error:

./demo_cpp: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory  

The patched cpp program failed to run and it seems that the c++ std lib is missing. However, this method did work for program written by pure C. Using the method mentioned here, i tried the following command and get the exactly same error:

patchelf --set-interpreter /home/ubuntu/glibc-2.27-amd64/lib/ld-linux-x86-64.so.2 --set-rpath /home/ubuntu/glibc-2.27-amd64/lib demo_cpp  

So I wonder if it is possible to change glibc for a cpp program? Do i need to build cpp std lib from source too? If so, how to patch the newly created libstdc++ for cpp program?

Conditional AJAX in Ruby On Rails

Posted: 27 Mar 2021 08:18 AM PDT

I am looking to trigger an AJAX action depending on the location/page of the user. I built the following:

if (window.location.href.indexOf('users/stream') >= 0) {    alert("Condition 1 is met")    $('#invite_to_video').html("<%= j render partial: 'messages/contact_ir_video', :locals => {:message => Message.new}  %>");  } else {    alert("Condition 2 is met")    $("#comments").html("<%= j render partial: '@message.comments' %>");  }  

When I simply try the if condition with the alert, it works well and Condition 1 is met is displayed.

However when I add the partial loading instructions I get the following:

ActionView::Template::Error (Missing partial messages/@message.comments, application/@message.comments with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :slim, :coffee, :jbuilder]}. Searched in:...

Although, it should only be condition 1 that triggers.

What would be the best way to do such conditional jQuery?

AppleScript: How to delete file and then add 1% to the progress bar?

Posted: 27 Mar 2021 08:19 AM PDT

So I have this code:

set theImages to choose file with prompt "Please select some images to process:" of type {"public.image"} with multiple selections allowed    -- Update the initial progress information  set theImageCount to length of theImages  set progress total steps to theImageCount  set progress completed steps to 0  set progress description to "Processing..."  set progress additional description to "Preparing to process your images..."    repeat with a from 1 to length of theImages      -- Update the progress detail      set progress additional description to "Processing image " & a & "/" & theImageCount            -- Increment the progress      set progress completed steps to a            -- Pause for demonstration purposes, so progress can be seen      delay (random number from 0.01 to 0.7)            repeat with b in theImages          tell application "Finder"              try                  delete b              end try          end tell      end repeat  end repeat    -- Reset the progress information  set progress total steps to 0  set progress completed steps to 0  set progress description to ""  set progress additional description to ""    display notification "All images were processed succesfully!" with title "Image Processer" subtitle "Images processed succesfully!" sound name "Frog"  

And it is supposed to delete a file then add 1% to the progress bar but instead it deletes them all first then the progress bar does it's thing. How do I fix this?

vb.net CheckedListbox get value from database

Posted: 27 Mar 2021 08:18 AM PDT

I am populating a CheckedListBox from a MsAccess database table. The table consists of two fields, Terms and RegX. I want to display Terms but when I submit I want to get the value form the RegX field.

Public Function GetMyTable() As DataTable          ' Create new DataTable instance.          Dim table As New DataTable            Dim strSql As String = "SELECT * FROM Keywords ORDER BY Terms ASC"            Dim cmd As New OleDbCommand(strSql, con)          Using dr As OleDbDataReader = cmd.ExecuteReader              table.Load(dr)          End Using            Return table      End Function    Private Sub SearchInDoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load            Dim dt1 As DataTable = GetMyTable()            If dt1.Rows.Count > 0 Then              For i As Integer = 0 To dt1.Rows.Count - 1                  CheckedListBox1.Items.Add(CStr(dt1.Rows(i).Item("Terms")), False)              Next          End If          CheckedListBox1.CheckOnClick = True      End Sub  

I dont know how to return the value of RegX when I click my Submit button

Update argparse namespace with other namespace/dictionary in Python

Posted: 27 Mar 2021 08:19 AM PDT

Let's say I have two argparse namespaces

parser1 = argparse.ArgumentParser()  parser1.add_argument('--name', type=str, required=False, default='John')    args1 = parser1.parse_args()    parser2 = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)  parser2.add_argument('--name', type=str, required=False)    args2 = parser2.parse_args()  

How can I update args1 with args2? I am aware of updating dicts, i.e.

dict = {'name': 'Pete'}  dict.update(**vars(args2))  

This should work I think (not tested), but can you also update an argparse namespace with another namespace? I would be fine with converting args2 to a dict to be able to update.

Fastled not enough CPU power?

Posted: 27 Mar 2021 08:19 AM PDT

I was wondering if someone could help me out?

I have a 5M ledstrip (300 leds) and running the following code on my ESP32. The code will make a led light spinning around!

void spinningwheel(){  int random_number;  int spin_speed;  for(int i =0; i < 1; i++){  random_number = random(NUM_LEDS);  }    Serial.println(random_number);  for (int i = 0; i <= random(6,15); i++){  spin_speed = i+1;  for (int i = 0; i <= NUM_LEDS; i++){  leds[i] = CRGB ( 0, 0, 255);  leds[i-10] = CRGB ( 0, 0, 0);  FastLED.show();  delay(spin_speed);  }  FastLED.clear();    }  for (int i = 0; i <= random_number; i++){  leds[i] = CRGB ( 0, 0, 255);  leds[i-10] = CRGB ( 0, 0, 0);  FastLED.show();  delay(spin_speed);  }  FastLED.clear();  delay(1000);  }  

The code is working fine if i use leds[i-3] = CRGB ( 0, 0, 0); But when i change the number i-3 to something like i-10 ill get a error in my Serial port

15:51:36.233 -> 258  15:51:36.267 -> Guru Meditation Error: Core  1 panic'ed (StoreProhibited).   Exception was unhandled.  15:51:36.335 -> Core 1 register dump:  15:51:36.368 -> PC      : 0x400d12ae  PS      : 0x00060930  A0      :   0x800d1658  A1      : 0x3ffb1e80    15:51:36.469 -> A2      : 0x3ffc0124  A3      : 0x3ffb1ea4  A4      :   0x3ffc04bc  A5      : 0x3ffb1eb0    15:51:36.571 -> A6      : 0x00000000  A7      : 0x3ffb0060  A8      :   0x00000000  A9      : 0x3ffb1e40    15:51:36.639 -> A10     : 0x00000001  A11     : 0x00000000  A12     :   0x3ffb8570  A13     : 0x00000000    15:51:36.742 -> A14     : 0x3ffb8528  A15     : 0x00000000  SAR     :   0x00000020  EXCCAUSE: 0x0000001d    15:51:36.843 -> EXCVADDR: 0x00000000  LBEG    : 0x400d0dfd  LEND    :   0x400d0e0c  LCOUNT  : 0x00000000    15:51:36.944 ->   15:51:36.944 -> Backtrace: 0x400d12ae:0x3ffb1e80 0x400d1655:0x3ffb1ea0   0x400d1741:0x3ffb1ee0 0x400d0ee0:0x3ffb1f20 0x400d0fe1:0x3ffb1f40   0x400d115e:0x3ffb1f70 0x400d118f:0x3ffb1f90 0x400d216d:0x3ffb1fb0   0x40088215:0x3ffb1fd0  15:51:37.147 ->   15:51:37.147 -> Rebooting...  15:51:37.180 -> :⸮⸮⸮⸮L⸮⸮1⸮m֊⸮1  HL⸮⸮b⸮⸮⸮  

DECODE OF THE ERROR

PC: 0x400d12ae: ClocklessController14, 60, 150, 90, (EOrder)66, 0, false,   5>::showPixels(PixelController(EOrder)66, 1, 4294967295u>&) at   D:\Documenten\Arduino\libraries\FastLED/controller.h line 178  EXCVADDR: 0x00000000    Decoding stack results  0x400d12ae: ClocklessController14, 60, 150, 90, (EOrder)66, 0, false,   5>::showPixels(PixelController(EOrder)66, 1, 4294967295u>&) at   D:\Documenten\Arduino\libraries\FastLED/controller.h line 178  0x400d1655: CPixelLEDController(EOrder)66, 1, 4294967295u>::show(CRGB const*,   int, CRGB) at D:\Documenten\Arduino\libraries\FastLED/controller.h line 408  0x400d1741: CFastLED::show(unsigned char) at   D:\Documenten\Arduino\libraries\FastLED/controller.h line 90  0x400d0ee0: CFastLED::show() at   D:\Documenten\Arduino\libraries\FastLED/FastLED.h line 500  0x400d0fe1: spinningwheel() at   D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino line 48  0x400d115e: Binair_buttons() at   D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino line 125  0x400d118f: loop() at D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino   line 141  0x400d216d: loopTask(void*) at   C:\Users\....\AppData\Local\Arduino15\packages\esp32\  hardware\esp32\1.0.4\cores\esp32\main.cpp line 19  0x40088215: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-   builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c line 143  

Can someone please explain me what i am doing wrong? Or did i passed the max RAM or CPU usage.

Cannot access a disposed context instance EF core

Posted: 27 Mar 2021 08:19 AM PDT

I am developing a CRM by .net core mvc and EF which needs a lot of DB connection to retrieve and update information. From time to time I face this error during debugging, this is a big project with a lot of users I don't know how it will work in real usage!

Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.\r\nObject name: 'XXX'.

before I used this setting in startup.cs:

services.AddDbContext<XXX>                  (option =>                   option.UseSqlServer(Configuration.GetConnectionString("YYY"))                  .ServiceLifetime.Singleton);  

that setting was lead to another error occasionally:

System.InvalidOperationException: The instance of entity type 'TblZZZ' cannot be tracked because another instance with the same key value for {'ZZZId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

so I have changed my setting to:

services.AddDbContext<XXX>                  (option =>                   option.UseSqlServer(Configuration.GetConnectionString("YYY"))                  .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));  

now I am facing the Cannot access a disposed context instance. I don't know what setting can solve my issue.

I m using net5.0

Update: my partial class:

public partial class TblXXX      {          private ZZZ context;//context          public TblXXX(ZZZ _context)          {              context = _context;          }          public TblXXX() { }  //function for check username     public bool CheckUsernameExit(string username) {              var u = context.TblXXX                  .Where(e => e.Username == username)                  .FirstOrDefault();              return (u != null);          }  }  

in my controller:

  public IActionResult Check(UserModelView user)          {              if (ModelState.IsValid)              {                  var r = _viewModel.tblXXX.CheckUsernameExit(user.tblXXX.Username);                  if (r)                  {                      toastNotification.AddErrorToastMessage("This email is in use. Enter differernt email.");                                         return View("Create", _viewModel);                  }                

and this is my ViewModel:

 public class UserModelView      {          public TblXXX tblXXX { get; set; }          public List<TblXXX > tblXXXList { get; set; }      }              

this is one of the cases I face the error.

How to get the document id from the field value in firestore flutter?

Posted: 27 Mar 2021 08:18 AM PDT

I want to get the document id from the field value I firebase firestore to add another value later. enter image description here

I can get field name using this code here:

Future<QuerySnapshot> getUserInfo(String username) async {      return await FirebaseFirestore.instance          .collection("Info")          .where("fname", isEqualTo: username)          .get();  

but I want to add another value to it. how do i do it.

Add a custom label and tick to categorical y-axis of tile-plot in ggplot2

Posted: 27 Mar 2021 08:18 AM PDT

I would like to add another row of empty tiles to my tile plot shown below for "No.14" bars. There would be no data for that row, so just adding an empty row to the dataframe was not sufficient as it created an NA item in the legend which I do not want.

Here is the data:

> dput(coupler.graph)  structure(list(Category = c("HBC", "TC", "BSC", "GSC", "GSC",   "SSC", "SSC", "GSC", "GSC", "SSC", "SSC", "SSC", "HBC", "TC",   "BSC", "BSC", "GSC", "GSC", "SSC", "HBC", "HBC", "TC", "TC",   "BSC", "GSC", "GSC", "GSC", "GSC", "GSC", "TC", "BSC", "BSC",   "GSC", "GSC"), `Bar Size` = c("No. 5", "No. 5", "No. 5", "No. 5",   "No. 5", "No. 6", "No. 6", "No. 6", "No. 6", "No. 8", "No. 8",   "No. 8", "No. 8", "No. 8", "No. 8", "No. 8", "No. 8", "No. 8",   "No. 10", "No. 10", "No. 10", "No. 10", "No. 10", "No. 10", "No. 10",   "No. 10", "No. 10", "No. 11", "No. 11", "No. 18", "No. 18", "No. 18",   "No. 18", "No. 18"), `No. Bars` = c(3, 9, 3, 6, 6, 85, 85, 7,   7, 90, 90, 90, 7, 9, 6, 6, 21, 21, 9, 22, 22, 27, 27, 13, 25,   25, 25, 8, 8, 4, 4, 4, 4, 4), Failure = c("Bar fracture", "Bar fracture",   "Bar fracture", "Bar pullout", "Bar fracture", "Bar pullout",   "Bar fracture", "Coupler failure", "Bar fracture", "Coupler failure",   "Bar pullout", "Bar fracture", "Bar fracture", "Bar fracture",   "Bar pullout", "Bar fracture", "Bar fracture", "Bar pullout",   "Coupler failure", "Coupler failure", "Bar fracture", "Coupler failure",   "Bar fracture", "Bar fracture", "Bar pullout", "Bar fracture",   "Coupler failure", "Bar fracture", "Coupler failure", "Coupler failure",   "Bar fracture", "Bar pullout", "Bar fracture", "Coupler failure"  ), x = c("1-3", "7-9", "1-3", "5-7", "5-7", "30-90", "30-90",   "5-7", "5-7", "30-90", "30-90", "30-90", "5-7", "7-9", "5-7",   "5-7", "20-30", "20-30", "7-9", "20-30", "20-30", "20-30", "20-30",   "11-15", "20-30", "20-30", "20-30", "7-9", "7-9", "3-5", "3-5",   "3-5", "3-5", "3-5")), row.names = c(NA, -34L), class = c("tbl_df",   "tbl", "data.frame"))  

My code to create the interactive plot:

labels1 <- factor(c("0", "1-3", "3-5", "5-7", "7-9", "9-11", "11-15", "15-20","20-90"), levels = c("0", "1-3", "3-5", "5-7", "7-9", "9-11", "11-15", "15-20","20-30","30-90")) values1 <- c("white", "#ffffd9", "#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#1d91c0", "#225ea8", "#253494","#081d58") labels1 <- factor(c("0", "1-3", "3-5", "5-7", "7-9", "9-11", "11-15", "15-20","20-90"), levels = c("0", "1-3", "3-5", "5-7", "7-9", "9-11", "11-15", "15-20","20-30","30-90")) values1 <- c("white", "#ffffd9", "#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#1d91c0", "#225ea8", "#253494","#081d58")

plot1 <- ggplot(coupler.graph) + aes(x = Category, y = fct_inorder(`Bar Size`), fill = factor(x,                                       levels = c("0", "1-3", "3-5", "5-7", "7-9",                                                 "9-11", "11-15",  "15-20","20-30", "30-90"))) +   geom_tile(width=0.9, height=0.9) + theme_classic() + scale_fill_manual(labels = factor(labels1), values = values1) +   labs(x = "Splicer Type", y = "Bar Size") +   theme(plot.title = element_blank(), axis.text =  element_text(color = "black", size = 12), axis.ticks.x = element_blank(),         axis.line = element_line(color = "black", size = 0.2), axis.ticks.y = element_line(color = "black", size = 0.2),         axis.title.y = element_text(color = "black", size = 16, margin = margin(0,40,0,0)),          axis.title.x = element_text(color = "black", size = 16, margin = margin(35,0,0,0)),         legend.title = element_blank(), legend.text = element_text(color = "black", size = 12))     ggplotly(    p = ggplot2::last_plot(),    width = NULL,    height = NULL,    tooltip = c("Category", "Failure"),    dynamicTicks = FALSE,    layerData = 1,    originalData = TRUE,) %>% add_annotations( text="Number of\nSpecimens", xref="paper", yref="paper",                    x=1.1, xanchor="left", y=0.9, yanchor="bottom", font = list(size = 18),                    legendtitle=TRUE, showarrow=FALSE ) %>%    layout(yaxis = list(title = list(text = "Bar Size", standoff = 30L)),               xaxis = list(title = list(text = "Bar Size",standoff = 30L)),               legend = list(orientation = "v", x = 1.1, y = 0.13))  

The resulting plot:

enter image description here

Android / kotlin - TabLayout with shared inputs

Posted: 27 Mar 2021 08:19 AM PDT

How can I create a TabLayout that shares an input? is this possible? I want to fill the data in both tabs at the same time.

And, if the user clicks on a record of the tabs; it should open another control that I've already created, filling it with the data of the selected record.

I can't post images, so I hope this helps:

Title: Pending Moves

Inputs:

Warehouse : [Spinner]
Show cancelled bills: [x]

TabLayout:

Departure by transfer Departure by customer delivery

Datatable for both tab options:

Id Request Date etc

Publishing a custom artifact to JFrog from SBT

Posted: 27 Mar 2021 08:19 AM PDT

I try to publish a custom artifact to JFrog artifactory from SBT. I have the following project: SBT version 1.4.3

project/plugins.sbt:

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")  

build.sbt (I simplified a bit the actual one)

ThisBuild / scalaVersion := "2.11.12"  ThisBuild / organization := "my.org"  ThisBuild / organizationName := "company"    lazy val root = (project in file(".")).settings(     name := "my-project"  )    publishTo := {    val artifactory = "https://artifactory.company.org/artifactory/repo"    if (isSnapshot.value)      Some(        "Artifactory Realm" at s"$artifactory-snapshots;build.timestamp=" + new java.util.Date().getTime      )    else      Some("Artifactory Realm" at s"$artifactory-releases;keep_forever=release-artifact")  }    artifact in (Compile, assembly) := {    val art = (artifact in (Compile, assembly)).value    art.withClassifier(Some("assembly"))  }    addArtifact(artifact in (Compile, assembly), assembly)    val packAnsible = taskKey[File]("Pack ansible files.")  val ansibleArtifactName = settingKey[String]("Ansible artifact name")    packAnsible := {    val ansibleZip =      target.value / s"scala-${scalaBinaryVersion.value}" / s"${name.value}.zip"    IO.zip(      IO.listFiles(Path("ansible").asFile).map(f => (f, f.name)),      ansibleZip,      None    )    ansibleZip  }  artifact in packAnsible := Artifact(name.value, "zip", "zip").withClassifier(Some("ansible"))    addArtifact(artifact in packAnsible, packAnsible)  

as you can see I add 2 artifacts to be publish:

  1. uber jar with classifier "assembly"
  2. a zip with some ansible vars with classifier "ansible"

After publishing in my repository I can find almost all what I wish:

  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-20210301.161254-1-assembly.jar
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-20210301.161254-1-javadoc.jar
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-20210301.161254-1-sources.jar
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-20210301.161254-1.jar
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-20210301.161254-1.pom
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/my-project_2.11-0.1.0-0.3.2-SNAPSHOT-ansible.zip
  • repo/com/org/my-project_2.11/0.1.0-SNAPSHOT/maven-metadata.xml

I can see in the maven-metadata all other artifacts except my zip and also the name of the jar does not contain the build.time and therefor will fail on next build unless I give the user the rights to overwrite/delete which I prefer not to.

I tried following the docs and added -Dsbt.override.build.repos=true both in my build server at /usr/local/etc/sbtopts and in the root of my project.

I would like to have all artifact (only my costume is not currently) to be properly published.

Thanks for the help.

Python comparing strings, problem with endlines

Posted: 27 Mar 2021 08:20 AM PDT

Hi guys I have two different strings. One of these stings is a description and the other one is a template.

I want to check if the template is inclued in the description.

The Problem is that I cant just do

if template in description:     print("template is included")     return True  else: raise Exception("exception test23")  

Spring-Boot: scalability of a component

Posted: 27 Mar 2021 08:20 AM PDT

I am trying Spring Boot and think about scalabilty.

Lets say I have a component that does a job (e.g. checking for new mails). It is done by a scheduled method.

e.g.

@Component  public class MailMan  {    @Scheduled (fixedRateString = "5000")    private void run () throws Exception    { //... }  }  

Now the application gets a new customer. So the job has to be done twice.

How can I scale this component to exist or run twice?

Do MIPS registers behave differently?

Posted: 27 Mar 2021 08:18 AM PDT

Do MIPS registers act differently? for example, there are saved registers and temp registers, can they be used interchangeably? Will temp registers possibly be over written by the OS, while saved registers wont (hence their name) or is it purely convention?

screen rotation not working on actual device but working in emulator

Posted: 27 Mar 2021 08:19 AM PDT

I have a weird problem. I set the screen orientation in android manifest and it works on emulater but not on the actual device. I also changed the orientation programmatically and still the problem persists. My manifest is as follows -

<?xml version="1.0" encoding="utf-8"?>  <manifest package="com.example.rotatedsignage"      android:versionCode="1"      android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">        <uses-sdk          android:minSdkVersion="8"          android:targetSdkVersion="19" />        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />      <uses-permission android:name="android.permission.INTERNET" />      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>        <application          android:allowBackup="true"          android:icon="@drawable/ic_launcher"          android:label="@string/app_name"          android:theme="@style/AppTheme" >          <activity              android:name="com.example.rotatedsignage.MainActivity"              android:configChanges="orientation"              android:label="@string/app_name"              android:screenOrientation="portrait" >              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                    <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>            <receiver              android:name="com.example.rotatedsignage.BootReceiver"              android:enabled="true"              android:exported="true" >              <intent-filter>                  <action android:name="android.intent.action.BOOT_COMPLETED" />              </intent-filter>          </receiver>      </application>    </manifest>  

What is wrong with my code? The code I used -

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  

any help is appreciated. Thanks in advance.

No comments:

Post a Comment