text:
Q: Drools - How to access an object in THEN clause I have a scenario when the data in the input is having different columns for one fact i.e. transposed data for e.g.
EmployeeID | EmpDept1 | EmpDept2 | EmpDept3 | EmpDept4 | EmpDept5

Now I have a lookup Department table as well e.g.
DeptId | DeptName

For me to do the lookup, one way is to create 5 rules like:
rule "Lookup dept-1 data"
when
    e: EmployeeData()
    d: DeptData(deptId == $e.EmpDept1)
then
    System.out.println(e.toString());
end

The problem here is that i have to create 5 rules (and in my case many more). Is there a way I can access the DeptData in the "THEN" clause and then write a JAVA lookup?
Or if there is any other good way, please let me know.
Thanks!

A: So basically you have an Employee where their Department may be listed in any of five places. The best way to figure this out would be to figure out where the department lives prior to firing the rules, and then modifying the object you pass into the rules. You're not restricted in terms of what kind of objects you pass into the rules as long as they serialize ok; if EmployeeData is currently the raw results from a database call or something, convert the parts of it you need into a new POJO and pass it into the rules.
So for your example, I would do something like:
class Employee {
  private Integer employeeId;
  private Integer departmentId; // assuming the only thing you need out of Department is id

  public static Employee fromEmployeeData(EmployeeData data) {
    Employee employee = new Employee();
    employee.setEmployeeId(data.getEmployeeId());

    if (data.getDept1() != null) {
        employee.setDepartmentId(data.getDept1());
    } else if (...) {} // other else-if omitted for brevity

    return employee;
  }

  // getters and setters here
}

public void invokeRules(EmployeeData data) {
  KieSession kieSession = ...;

  Employee employee = Employee.fromEmployeeData(data);

  kieSession.insert( employee );
  kieSession.fireAllRules();
}

Then you can write rules that key off of the department id:
rule "Employee is in department 6"
when
  Employee( departmentId == 6 )
then
  // do something
end

Alternatively, you can call Java methods from the when clause. Let's say we create a class called EmployeeUtils that has a method for resolving the department from the EmployeeData:
class EmployeeUtils {

  public static Integer resolveDepartment(Employee e) {
    Integer deptId = null;

    if (e.getDept1Id() != null) {
      deptId = e.getDept1Id();
    } else if (...) {} // other else-if omitted for brevity

    return deptId;
  }
}

You can then call this method on the left hand side like this:
rule "Employee in department 6"
when
  $employee: Employee()
  Integer(this == 6) from EmployeeUtils.resolveDepartment($employee)
then
  // do something
end

Obviously you could call it on the right hand side as well:
rule "Example"
when
  $employee: Employee()
then
  System.out.println("Employee is in department " + EmployeeUtils.resolveDepartment($employee));
end

In general it is not recommended to call Java methods from the left hand side because such calls cannot be optimized. When you're doing filtering like Employee(department == 6), Drools can do a lot of optimization on the assertions to make your rules fire faster. But if you're calling a Java method, that's like a black box to the Drools engine; it has no idea what that Java method is going to be doing, so it must let it evaluate as-is instead of doing work to make it faster.
Furthermore, it is also generally not recommended to pass arbitrary data into a rule set. Pass in just the data you need for the rules to fire. When converting from another data source, eg. from a SQL query result or conversion from a spreadsheet, parse the parts of that other data that you actually need, and pass that parsed input object into the rules.
I worked for a company that would pass the database result directly into the rules. The logic was that the code was compiled, so if you needed to make changes to the rule input object you would need to recompile the code and do a new release. But database schema and rules could be external to the compiled code, so they could change without needed recompile, so just make all the data available and don't bother with a new release. This worked when the company was new and the data we were passing in was only a few joined tables; by the time I left we were passing in hundreds of tables of data adding up to several hundred kilobytes in memory, though the rules only needed a few bits of data off of maybe five tables. It was slow and wasteful. Don't go down this route.
Something like this, where you have an Employee and you have a Department data external -- joining the two is something that would optimally be accomplished in (for example) a SQL query. This sort of relational joining really doesn't usually need any decisions made on it. And if it does need decisions (eg. for example if the department code is in Dept5 then it means something different than if it is in Dept2), then multiple rules are in fact appropriate. But when it's just a matter of the same logic but in potentially 5 places? Don't bother doing it in rules; there's no benefit to it. Do it in Java, and then pass the result into the rules to make assertions against.

A: I resolved this by using "collect"
rule "Lookup dept data"
when
    e: EmployeeData()
    d1: ArrayList() from collect (DeptData(deptId == $e.EmpDept1))
    d2: ArrayList() from collect (DeptData(deptId == $e.EmpDept2))
    d3: ArrayList() from collect (DeptData(deptId == $e.EmpDept3))
    d4: ArrayList() from collect (DeptData(deptId == $e.EmpDept4))
    d5: ArrayList() from collect (DeptData(deptId == $e.EmpDept5))
then
    System.out.println("Employee == " + e);
    if (d1.size() > 0) System.out.println("Department 1 == " + d1.get(0));
    if (d2.size() > 0) System.out.println("Department 1 == " + d2.get(0));
    if (d3.size() > 0) System.out.println("Department 1 == " + d3.get(0));
    if (d4.size() > 0) System.out.println("Department 1 == " + d4.get(0));
    if (d5.size() > 0) System.out.println("Department 1 == " + d5.get(0));
end

The "collect" function here ensures that Employee records are not duplicated and then individual applicable departments can be found.


text:
Q: How to ensemble SVM and CNN classifier using bagging? I am doing a classification of tuberculosis using X-ray images. While I extract the useful features from the X-ray images into a csv file and run SVM with it and get a roughly ~60% accuracy. Meanwhile, My CNN model which is directly train on the images dataset has achieved an accuracy of ~80%. I can find reference online where ensemble method can be used when two models machine learning model or deep learning model, not one with another. Example, I can ensemble CNN with another type of CNN.

A: Assuming your question is 'How to ensemble SVM & CNN classifier using bagging' it's not that hard. You train each model SVM and CNN ( You can use multiples of each) with subset of the entire train set. After each model has been trained you give test data, and for each data all models makes a classification. It would work like a vote. SVM votes 'True' and CNN also votes 'true' majority is 'true' so your ensemble model will classify it to 'True'.
So it doesn't matter if its another type of model.

A: Bootstrap aggregating or bagging is an ensembling method where you have different models trained on different samples of the training set. So, Bagging is not applicable here.
In the case of ensembling a CNN and SVM model, a simple method would be to average the predictions. There are other techniques like weighing(more votes for the accurate model) etc. Please refer this link:
https://mlwave.com/kaggle-ensembling-guide/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do R plots have handles? Do plots in R have handles? For example, if I were to use something like this:
plot(plotData[,1], plotData[,2], type='l', col='red', lty=2, xlab='x',
    ylab='y', main='sample plot')

would I be able to change anything in this plot later like the color, or the x-axis label, or the x-axis range, etc.? Or do I have the plot this all over again?
Thanks!

A: Base R does not have handles in the sense that you are asking. Although you can modify some aspects of the plot after you've plotted it, much better suited to the needs in question would be to use ggplot
You can save the output to an object and append as needed.
You can also use last_plot()
Have a look at
http://www.cookbook-r.com/Graphs/ and http://docs.ggplot2.org/current/


text: Q: K-Means Clustering in Py-spark I have a really big data frame. I am considering 8 columns to make 8 clusters. Now, normally the code would discard a row even if 1 of the 8 column values is NaN. In my case, I have to write a pyspark code that behaves in such a way that(Even When a row has some NaN values, the code will ignore them and take other column values into consideration and thereby performing clustering even for rows that have some NaN values)Any help or lead is highly appreciated.


text:
Q: AWS Lambda to DynamoDB - Missing the key PK in the item I am sending a POST request to API Gateway via Postman.
Please could someone help me understand how to solve the error, and make it know what the PK is in the Item object?
The error:
2022-01-18T07:47:45.636Z    f9879b45-b7d5-22ab-9439-cec7c1c8c332
ERROR   ValidationException: One or more parameter values were invalid: Missing the key PK in the item
-- DELETED MANY at Reqests --
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
code: 'ValidationException',
time: 2022-01-18T07:47:45.519Z,
requestId: 'G7LU6ADFQKB26JDHJ6QXADDB3JVV4KQNSO5AEMVJF66Q9ASUAAJG',
statusCode: 400,
retryable: false,
retryDelay: 5.218698231501939

The Lambda Function:
"use strict";
require("dotenv").config();
// const config = require("../../config/keys");
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-west-1" });
const documentClient = new AWS.DynamoDB.DocumentClient();

const addJobListing = async (data) => {
  const body = {
    Item: {
      PK: data["PK"],
      SK: data["SK"],
      "Days Off": data["Days Off"],
      "Start Date": data["Start Date"],
      "Job ID": data["Job ID"],
      "Contract Length": data["Contract Length"],
      "Expiration Date": data["Expiration Date"],
      Created: {
        date: data["Created Date"],
        time: data["Created Time"],
      },
      Insurance: data["Insurance"],
      Title: data["Title"],
      Holidays: data["Holidays"],
      Ages: data["Ages"],
      "Flight Reimbursement": data["Flight Reimbursement"],
      Curriculum: data["Curriculum"],
      "Account ID": data["Account ID"],
      "Minimum Monthly Salary Before Tax":
        data["Minimum Monthly Salary Before Tax"],
      "Housing Allowance": data["Housing Allowance"],
      Responsibilities: data["Responsibilities"],
      "Job Closest Metro": data["Job Closest Metro"],
      "Job Requirements": data["Job Requirements"],
      "Job Type": data["Job Type"],
      "Z-VISA Reimbursement": data["Z-VISA Reimbursement"],
      Meals: data["Meals"],
      Subject: data["Subject"],
      "Salary Information": data["Salary Information"],
      "Maximum Monthly Salary Before Tax":
        data["Maximum Monthly Salary Before Tax"],
      "Vacancy Status": data["Vacancy Status"],
      "Contract Completion Bonus": data["Contract Completion Bonus"],
      "Last Modified": {
        date: data["Modified Date"],
        time: data["Modified Time"],
      },
    },
    TableName: "table-name-hidden",
  };

  return await documentClient
    .put(body)
    .promise()
    .then((data) => console.log(data.Attributes))
    .catch(console.error);
};

exports.handler = async (event, context, callback) => {
  console.log("EVENT BODY", event.body);
  const response = await addJobListing(JSON.parse(event.body));
  return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*", // Required for CORS support to work
      "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
    },
    body: JSON.stringify(response),
  };
};

The JSON:
{
    "Item": {
        "PK": "ACC#1000",
        "SK": "JOBID#01.17/01/2022",
        "Days Off": "Weekends",
      "Start Date": "17/09/2022",
      "Job ID": "01",
      "Contract Length": "Two Years",
      "Expiration Date": "17/09/2022",
      "Created": {
            "date": "17/09/2022",
            "time": "00:00:00"
      },
      "Insurance": "Insurance",
      "Title": "Title Of Vacancy",
      "Holidays": "Amount of Holidays",
      "Ages": "Ages of Children",
      "Flight Reimbursement": "Flight Reimbursement",
      "Curriculum": "Curriculum",
      "Account ID": "10",
      "Minimum Monthly Salary Before Tax": "Minimum Monthly Salary Before Tax",
      "Housing Allowance":"Housing Allowance",
      "Responsibilities": "Responsibilities",
      "Job Closest Metro": "Job Closest Metro",
      "Job Requirements": "Job Requirements",
      "Job Type": "Job Type",
      "Z-VISA Reimbursement": "Z-VISA Reimbursement",
      "Meals": "Meals",
      "Subject": "Subject",
      "Salary Information": "Salary Information",
      "Maximum Monthly Salary Before Tax": "Maximum Monthly Salary Before Tax",
      "Vacancy Status": "Vacancy Status",
      "Contract Completion Bonus": "Contract Completion Bonus",
      "Last Modified": {
            "date": "17/09/2022",
            "time": "00:00:00"
      }
      }
}

A: Based on the JSON provided, instead of data["PK"], should it be data["Item"]["PK"] instead?


text:
Q: How to prove this Bessel's identity? I've got a problem with proving this Bessel's identity:
$ J_0(t)+2\sum_{n=1}^{\infty}{J_{2n}(t)} = 1$

A: Take $\varphi = \pi$ in the fundamental identity :
$$e^{i z \sin \varphi }=J_0(z)+2\sum_{k=1}^{\infty}J_{2k}\cos{2k \varphi}+2i\sum_{k=0}^{\infty}J_{2k-1}\sin{(2k+1) \varphi}$$
(Gradshteyn and Ryzhic, Academic Press, 1980 formulass 8.511 p. 973)


text:
Q: what is the difference between / and //? I have been facing this wierd problem while trying to montor an FTP server.
If I try to use ftp://192.x.x.x/home/$USER/output , the monitoring tool fails to pickup the folder.
However, if I use ftp://192.x.x.x//home/$USER/output, then the FTP folder is picked up easily.
So I want to know, what is the difference between  / and  // ?

A: I hope this helps.
A path name consisting of a single slash / resolves to root directory of the process.  A path name that begins with two slashes // may be interpreted diffrently, although more than two leading slashes shall be treated as a single slash.
Most implementations simply treat // as / , but may still show // .
Also see UNIX, difference between path starting with '/' and '//'


text:
Q: Determine country from IP - IPv6 In my project, I have a function in postgres (plpgsql) that determines country from a given ip address:
CREATE OR REPLACE FUNCTION get_country_for_ip(character varying)
  RETURNS character varying AS
$BODY$
declare
    ip  ALIAS for $1;
    ccode   varchar;
    cparts  varchar[];
    nparts  bigint[];
    addr    bigint;
begin
    cparts := string_to_array(ip, '.');
    if array_upper(cparts, 1) <> 4 then
        raise exception 'gcfi01: Invalid IP address: %', ip;
    end if;
    nparts := array[a2i(cparts[1])::bigint, a2i(cparts[2])::bigint, a2i(cparts[3])::bigint, a2i(cparts[4])::bigint];
    if(nparts[1] is null or nparts[1] < 0 or nparts[1] > 255 or
       nparts[2] is null or nparts[2] < 0 or nparts[2] > 255 or
       nparts[3] is null or nparts[3] < 0 or nparts[3] > 255 or
       nparts[4] is null or nparts[4] < 0 or nparts[4] > 255) then
        raise exception 'gcfi02: Invalid IP address: %', ip;
    end if;

    addr := (nparts[1] << 24) | (nparts[2] << 16) | (nparts[3] << 8) | nparts[4];
    addr := nparts[1] * 256 * 65536 + nparts[2] * 65536 + nparts[3] * 256 + nparts[4];

    select into ccode t_country_code from ip_to_country where addr between n_from and n_to limit 1;
    if ccode is null then
        ccode := '';
    end if;
    return ccode;
end;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

This may not be the most efficient, but it does the job.  Note that it uses an internal table (ip_to_country), which contains data as below (the numbers n_from and n_to are the long values of the start and end of address ranges:
  n_from  |   n_to   | t_country_code
----------+----------+----------------
        0 | 16777215 | ZZ
 16777216 | 16777471 | AU
...

Now we are starting to look at the IPv6 addressing as well - and I need to add similar functionality for IPv6 addresses.  I have a similar set of data for IPv6, which looks like this:
 t_start     | t_end                                   | t_country_code
-------------+-----------------------------------------+----------------
 ::          | ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff   | ZZ
 100::       | 1ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff  | ZZ
...
 2000::      | 2000:ffff:ffff:ffff:ffff:ffff:ffff:ffff | ZZ
...
 2001:1200:: | 2001:1200:ffff:ffff:ffff:ffff:ffff:ffff | MX
...

Now, given an IP address ::1, how do I (1) check that it's a valid IPv6 address and (2) get the corresponding country mapping?

A: I believe I found the solution.  It involves modifying the data first and then some massaging of the input.  Here's what worked.
First, the data needs to be converted so that all addresses are full, without shortening, with semicolon separators removed.  The sample data shown in my question is converted to:
 t_start                          | t_end                            | t_country_code
----------------------------------+----------------------------------+----------------
 00000000000000000000000000000000 | 00ffffffffffffffffffffffffffffff | ZZ
 01000000000000000000000000000000 | 01ffffffffffffffffffffffffffffff | ZZ
...
 20000000000000000000000000000000 | 2000ffffffffffffffffffffffffffff | ZZ
...
 20011200000000000000000000000000 | 20011200ffffffffffffffffffffffff | MX
...

This is what is stored in the database.
The next step was to convert the IP address received in the code to be in the same format.  This is done in PHP with the following code (assume that $ip_address is the incoming IPv6 address):
$addr_bin = inet_pton($ip_address);
$bytes = unpack('n*', $addr_bin);
$ip_address = implode('', array_map(function ($b) {return sprintf("%04x", $b); }, $bytes));

Now variable $ip_adress wil contain the full IPv6 address, for example
:: => 00000000000000000000000000000000
2001:1200::ab => 200112000000000000000000000000ab

and so on.
Now you can simply compare this full address with the ranges in the database.  I added a second function to the database to deal with IPv6 addresses, which looks like this:
CREATE OR REPLACE FUNCTION get_country_for_ipv6(character varying)
  RETURNS character varying AS
$BODY$
declare
    ip  ALIAS for $1;
    ccode   varchar;
begin
    select into ccode t_country_code from ipv6_to_country where addr between n_from and n_to limit 1;
    if ccode is null then
        ccode := '';
    end if;
    return ccode;
end;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

Finally, in my php code I added the code that calls one or the other Postgres function based on the input ip_address.

A: First, I see a couple things you are doing that will pose problems.  The first is this use of varchar and long to represent IP addresses when PostgreSQL has perfectly valid INET and CIDR types that will do what you want only better and faster.  Note these do not support GIN indexing properly at present so you can't do exclude constraints on them.  If you need that, look at the ip4r extension which does support this.
Note as a patch for now you can cast your varchar to inet.  Inet also supports both ipv4 and ipv6 addresses as does cidr, and similar types exist on ip4r.
This will solve the ipv6 validation issue for you, and likely cut down on your storage as well as provide better operational checks and better performance.
As for countries, I am also thinking that the mappings may not be so straight-forward.


text:
Q: How to count the number of rows in a query when in most cases, they are expected to be 0 - Doctrine2 I have a register form with email which should be unique. What I want to do is, if someone fills in an email which is alreday registered for another user, this someone to see a message, written by me, not something like
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin@domain.com' for key 'UNIQ_1483A5E9E7927C74'

I tried this in the repository class:
public function getSameFriends ($email)
    {
        $q = $this->createQueryBuilder('f');

        $q->select('f')
          ->where('f.email = :email')
          ->setParameter('email', $email);

        return $q->getQuery()->getSingleScalarResult();
    }

and then this in the controller:
$em = $this->getDoctrine()->getEntityManager();
        $count = $em->getRepository('EMMyFriendsBundle:Friend')
                                    ->getSameFriends($friend->getEmail());
        if($count != 0)
        {
            $this->get('session')->setFlash('notice', 'There already is a friend with this email!');
            return $this->redirect($this->generateUrl('home_display'));
        }

but I get an exception that
No result was found for query although at least one row was expected.
500 Internal Server Error - NoResultException

I don't need the result of the query, just to know if the results are 1 or 0. Do you have any idea how to make this?

A: You can do:
return count($q->getQuery()->getResult());

BTW, have you looked at the 'uniqueEntity' validation constraint? It provides the functionality you need out of the box:
http://symfony.com/doc/current/reference/constraints/UniqueEntity.html


text:
Q: List examples of how to "briefly draw attention" to an object on screen in iOS? In iOS, how can one briefly draw attention to an object on screen? Suppose, create a brief glow or cause a shadow to appear and then disappear?
For the purposes of this question, let's define "object on screen" as an instance of UIImageView.
Also, if possible provide an example of how to draw attention to a button.

A: [UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.1f];
yourView.transform = CGAffineTransformMakeScale(1.1, 1.1);
[UIView commitAnimations];

Or, of course the same thing with a block animations. And after the attention got away from your view you can use :
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.1f];
yourView.transform = CGAffineTransformIdentity;
[UIView commitAnimations];

A: Here is a simple hop animation...
- (void)drawAttn
{
float jumpHeight = 20.0;

CGPoint originalPoint = objectForAttn.center;
CGPoint jumpPoint = CGPointMake(objectForAttn.center.x, objectForAttn.center.y - jumpHeight);
    [UIView animateWithDuration:0.20 delay:0.0 options:UIViewAnimationOptionAutoreverse animations:^{
        [objectForAttn setCenter:jumpPoint];

    } completion:^(BOOL finished) {
        /* do other stuff after hop */
    }];
}

A: My app QCount (free in the store, tap a "wrong" number 3 times) uses a fade animation as follows:
(note I wrote this when I was REALLY new to iOS, so there is probably a more compact way to write it)
    aLabel = // a UILabel I get from somewhere
    aColor = aLabel.backgroundColor;
    [UIView animateWithDuration:0.2
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         aLabel.alpha = 0.0;
                     }
                     completion:^(BOOL finished){
                         // Wait .2 seconds and then fade in the view
                         [UIView animateWithDuration:.2
                                               delay: 0.0
                                             options:UIViewAnimationOptionCurveEaseIn
                                          animations:^{
                                                    aLabel.alpha = 1.0;
                                          }
                                          completion:nil];
                     }];

A: There are lots of options: hopping, underlining, vibrating, blinking, rotating, scaling, endarkening around, and their combinations.
But IMO, shine effect on "slide to unlock" text is excellent.
You can check it out here:
iPhone "slide to unlock" animation

A: Most people list code, but I'm sticking to describing some examples;

*

*I've seen objects briefly grow and shrink back to their normal size to draw attention

*Bejeweled (a Popcap game) lets diamonds briefly 'shine' (as if sunlight passed over it) to give you a subtle hint

*I've seen certain applications use a hand or a fictive character point to a certain object briefly

And of course, you could always introduce a talking paperclip to tell you what's what.

A: I wanted to draw attention to a label whose value had changed. This simple animation produces a nice 'I've changed' animation...
    //copy the label
    UILabel *newPageLabel = [[UILabel alloc] initWithFrame:_countLabel.frame];
    [newPageLabel setFrame:CGRectOffset(newPageLabel.frame, 0, 0)];
    newPageLabel.text = _countLabel.text;
    newPageLabel.textAlignment = _countLabel.textAlignment;
    newPageLabel.backgroundColor = _countLabel.backgroundColor;
    newPageLabel.textColor = _countLabel.textColor;
    newPageLabel.font = _countLabel.font;

    //scale and fade out the copied label
    [self.navigationController.toolbar addSubview:newPageLabel];
    [UIView animateWithDuration:0.5
                          delay:0.0
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         newPageLabel.transform = CGAffineTransformMakeScale(2,2);
                         newPageLabel.alpha = 0;
                     }
                     completion:^(BOOL finished){
                         [newPageLabel removeFromSuperview];
                     }
     ];


text:
Q: functools.partial raising TypeError "got multiple values for keyword argument" Python I try to efficiently iterate over many strings and there is a repeated part of the strings I would like to insert with a partial function
def add_seqs(seqs_outer,sequence):
    return seqs_outer[0]+sequence+seqs_outer[1]

def my_function(string,start,stop,list_variable):
    seqs_pre=string[:start]
    seqs_post=string[stop:]
    seqs_outer=(seqs_pre,seqs_post)
    seqs_out=map(functools.partial(add_seqs,seqs_outer=seqs_outer),list_variable)
    return seqs_out

I finally want to use an apply function over many different strings with a fixed list_variable, but I get an error in my_function:

TypeError: my_function() got multiple values for keyword argument 'seqs_outer'

I guess I do something wrong in the use of partial - how can I make the above code work?

A: Okay, inspired by this thread I swapped the order of arguments in
def add_seqs(seqs_outer,sequence)
to
def add_seqs(sequence,seqs_outer)
this did the job


text:
Q: Modualrize Python program with appJar GUI How do you modularize an appJar app? When I try to use the example code and move the press() function into an own file, this functions doesn't know the app variable. I guess it's best if you look at the Image below - if not I'll update the question!

A: As for me it is not good idea to put press() in separated file. I would rather keep press() in current file and it could use function from other file - but this file should get all values as arguments
modules/methods.py
def display(app):
    print("User:", app.entry("Username"), "Pass:", app.entry("Password"))

main.py
from appJar import gui
from modules import methods

def press():
    methods.display(app)

with gui("Login Window", "400x200", bg='orange', font={'size':18}) as app:
    app.label("Welcome to appJar", bg='blue', fg='orange')
    app.entry("Username", label=True, focus=True)
    app.entry("Password", label=True, secret=True)
    app.buttons(["Submit", "Cancel"], [press, app.stop])

Or event other function should get only values from widgets
modules/methods.py
def display(username, password):
    print("User:", username, "Pass:", password)

main.py
def press():
    methods.display(app.entry("Username"), app.entry("Password"))

If you really want press() in other file then it should get app as argument
modules/methods.py
def press(app):
    print("User:", app.entry("Username"), "Pass:", app.entry("Password"))

but then you have to use lambda:methods.press(app) to assign to button function with argument.
main.py
app.buttons(["Submit", "Cancel"], [lambda:methods.press(app), app.stop])


text: Q: ESPG:27700 is displaying incorrect coordiantes I am new to GIS, so forgive me. I have set up a project using Open Street Map as my background, I have set the CRS to ESPG:27700 British National Grid, however the status bar is not displaying the coordinates correctly, and still says 000,000 is located on the intersection of Greenwich meridian and the equator...any thought how to resolve this?


text:
Q: Why pthread_cond_signal could hang up? I've read a few suggested topic but unfortunately haven't found the answer for my question.
Any suggestion is highly appreciated.
So, I'm working on the huge project and here is effected code snippet:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>

static pthread_mutex_t mutex;
static pthread_cond_t cond;

static char *timestamp()
{
    time_t rawtime;
    struct tm *timeinfo;
    char *stamp;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    stamp = asctime(timeinfo);
    stamp[strlen(stamp) - 1] = '\0';

    return stamp;
}

static void *monitor(void *ctx)
{
    int ret;
    struct timeval now;
    struct timespec timeout = { 0 };

    while (1)
    {
        gettimeofday(&now, NULL);

        timeout.tv_sec = now.tv_sec + 1;

        pthread_mutex_lock(&mutex);

        if (!(ret = pthread_cond_timedwait(&cond, &mutex, &timeout)))
        {
            printf("%s [%s] Signaled successfully!\n", timestamp(),
                __FUNCTION__);

        }
        else if (ret == ETIMEDOUT)
            printf("%s [%s] Timed out!\n", timestamp(), __FUNCTION__);

        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main()
{
    pthread_t tid;

    if (pthread_mutex_init(&mutex, NULL) < 0)
    {
        perror("mutex");
        return -1;
    }

    if (pthread_cond_init(&cond, NULL) < 0)
    {
        perror("cond");
        pthread_mutex_destroy(&mutex);
        return -1;
    }

    if (pthread_create(&tid, NULL, monitor, NULL) < 0)
    {
        perror("create()");
        pthread_cond_destroy(&cond);
        pthread_mutex_destroy(&mutex);
        return -1;
    }

    pthread_detach(tid);
    srand(time(NULL));

    while (1)
    {
        int delay = rand() % 5 + 1;

        printf("%s [main] Waker is sleeping for %d sec\n", timestamp(), delay);
        sleep(delay);

        printf("%s [main] Signaling...\n", timestamp());
        pthread_mutex_lock(&mutex);
        printf("%s [main] Lock aquired...\n", timestamp());
        pthread_cond_signal(&cond);
        printf("%s [main] Signaled. Releasing...\n", timestamp());
        pthread_mutex_unlock(&mutex);
    }

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    return 0;
}

Every time when [main] thread is reaching out the pthread_cond_signal and pthread_cond_timedwait is waiting (not timed out) the stuck is happening.
Locking mutex before pthread_cond_signal is best practice, which I have read here
This topic says that such stuck could happen if cond/mutex is destroyed before waiting.
This topic describes spurious wakes up, which could lead to such stuck.
However, both seems not relevant to my case.
I've also assumed that such behavior could be related to ulimit -s/-i. But setting to unlimited value doesn't help.
What's interesting is that [monitor] thread also gets stuck as [main] does.
UPD
    Program output:
    Wed Jun  8 13:34:10 2022 [main] Waker is sleeping for 4 sec
    Wed Jun  8 13:34:10 2022 [monitor] Timed out!
    Wed Jun  8 13:34:11 2022 [monitor] Timed out!
    Wed Jun  8 13:34:12 2022 [monitor] Timed out!
    Wed Jun  8 13:34:13 2022 [monitor] Timed out!
    Wed Jun  8 13:34:14 2022 [main] Signaling...
    Wed Jun  8 13:34:14 2022 [main] Lock acquired...
    /*No prints at all */

UPD2:
I refactored above example just for using pthread_cond_wait like this:
[monitor thread]
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);

[main thread]
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);

and I'm hanging on the pthread_cond_signal again...
So, it seems like problem from OS perspective. I only know that small ulimit's stack size could lead to stack overflow, which could causing such stuck (arch depended stuff, 100 % reproducible in my case).
Does anyone know some other specific configuration, which could affect it?


text:
Q: Store and retrieve Boolean Object to a MySql database This is my first question here, but before asking to you I have searched all around the Internet without solution.
I want to store Java Objects in a MySql database and to do so I'm using the data type BLOB for all the objects. The MySql table is:
CREATE TABLE settaggi_variabili_pc (`id` int(11) NOT NULL AUTO_INCREMENT, PC1 BLOB, PC2 BLOB, PC3 BLOB, PC4 BLOB, PC5 BLOB, PC6 BLOB, PC7 BLOB, PC8 BLOB, PC9 BLOB, PC10 BLOB, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1;

In there I have to store Java objects like Color, Font and Boolean:
prpdStmnt = con.prepareStatement("UPDATE settaggi_variabili_pc SET PC1=?, PC2=?, PC3=?, PC4=?, PC5=?, PC6=?, PC7=?, PC8=?, PC9=?, PC10=? WHERE id=?");
for (int i = 0; i < vDati.size(); i++)
{
    Variabile_variabili_pc vpc = (Variabile_variabili_pc) vDati.get(i);
    Object o = null;
    if (vpc.getOggetto() instanceof Color)
        o = (Color) vpc.getOggetto();
    else if (vpc.getOggetto() instanceof Font)
        o = (Font) vpc.getOggetto();
    else if (vpc.getOggetto() instanceof JSwitchButton)
        o = (Boolean)((JSwitchButton) vpc.getOggetto()).isSelected();

    prpdStmnt.setInt(11, i + 1);
    for (int x = 1; x <= 10; x++)
    {
        prpdStmnt.setObject(x, o);
    }

    prpdStmnt.executeUpdate();

The JSwitchButton is a custom class that extends AbstractButton.
All this code works right.
My problem is when I try to retrieve the Boolean Object, this is the code:
ritorno = db.eseguiQuery("SELECT PC1, descrizione FROM settaggi_variabili_pc");
try
{
    while(ritorno.next())
    {
        InputStream is = ritorno.getBlob(1).getBinaryStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        o = ois.readObject();

        if (o.getClass().equals(Color.class))
            System.out.println("Object type Color");
        else if (o.getClass().equals(Font.class))
            System.out.println("Object type Font");
        else if (o.getClass().equals(Boolean.class))
            System.out.println("Object type Boolean");
    }
}

catch (SQLException e)
{
    e.printStackTrace();
} catch (IOException e)
{
    e.printStackTrace();
} catch (ClassNotFoundException e)
{
    e.printStackTrace();
}

When the ObjectInputStream read the Boolean object the code return a java.io.EOFException error. This error come becouse the Boolean Object, during the store action, was tranlated to TINYINT value in MySql database and it is not stored as a Boolean Object.
So the question is: how can I store a Boolean object to a BLOB MySql Type and how can I retrieve it to a Boolean object again like I done with Color or Font? Is there a way so I can store the Boolean like an Object and not like a primitive type?
Thank you to all.

A: First of all, as @Jorge Campos pointed out, what you have is not a good structure for storing things in a database.  Even for your application, simple configuration data would better be stored in some sort of flat text format (i.e INI Files or similar.  If you really must use a database, you should certainly think about using either an object oriented database or even an Object-Relational Mapping (ORM) tool (such as Hibernate) sitting on-top of MySQL.
Getting down to an actual answer, Just change the line else if (o.getClass().equals(Boolean.class)) in your code above (note the bold), to use a more appropriate class, such as Integer or Byte - that way when the TINYINT is returned fro MySQL you will be able to represent it.
As an aside, I think you would benefit from The StackExchange code review site https://codereview.stackexchange.com/.  Your code is VERY sloppy, and would certainly benefit from a review.  You can have your code reviewed without changing your database, if you really want.


text:
Q: How to display products from subcategory to parent category in opencart? I'm trying to find a solution but still no luck. I want to display all products from subcategories to parent category.
I'm using Opencart 1.5.3.1

A: Another solution, rather than modifying the core files directly, is to use vQmod to modify the file for you. That way when you upgrade to a new version, you won't have to re-install any custom modifications you've made.
Below is an the code you'd use to accomplish this in vQmod:
<?xml version="1.0" encoding="UTF-8"?>
<modification>
    <id>Display products in sub-categories while browsing a parent category</id>
    <version>1.0.0</version>
    <vqmver>2.4.0</vqmver>
    <author>Jay Williams - jay@myd3.com</author>
    <file name="catalog/controller/product/category.php">
        <operation>
            <search position="after"><![CDATA['filter_category_id' => $category_id,]]></search>
            <add><![CDATA['filter_sub_category' => true,]]></add>
        </operation>
    </file>
</modification>

Source: https://gist.github.com/jaywilliams/8044763

A: catalog/controller/product/category.php
For Opencart Version 2.1.0.2, the solution of Ignacio works fines as well just that:

$data (of version 1.5.x) is now called
$filter_data (line #169)

Then just add the line
'filter_sub_category' => true,
after line #170 ('filter_category_id' => $category_id,)
Thanks Ignacio!

A: After reading the source, I figured it out:
In catalog/controller/product/category.php (or wherever you're calling function model_catalog_product->getProducts) you have to add filter_sub_category = true:
$data = array(
    'filter_category_id' => $top_category,
    'filter_sub_category' => true,
    'sort'               => $sort,
    'order'              => $order,
    'start'              => ($page - 1) * $limit,
    'limit'              => $limit
);

$product_total = $this->model_catalog_product->getTotalProducts($data);

Make sure you check the other answers if you're using a later version ;)

A: the vqmod method is the best and works easily. just add that file and anything.xml and place it in vqmod > xml

A: Just contributing with one more information, newest versions uses "ocmod", OpenCart's own vqmod feature. It can work the same way through there.

A: For Opencart 3.x:
./catalog/controller/product/category.php
find:
'filter_category_id' => $category_id,

add after:
'filter_sub_category' => true,

After change file, go to "Modification" and "Clear" and "Update" button click


text:
Q: Creating a custom cocoa pod with a storyboard in it I am creating a pod, and in the resource bundle I have a storyboard (localised).
When I try to instantiate a storyboard, an error occurred: Could not find a storyboard named 'MyStoryboard' in bundle NSBundle. The code look like this:
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"MyBundle" withExtension:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle:bundle];

MyBundle structure looks like this:
- MyBundle.bundle
  - Base.lproj
    - MyStoryboard.storyboard
  - es.lproj
    - MyStoryboard.strings

Can storyboard can be included in a bundle in the first place?
I have not seen examples of Pod that includes storyboards. If you know of any pods that share their storyboard, let me know too.

A: You want the resources option. Here are some specs that include theirs:
JCAutocompletingSearch/0.9.2/JCAutocompletingSearch.podspec
JCAutocompletingSearch/0.9.3/JCAutocompletingSearch.podspec
JCAutocompletingSearch/0.9.4/JCAutocompletingSearch.podspec
JCAutocompletingSearch/0.9.5/JCAutocompletingSearch.podspec
JCAutocompletingSearch/0.9.6/JCAutocompletingSearch.podspec
Keystone-Contacts-iOS/1.1.4/Keystone-Contacts-iOS.podspec
LumberjackConsole/2.0.0/LumberjackConsole.podspec
LumberjackConsole/2.0.1/LumberjackConsole.podspec
Mixpanel/2.1.0/Mixpanel.podspec
Mixpanel/2.2.0/Mixpanel.podspec
Mixpanel/2.2.1/Mixpanel.podspec
Mixpanel/2.2.2/Mixpanel.podspec
Mixpanel/2.2.3/Mixpanel.podspec
Mixpanel/2.3.0/Mixpanel.podspec
Mixpanel/2.3.1/Mixpanel.podspec
Mixpanel/2.3.2/Mixpanel.podspec
Mixpanel/2.3.4/Mixpanel.podspec
Mixpanel/2.3.5/Mixpanel.podspec
OpenBLE/1.0.0/OpenBLE.podspec

A: There are two things to keep in mind.

*

*You add your pod resources via a predefined bundle like
s.resources = ["Resources/Pod.bundle"]

in this case the content of your bundle will be copied to your xcode project without any "further processing". This means that storyboards or xib files will not be compiled and won't be available in your project.

*You can explicitly mention your storyboard/nib files like
s.resources = ["Resources/**/*.storyboard"]

In this case the storyboard will be compiled and will be available in your project. The downside of this (at the moment of this writing) is that you can not use localized storyboards, because all storyboards will be processed and copied at the root location of your bundle. So storyboards with the same name in different .lproj folders will be overwritten.

A: I solved my problem by using this line code to get bundle
let bundle = Bundle(for: type(of: self))

A: I currently have the same issue here. While not answering the question itself, I'd like to provide additional information that most likely is valid in your case, too:
Calling
NSString *path = [bundle pathForResource:@"MyStoryboard" ofType:@"storyboard"];
NSLog(@"path: %@",path);

will print
/var/mobile/Containers/Bundle/Application/_identifier_/MyApp.app/MyBundle.bundle/Base.lproj/MyStoryboard.storyboard

i.e. the storyboard itself is found, but not loadable "the normal way".


text:
Q: mySQL column to hold array I'm a beginner concerning coding and especially SQL and PHP.
I deal with app. 120 users.
The users can acquire app. 300 different collectible items.
When a user acquires a specific item, I would like the ID number of that particular item to be stored in the row of the user who acquired it, so that there is some information about what items the user already has (and to avoid duplicate items in his possession).
Is there a good way to store such information?
Is it even possible to set a column type to array and store it there?
Please note: I'm not lazy and I've been digging around and searching for the answer for 2 hours. I couldn't find a solution. I know of the rule that one should insert only one piece of information into one cell.

A: MySQL does not support storing arrays. However, you can use a second table to emulate an array by storing the relation between the users and items. Say you have the table users:
CREATE TABLE users (
    user_id SERIAL PRIMARY KEY,
    ...
);

And you have a table defining items:
CREATE TABLE items (
    item_id SERIAL PRIMARY KEY,
    ...
);

You can relate what items a user has using a table similar to user_items:
CREATE TABLE user_items (
    id SERIAL PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    item_id BIGINT UNSIGNED NOT NULL,
    ...,
    FOREIGN KEY (user_id)
        REFERENCES users (user_id),
    FOREIGN KEY (item_id)
        REFERENCES items (item_id)
);

Then, to determine what items user 123 has acquired, you could use JOINs similar to:
SELECT items.*
FROM users
INNER JOIN user_items
    ON user_items.user_id = users.user_id
INNER JOIN items
    ON items.item_id = user_items.item_id
WHERE users.user_id = 123; -- Or some other condition.

A: I assume you have 2 tables for example, users and items. To control which user already has a specific item, i would create an associative table, including the UserID from users and ItemID from items. This way you can now check in your user_items table if the user already has this item.
Here is a small example:
users (UserID is PK):
+--------+----------+
| UserID | UserName |
+--------+----------+
|      1 | Fred     |
|      2 | Joe      |
+--------+----------+
items (ItemID is PK):
+---------+----------+
| ItemID  | ItemName |
+---------+----------+
|       5 | Book     |
|       6 | Computer |
+---------+----------+
user_items (ItemID referencing items.ItemID, UserID referencing users.UserID):
+---------+--------+
| ItemID  | UserID |
+---------+--------+
|       5 |      1 |
|       6 |      2 |
+---------+--------+


text:
Q: Load and do the payment under different radio buttons (v2 REST API with PayPal JavaScript SDK) I am loading individual payments method under their own div container:

div id="paypal-button-container_paypal"

div id=="paypal-button-container_card"

div id=="paypal-button-container_sofort"

    let FUNDING_SOURCES = [
        paypal.FUNDING.PAYPAL,
        paypal.FUNDING.CARD,
        paypal.FUNDING.SOFORT
    ];

    FUNDING_SOURCES.forEach(function (fundingSource) {
        var button = paypal.Buttons({
            fundingSource: fundingSource,
        })
        button.render('#paypal-button-container_'+fundingSource)
    });

How can I trigger the following functions,

createOrder onApprove onInit onClick onCancel

etc... in the above code?
If I do it within the loop, each of the actions will be repeated multiple times.
Do I have to do the following for each of the payment buttons: https://developer.paypal.com/docs/checkout/apm/sofort/#link-renderpaymentbutton (if so then, is not the same code repeating again & again?)
Need your help on this. Help would be appreciated. Thank you.

A: Put the callback functions (createOrder, onApprove, etc) inside paypal.Buttons({...}).
They will be called at the appropriate time, for example createOrder occurs after a button is clicked.


text:
Q: Yii2 :: Как обновить существующий список enum? Есть в базе список enum ('name_1','name_2','name_3'). Был создан контроллер и модель, все работает отлично.
Позже я изменил список на ('new_name_1','new_name_2','new_name_3'), но в форме для ввода данных я все еще вижу старый список ('name_1','name_2','name_3'), соответственно при попытке сохранить выскакивает ошибка, т.к. идет несоответствие с базой.
Подскажите, можно ли изменить где-то список enum? Я так понимаю он где-то был зафиксирован при создании модели или контроллера.
Спасибо.

A: Нужно в модели поменять атрибуты name_1,name_2,name_3 на new_name_1, new_name_2, new_name_3

A: В общем нужно было кроме БД еще в форме поменять...


text:
Q: Can't redirect to view controller from AppDelegate when there's no logged in PFUser My root view controller is for logged in users only, therefore I have to redirect the non logged in users to the sign up/log in screen. I've tried to this from the AppDelegate, but my implementation doesn't works. When I launch the app it doesn't perform the presentLoginViewControllerAnimated method and crashes because there's no logged in users. (The Dev log also doesn't displayed)
Here's my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    if (![PFUser currentUser]) {
        NSLog(@"Dev log");
        [self presentLoginViewControllerAnimated:YES];
}

- (void)presentLoginViewControllerAnimated:(BOOL)animated {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    UINavigationController *loginController = [storyboard instantiateViewControllerWithIdentifier:@"Login"];
    [self.window.rootViewController presentViewController:loginController animated:animated completion:nil];
}

If somebody sees what did I wrong, or did something like this in the past I would really appreciate any help. In brief, I just like to hide the registration required view controllers from non logged in users. If there's any other easier solution it could be good too.

A: You have to present your root view controller to your user whether they're logged in or not, so you may need to change what you're using as your root view controller.  Try using your login view as the root view controller and then redirect them to your main view controller when they are logged in.

A: I personally would solve the problem from a software design perspective. Make your login controller in you storyboard the initial view controller. In the login controller do your check
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ([PFUser currentUser]) {
        NSLog(@"Dev log");
        [self presentLoginViewControllerAnimated:YES];
    }
}

and change your presentViewController method to load your "logged in" view and also he last line to:
[self presentViewController:loginController animated:animated completion:nil];


text:
Q: Is there an alternative for this chmod command on Debian? I'm trying to setup a chmod using this command
sudo chmod +a "www-data allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs

apparently this does not work on debian.
Any clue on how to achieve the same thing ?

A: The command seems to be correct... if you are using a version of CHMOD which supports ACLs and a filesystem which does the same.

A: The Symfony documentation at Installing and Configuring Symfony explains that if chmd +a is not supported, you can install the acl package and use the setfacl command instead of chmod +a.
Once you install the acl package, follow the directions at FilePermissions#ACLs to enable acl on your partition. This will allow you to use setfacl,


text:
Q: Join using "USING" failing on w3schools tutotial database On the tutorial database found here, where is actually possible to test commands on a pre-filled database, I was trying the following command:
SELECT *
FROM Orders INNER JOIN Customers USING (CustomerID);

Basically: Join the tables Orders and Customers using the common column CustomerID.
I get "An unspecified error occurred." Is this a bug or am I doing something wrong?
On the other hand, the following works:
SELECT * FROM Orders a INNER JOIN Customers b ON a.CustomerID = b.CustomerID;

A: It would seem that the database used on W3schools depends on your browser. If you use a browser that supports WebSQL (like Chrome) then using works. With Firefox it didn't.


text:
Q: Inheriting from a class which doesn't exist in Python So what I'm trying to do is, running a piece of code in multiple environments. In the environment(s) where the module is present, I can inherit the class from it, but where the module isn't present, I don't want my code to break and an error shouldn't come.
try:
    from school.modules import student
except ImportError:
    pass

class MyWebAPP(student.StudentClass):

I get an error that student isn't defined. I want to somehow by-pass this.
Suggestions ?

A: Assign the class to a variable and use object in case it doesn't exist.
try:
    from school.modules import student
    parent = student.StudentClass
except ImportError:
    parent = object

class MyWebAPP(parent):
    pass

This prevents that you have to repeat the whole definition of the class in both branches, but assumes that everything else inside the class doesn't need changes depending on the base class that is used.


text:
Q: Python selenium data transfer to excel - optimal solution I use the code below to transfer scraped data to excel sheet.
It works, but the downside is the execution time.
It takes around 5-10 seconds to transfer approx 200 rows x 2 columns (400 elements) that way.
I was hoping, that someone could hint me with some more efficient solution.
Python code:
driver=webdriver.Chrome(executable_path=r'C:/chromedriver.exe')
driver.get('https://www...table')
First = driver.find_elements_by_xpath('//table[@id="cr1"]/tbody/tr/td[1]')
Second = driver.find_elements_by_xpath('//table[@id="cr1"]/tbody/tr/td[2]')
xlapp = win32.Dispatch('Excel.Application')
wbook = xlapp.Workbooks.Open(r'Test.xlsm')
sheet = wbook.Worksheets('COMM')
for i in range(len(First)):
    sheet.Cells(i,1).Value = First[i]
    sheet.Cells(i,2).Value = Second[i]

A: An efficient approach would be to scrape the data from the table and using DataFrame and pandas write the data within an CSV/XLS/XLSX file as follows:
driver=webdriver.Chrome(executable_path=r'C:/chromedriver.exe')
driver.get('https://www...table')
First = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[@id="cr1"]/tbody/tr/td[1]')))]
Second = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[@id="cr1"]/tbody/tr/td[2]')))]
df = pd.DataFrame(data=list(zip(First, Second)), columns=['First', 'Second'])
print(df)
df.to_excel(r'C:\Data_Files\output_files\Test.xlsx', index=False)
driver.quit()


text:
Q: How to describe a shopping dispute? I try to state a disagreement in a deal, or someone violates the deal or contract. I did a web search on shopping dispute, and got only 8000 results.  The number implies that it is not a common usage to describe it, while correct usage usually comes out with millions of results. How to describe it?

Dispute: a disagreement or argument; a territorial dispute between the two countries

A: If there is a formal contract and one party or the other is claiming that the other has not lived up to the terms of the contract, that is a "contract dispute". Usually we use the term "contract dispute" when there is some ambiguity in the contract that both parties can make at least a plausible claim that they are right. If someone is just ignoring the contract, if it said he was supposed to pay $X or do such-and-such work and he just refuses, that's generally called "breach of contract" rather than a "contract dispute".
In cases where there is no formal contract, like when you go to a store and buy something and then claim you didn't get your money's worth in one way or another, that's a "consumer complaint".
Off the top of my head I can't think of any other related terms, but I'm sure lawyers have a boatload of them. :-)


text:
Q: Hash-table type in Lisp I found out, that in CL hash table has a type HASH-TABLE (surprisingly). However, a vector can be just VECTOR, but it also can be specified further as (vector number 12), for example.
It seems only natural for hash-table to have a list type, like, (hash-table number cons) or something, but it doesn't seem to work, and I cannot find any reference to it. Any advice?

A: TL;DR typed vectors may be optimized for memory usage, but typed hash-tables are mostly pointless.

Disclaimer: this is mostly based on intuition and it's not even close to an authoritative answer.
Typed vectors are useful because they're the most practical way to store data contiguously in memory -- if you know the type (and thanks to that, also the size) of all elements, it's trivial to allocate just enough memory to store all of them together. As you may already know, CL's bit vectors are just that: an abstraction for optimally stored, individually accessible bits. Without type information, you must store a vector of pointers to scattered pieces of actual data.
If you're familiar with how a simple hash-table is implemented, then you know that type information is less useful here. It is kinda awkward to store the actual data in the table (which is usually a vector of pointers instead), either because dealing with hash-key collisions becomes harder (or else you would end up with a linked list anyway), or because resizing the table would involve copying all the data to a new table, instead of just changing a few pointers. Of course resizing a vector also requires copying everything, but it's done in a single step, while for the hash-table it must be done once for every element, because their positions in the table will have changed. There's mostly no benefit.
Also, a typed hash-table doesn't sound very Lispy.


text:
Q: Закладки и новые окна в Chrome Есть такая часть кода:
$("#btnPublishAll").click(function (evt) {
    $("input:checkbox[name='visitselect']:checked").each(function (i, obj) {
        var url = "[@spring.url " / visit / publicate "/]?id=" + $(obj).attr("data-visit");
        window.open(url);
    });
    return false;
});

Я хочу чтобы каждое последующее окно открывалось как новая вкладка, а не новое окно. Что я имею: первая ссылка открывается как вкладка, а все последующие - как новые окна :/
Что делать?

A: Чтобы ссылка открывалась в новой табе
bla-bla

Чтоб ссылка открывала новое окно
bla-bla

При дефолтных настройках браузера это должно работать верно.
А теперь касательно Вашего кода:
$("#btnPublishAll").click(function (evt) {
    $("input:checkbox[name='visitselect']:checked").each(function (i, obj) {
        var url = "[@spring.url " / visit / publicate "/]?id=" +
                  $(obj).attr("data-visit");
        $('link').appendTo("body").click().remove();
    });
    return false;
});


text:
Q: add an attribute in a model class after deploy a appcelerator titanium app i write a app with appcelerator titanium and want to add an attribute in a model class. I must write a migration to prevent android errors with "..has no column.."
(http://docs.appcelerator.com/platform/latest/#!/guide/Alloy_Sync_Adapters_and_Migrations-section-36739597_AlloySyncAdaptersandMigrations-Migrations)
I just want to drop the table "favorites":
migration.up = function(migrator) {
    migrator.dropTable("favorites");
};

Why it doesn't work and the error message is still where?
migrator.createTable(...) also didn't work

A: create a migration file:
   alloy generate migration favorites
add the following code:
  migration.up = function(migrator) {
migrator.dropTable("favorites");

migrator.createTable({
    columns: {
        "id": 'INTEGER PRIMARY KEY AUTOINCREMENT',

        "title":"text",
        "url":"text",
        "some_new_column":"text"

     }
 });

};
migration.down = function(migrator) {
    migrator.dropTable("favorites");
};


text:
Q: How to draw text on Canvas Currently, I am able to add various Shape on Canvas by
canvas.Children.Add(line);
canvas.Children.Add(polyLine);
//...

But, how can we draw text, with various font size, font type, ... on it?

A: Add TextBlock to canvas's children.

A: In this example, they are not drawing on canvas but detecting pointer movements and than adding line shapes to the canvas. So I think you cannot draw on canvas directly. There is another post that talks about Drawing Context, so you might want to look into it.


text:
Q: sql query is slow when writing cache data on apache ignite cluster Test on apache ignite 2.7.0 and 2.3.0, if no cache data is writing, the sql query is fast, but when I writing data, the sql query becames slow, why?
And how to make sql query fast when data is writing into apache ignite cache?
Or how to seperate cache read and write on apache ignite?
Define a cache entity ABData as below and load 3000 ABDatas with Streamer.add method 10 times.
Each time after we already loaded all the ABData(suppose after 10 minutes, it means that the 3000 ABDatas have been added into the ignite cache),  run SqlFieldQuery('select * from ABData'), all the ABDatas get returned whithin 5 milliseconds.
But each time when the 3000 ABDatas is still in the loading(e.g.,each time before loading ABData, we launch another thread to query ABData with SqlFieldQuery), run SqlFieldQuery('select * from ABData'), all the ABDatas get returned after 100 milliseconds.
public class ABData {

    @QuerySqlField(index = true)
    private String code;

    @QuerySqlField(index = false)
    private String configData;

    @QuerySqlField(index = false)
    private Integer categoryID;

}

A: It's hard to say what happens here. I suggest you debug this issue, taking e.g. stack traces and trying to figure out where time is spent/where locking happens.
Then it may be some problems in your scenario, such as creating short-lived server nodes to do data streaming. They will trigger rebalancing when they come or leave.


text:
Q: Numerical computation of a formula with erf() and exp() I need to compute the following formula numerically using double precision:
$\frac {\frac{1}{2 \pi^{2} \sigma} \left(\pi^{2} \sigma \operatorname{erf}{\left (\frac{1}{\sqrt 2} \left(\frac{r}{\sigma} + \sigma\right) \right )} - \pi^{2} \sigma \operatorname{erf}{\left (\frac{1}{\sqrt 2} \left(\frac{r - b}{\sigma} + \sigma\right) \right )} + \sqrt{2} \pi^{\frac{3}{2}} \left(-1 + e^{- b}\right) e^{t}\right)} {\left(1 - \frac{1}{2} \operatorname{erf}{\left (\frac{r}{\sqrt 2 \sigma} \right )} - \frac{1}{2} \operatorname{erf}{\left (\frac{\left(b - r\right)}{\sqrt 2 \sigma} \right )}\right) e^{- r - \frac{\sigma^{2}}{2}} + \frac{1}{2} \operatorname{erf}{\left (\frac{\left(r + \sigma^{2}\right)}{\sqrt 2 \sigma} \right )} + \frac{1}{2} \operatorname{erf}{\left (\frac{\sqrt{2}}{2 \sigma} \left(b - r - \sigma^{2}\right) \right )}}$
It is guaranteed that:

*

*$\sigma > 0$. This is the parameter I control. It would be nice if the computation worked for $\sigma$ from around 1e-3 to 1e5, though.

*$r \in (0, 1e7]$.

*$b \in (0, 1e7]$.

*$t = - \frac {(b - r)^2} {2 \sigma^2} + (b - r) - \sigma^2/2 \leq 0$

The problem is that for some valid inputs, such as $\sigma=1$, $r=1111$, $b=200$, the formula results in a 0/0 division.

*

*In the numerator, $\operatorname{erf}$s in the first and second terms get rounded to 1 and cancel out. The third term underflows.

*In the denominator, the first term underflows, while the second and third ones cancel out.

How can I avoid these problems and compute this formula stably? Perhaps there are some identities for $\operatorname{erf}(a) - \operatorname{erf}(b)$ that will allow to avoid cancellation?

A: When you have problems with cancellation, the usual prescription is to subtract off the large terms analytically leaving the small ones you care about.  $\operatorname{erf}(x)$ gets very close to $1$ as $x$ gets even moderately large.  In the numerator, your cancellation happens when $b$ is rather small and $\sigma$ is rather large.  Then the term $-\frac b\sigma$ in the argument doesn't matter much.  You can test for that and use the expansion $$\operatorname{erf}(x) \approx 1+e^{-x^2} \left(-\frac1{\sqrt\pi x} + \frac 1{2 \sqrt\pi x^3} - \frac3{4 \sqrt\pi x^5} + O(x^{-7})\right)$$  You probably don't need all the terms.  The $1$s will cancel, leaving just the terms multiplied by $e^{-x^2}$.  The problem is similar in the denominator, with the same solution.


text:
Q: How to set page content to the middle of screen?
Possible Duplicate:
How to align a
 to the middle of the page

I need is to show the content of a web page in the middle of the screen, no matter what screen size it is, big or small, resolution high or low, it always gets automatically adjusted to the middle of screen.

A: Solution for the code you posted:
.center{
    position:absolute;
    width:780px;
    height:650px;
    left:50%;
    top:50%;
    margin-left:-390px;
    margin-top:-325px;
}

--
How this works?
Example: http://jsfiddle.net/953Yj/

    Lorem ipsum

.center{
    position:absolute;
    height: X px;
    width: Y px;
    left:50%;
    top:50%;
    margin-top:- X/2 px;
    margin-left:- Y/2 px;
}

*

*X would your your height.

*Y would be your width.

To position the div vertically and horizontally, divide X and Y by 2.

A: I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:
Markup:

CSS:
div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.
Edit: Credit goes to CSS-Tricks, where I got the original idea.

A: If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:

...

CSS:
#content {
    max-width: 1000px;
    margin: auto;
    left: 1%;
    right: 1%;
    position: absolute;
}

JavaScript (using jQuery):
$(function() {
    $(window).on('resize', function resize()  {
        $(window).off('resize', resize);
        setTimeout(function () {
            var content = $('#content');
            var top = (window.innerHeight - content.height()) / 2;
            content.css('top', Math.max(0, top) + 'px');
            $(window).on('resize', resize);
        }, 50);
    }).resize();
});

Demo: http://jsfiddle.net/nBzcb/

A: HTML
<!DOCTYPE html>

        <title>Center</title>

          some text

CSS
body
{
   width: 100%;
   Height: 100%;
}
#main_body
{
    background: #ff3333;
    width: 200px;
    position: absolute;
}

JS ( jQuery )
$(function(){
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var main = $("#main_body");
    $("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
                          left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});

See example here


text:
Q: Search Substring(specific value) from array index in java I want to filter specific text from a specific array in java like
String a="code=500,code1=1000"

I want to get only 500 from index 0 by searching "code="

A: One approach would be to:
Split the String by "," to an array.
Now for each element of the array, do a replaceAll to remove the text before the number.
It might not be the most optimal, but this should work:
String[] split = a.split(",");
for (String s: split) {
  String desiredText = s.replaceAll(".+=", "");
}

Then you could add the desiredText to a List or whatever it is you want to do with it.


text:
Q: Attaching unsaved Excel file to email I have an Excel form for users to fill and send as an attachment (without having to save it locally on their computer).
The code works.
Dim Names()
Names = Array("testmail@gmail.com")
ActiveWorkbook.SendMail _
Recipients:=Names(), _
Subject:="Test subject"

I would like the email just to be created and not sent until the users have attached an additional file (found on their local computer).
I wrote the following code:
Dim olapp As Object
Dim olmail As Object
Dim wb As Workbook
Set olapp = CreateObject("outlook.application")
Set olmail = olapp.CreateItem(olMailItem)
Set wb = ActiveWorkbook

With olmail
.To = "testmail@gmail.com"
.Subject = "Test Subject"
.Body = ""
.Attachments.Add wb.FullName
.Display

My problem is that only the latest saved copy will be attached to the created email, and since the users will not have the form/Excel file stored locally on their computer, an empty form (or the last saved form) will be attached to the email.
Is there any way for an email to be created, with a copy of the workbook, but not to send it?

A: i tried this one-liner in the immediate window and it managed to send an unsaved file: Application.Workbooks("Book2").SendMail("my.email@company.com","Test Subject") you can use wb from your code instead of Application.Workbooks("Book2") in my example. Note that this will send the email, without the possibility to edit it.


text:
Q: Remove white line between html table td's I'm creating an HTML email template and have finally (after hours of frustration finding more blockers of how dated HTML technology is) got a design I like. I've removed the images I'll actually use, so apologise for the gross photos. But I'm trying to remove the white cell line between two td's. I've removed cell-padding and cell-spacing, thinking that it would have a global effect on the table. But I am wrong. I've also used it on each td, but still no joy, any help will be appreciated.
P.S, thanks Gmail, for making the markup pretty ugly to look at and having to use inline style

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link href="https://fonts.googleapis.com/css?family=Nunito:300,400" rel="stylesheet">

              cursus a congue at, pharetra vel justo. Maecenas eget elit id nulla lobortis vestibulum eget fermentum nisi. Sed et tortor nunc. Proin id ornare dui. In risus arcu, aliquam et vulputate placerat, tempor ut elit. In ac placerat velit. Aliquam turpis dui,
              lobortis ut consequat et, cursus vel

                  Mauris sit

                  Mauris sit amet

            Mauris sit amet
Mauris sit amet

A: I was able to get rid of the white line with some CSS trickery. On the bottom td, I added:
margin-top: -1px;
display: inline-block;
width: 100%;

See working snippet:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link href="https://fonts.googleapis.com/css?family=Nunito:300,400" rel="stylesheet">

              cursus a congue at, pharetra vel justo. Maecenas eget elit id nulla lobortis vestibulum eget fermentum nisi. Sed et tortor nunc. Proin id ornare dui. In risus arcu, aliquam et vulputate placerat, tempor ut elit. In ac placerat velit. Aliquam turpis dui,
              lobortis ut consequat et, cursus vel

                  Mauris sit

                  Mauris sit amet

            Mauris sit amet
Mauris sit amet

A: I've had this problem in html emails viewed in Outlook on Windows desktop machines. If that is your problem, you can add this snippet before the closing

Or try this: change background-image property on your   to simply background: #114496 url(https://i.ibb.co/vV22b3P/testesttest.png);


text:
Q: How can I draw a bezier curve using Python's PIL? I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler.

A: You can use the aggdraw on top of PIL, bezier curves are supported.
EDIT:
I made an example only to discover there is a bug in the Path class regarding curveto :(
Here is the example anyway:
from PIL import Image
import aggdraw

img = Image.new("RGB", (200, 200), "white")
canvas = aggdraw.Draw(img)

pen = aggdraw.Pen("black")
path = aggdraw.Path()
path.moveto(0, 0)
path.curveto(0, 60, 40, 100, 100, 100)
canvas.path(path.coords(), path, pen)
canvas.flush()

img.save("curve.png", "PNG")
img.show()

This should fix the bug if you're up for recompiling the module...

A: Although bezier curveto paths don't work with Aggdraw, as mentioned by @ToniRuža, there is another way to do this in Aggdraw. The benefit of using Aggdraw instead of PIL or your own bezier functions is that Aggdraw will antialias the image making it look smoother (see pic at bottom).
Aggdraw Symbols
Instead of using the aggdraw.Path() class to draw, you can use the aggdraw.Symbol(pathstring) class which is basically the same except you write the path as a string. According to the Aggdraw docs the way to write your path as a string is to use SVG path syntax (see: http://www.w3.org/TR/SVG/paths.html). Basically, each addition (node) to the path normally starts with

*

*a letter representing the drawing action (uppercase for absolute path, lowercase for relative path), followed by (no spaces in between)

*the x coordinate (precede by a minus sign if it is a negative number or direction)

*a comma

*the y coordinate (precede by a minus sign if it is a negative number or direction)

In your pathstring just separate your multiple nodes with a space. Once you have created your symbol, just remember to draw it by passing it as one of the arguments to draw.symbol(args).
Bezier Curves in Aggdraw Symbols
Specifically for cubic bezier curves you write the letter "C" or "c" followed by 6 numbers (3 sets of xy coordinates x1,y1,x2,y2,x3,y3 with commas in between the numbers but not between the first number and the letter). According the docs there are also other bezier versions by using the letter "S (smooth cubic bezier), Q (quadratic bezier), T (smooth quadratic bezier)". Here is a complete example code (requires PIL and aggdraw):
print "initializing script"

# imports
from PIL import Image
import aggdraw

# setup
img = Image.new("RGBA", (1000,1000)) # last part is image dimensions
draw = aggdraw.Draw(img)
outline = aggdraw.Pen("black", 5) # 5 is the outlinewidth in pixels
fill = aggdraw.Brush("yellow")

# the pathstring:
#m for starting point
#c for bezier curves
#z for closing up the path, optional
#(all lowercase letters for relative path)
pathstring = " m0,0 c300,300,700,600,300,900 z"

# create symbol
symbol = aggdraw.Symbol(pathstring)

# draw and save it
xy = (20,20) # xy position to place symbol
draw.symbol(xy, symbol, outline, fill)
draw.flush()
img.save("testbeziercurves.png") # this image gets saved to same folder as the script

print "finished drawing and saved!"

And the output is a smooth-looking curved bezier figure:

A: def make_bezier(xys):
    # xys should be a sequence of 2-tuples (Bezier control points)
    n = len(xys)
    combinations = pascal_row(n-1)
    def bezier(ts):
        # This uses the generalized formula for bezier curves
        # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
        result = []
        for t in ts:
            tpowers = (t**i for i in range(n))
            upowers = reversed([(1-t)**i for i in range(n)])
            coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)]
            result.append(
                tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys)))
        return result
    return bezier

def pascal_row(n, memo={}):
    # This returns the nth row of Pascal's Triangle
    if n in memo:
        return memo[n]
    result = [1]
    x, numerator = 1, n
    for denominator in range(1, n//2+1):
        # print(numerator,denominator,x)
        x *= numerator
        x /= denominator
        result.append(x)
        numerator -= 1
    if n&1 == 0:
        # n is even
        result.extend(reversed(result[:-1]))
    else:
        result.extend(reversed(result))
    memo[n] = result
    return result

This, for example, draws a heart:
from PIL import Image
from PIL import ImageDraw

if __name__ == '__main__':
    im = Image.new('RGBA', (100, 100), (0, 0, 0, 0))
    draw = ImageDraw.Draw(im)
    ts = [t/100.0 for t in range(101)]

    xys = [(50, 100), (80, 80), (100, 50)]
    bezier = make_bezier(xys)
    points = bezier(ts)

    xys = [(100, 50), (100, 0), (50, 0), (50, 35)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    xys = [(50, 35), (50, 0), (0, 0), (0, 50)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    xys = [(0, 50), (20, 80), (50, 100)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    draw.polygon(points, fill = 'red')
    im.save('out.png')

A: A bezier curve isn't that hard to draw yourself. Given three points A, B, C you require three linear interpolations in order to draw the curve. We use the scalar t as the parameter for the linear interpolation:
P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C

This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so:
Pfinal = P0 * t + (1 - t) * P1

There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some dt (delta t) and we need to be aware that 0 <= t <= 1. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.

A: I found a simpler way creating a bezier curve (without aggraw and without complex functions).
import math
from PIL import Image
from PIL import ImageDraw

image = Image.new('RGB',(1190,841),'white')
draw = ImageDraw.Draw(image)
curve_smoothness = 100

#First, select start and end of curve (pixels)
curve_start = [(167,688)]
curve_end = [(678,128)]

#Second, split the path into segments
curve = []
for i in range(1,curve_smoothness,1):
    split = (curve_end[0][0] - curve_start[0][0])/curve_smoothness
    x = curve_start[0][0] + split * i
    curve.append((x, -7 * math.pow(10,-7) * math.pow(x,3) - 0.0011 * math.pow(x,2) + 0.235 * x + 682.68))

#Third, edit any other corners of polygon
other =[(1026,721), (167,688)]

#Finally, combine all parts of polygon into one list
xys = curve_start + curve + curve_end + other #putting all parts of the polygon together
draw.polygon(xys, fill = None, outline = 256)

image.show()


text:
Q: How would I start an inmemory version of cockroachDB to run my BDD? Hello all I am working creating on BDD's with cockroach DB. Unfortunately I am not able to find any reference document in order to create a BDD for cockroach DB.

A: If by BDD you mean behaviour-driven development, BDD isn't something you "create", it's a style of development that is guided and tested by the behaviours your application is intended to provide. I don't think CockroachDB offers any docs specifically related to developing using BDD, but there is a doc for general testing best practices with CockroachDB . Alternatively, a little background reading might be helpful:
BDD in general
and applying it to databases


text:
Q: angular rxjs: handle multiple http requests I have following pseudocode
objects = [obj1, obj2, obj3]
for obj in objects {
user: http.get(obj1.user_id)
product: http.get(obj1.product_id)
}.subscribe(results => {

do something with results

})

What I want here is that, I loop through an array of objects and for each object get related user and product and then subscribe to do something with the user and product. How can I do that?

A: You could use RxJS forkJoin along with Array#map to trigger multiple observables in parallel.
const objects = [obj1, obj2, obj3];

forkJoin(
  objects.map(obj =>           // <-- `Array#map` function
    forkJoin({
      user: http.get(obj.user_id)
      product: http.get(obj.product_id)
    })
  )
).subscribe({
  next: (res) => {
    console.log(res);
    // use `res`
  },
  error: (err) => {}
});

/*
output in subscription:
[
  {
    user: result from `http.get(obj1.user_id)`,
    product: result from `http.get(obj1.product_id)`,
  },
  {
    user: result from `http.get(obj2.user_id)`,
    product: result from `http.get(obj2.product_id)`,
  },
  {
    user: result from `http.get(obj3.user_id)`,
    product: result from `http.get(obj3.product_id)`,
  }
]
*/

A: You could use the zip() operator to combine your requests and execute some code once every request has finished:
const sourceOne = http.get(obj1.product_id);
const sourceTwo = http.get(obj2.product_id);

zip(sourceOne, sourceTwo).subscribe(val => {
    // do something
});


text:
Q: syntax error on varbinary(-1) I am receiving a syntax error:

MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server
  version for the right syntax to use
  near '-1) NULL,   PRIMARY KEY
  (diagram_id),   UNIQUE INDEX
  UK_principal_name (p' at line 6

This is what i am trying to run. i have looked that the lines it is telling me is incorrect and i have yet to find the correct syntax to use. any help would be appreciated.
    DROP TABLE IF EXISTS `teamfocus_dbo`.`sysdiagrams`;
CREATE TABLE `teamfocus_dbo`.`sysdiagrams` (
  `name` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `principal_id` INT(10) NOT NULL,
  `diagram_id` INT(10) NOT NULL AUTO_INCREMENT,
  `version` INT(10) NULL,
  `definition` VARBINARY(-1) NULL,
  PRIMARY KEY (`diagram_id`),
  UNIQUE INDEX `UK_principal_name` (`principal_id`, `name`)
)
ENGINE = INNODB;

A: Try changing the VARBINARY(-1) to a positive length, like VARBINARY(1)

A: Pretty sure you can't have negative length columns... change VARBINARY(-1) to a positive length.
Maybe you're meaning to set the default value to -1?
`definition` VARBINARY(1) NULL DEFAULT -1


text:
Q: Get sub from cognito user in amazon webservices I sign up a new user in the cognito in AWS. Here is the code (JavaScript):
userPool.signUp(username, password, attributeList, null, function(err, result){
     if (err) {
        console.log(err);
        return;
     }
     cognitoUser = result.user;
     console.log("cognitoUser: ", cognitoUser);
});

My question is: How get I get the sub from the new user?
cognitoUser just contains the username. I didn't find any method for it. Can anybody help me?

A: The solution is: adminGetUser()
You should call this message in a lambda function.
Probably you will get the error message that you are not authorized. So, you must add arn:aws:iam::aws:policy/AmazonCognitoPowerUser to your iotSam.yaml.
Now, it should work.


text:
Q: Groupby values in 2nd column, pick value in 1st column and plot values [against that first column value] from each of remaining (three) columns Right off the bat I want to apologize if I did not follow any formatting rules.
My raw data looks like the following:
{'SOC_percent\tTemp_degC\tmeasuredResistance_discharge_mOhm_2s\tmeasuredResistance_discharge_mOhm_10s\tmeasuredResistance_discharge_mOhm_30s': {0: '5\t-30\t10.41234227\t17.87211262\t39.78919418', 1: '5\t-25\t9.005372364\t14.65298748\t31.43701839', 2: '5\t-20\t7.00477665\t11.96754116\t24.39672451', 3: '5\t-10\t4.76738317\t8.501801895\t16.57636139', 4: '5\t0\t3.287172099\t5.57923204\t9.111447624', 5: '5\t5\t2.284002209\t4.236576914\t6.727561459', 6: '5\t10\t1.869262009\t3.249023803\t5.020990525', 7: '5\t20\t1.27797832\t1.963468963\t2.881752003', 8: '5\t25\t0.936303318\t1.546113511\t2.21395074', 9: '5\t35\t0.707298817\t1.091719664\t1.630883462', 10: '5\t45\t0.543718996\t0.787786805\t1.224869972', 11: '5\t50\t0.479637917\t0.674293305\t1.068590803', 12: '10\t-30\t8.537862111\t13.76174563\t27.78918201', 13: '10\t-25\t6.685843592\t10.49706991\t20.26777709', 14: '10\t-20\t5.09106992\t7.978204366\t14.64512627', 15: '10\t-10\t3.139438794\t4.984757272\t8.55042102', 16: '10\t0\t1.991892456\t2.847802776\t4.272164584', 17: '10\t5\t1.509715963\t2.222798386\t3.332446494', 18: '10\t10\t1.21478403\t1.750446842\t2.62220956', 19: '10\t20\t0.804205279\t1.112408203\t1.663905423', 20: '10\t25\t0.632856291\t0.897095496\t1.340630939', 21: '10\t35\t0.526353672\t0.71202232\t1.078469491', 22: '10\t45\t0.442828733\t0.573468612\t0.879484805', 23: '10\t50\t0.407810006\t0.517250198\t0.797987409', 24: '15\t-30\t6.417216981\t9.928443396\t19.83665094', 25: '15\t-25\t5.204660377\t7.83495283\t15.09165094', 26: '15\t-20\t4.063358491\t6.200141509\t11.37070755', 27: '15\t-10\t2.622933962\t4.123330189\t7.229716981', 28: '15\t0\t1.767141509\t2.592150943\t3.923669811', 29: '15\t5\t1.334830189\t2.047745283\t3.042', 30: '15\t10\t1.103283019\t1.625367925\t2.386603774', 31: '15\t20\t0.764179245\t1.049566038\t1.513518868', 32: '15\t25\t0.616150943\t0.8775\t1.240150943', 33: '15\t35\t0.500009434\t0.702981132\t1.006518868', 34: '15\t45\t0.423358491\t0.57690566\t0.826358491', 35: '15\t50\t0.397910377\t0.51754717\t0.759028302', 36: '20\t-30\t4.841886792\t6.89245283\t12.58301887', 37: '20\t-25\t3.826783019\t5.370471698\t9.450754717', 38: '20\t-20\t3.027037736\t4.226226415\t7.066603774', 39: '20\t-10\t1.916518868\t2.734415094\t4.374622642', 40: '20\t0\t1.298650943\t1.716490566\t2.423150943', 41: '20\t5\t1.032518868\t1.411235849\t1.96704717', 42: '20\t10\t0.867198113\t1.152584906\t1.612735849', 43: '20\t20\t0.614556604\t0.78159434\t1.103896226', 44: '20\t25\t0.526622642\t0.691698113\t0.953169811', 45: '20\t35\t0.435009434\t0.597509434\t0.822556604', 46: '20\t45\t0.3835\t0.522943396\t0.706783019', 47: '20\t50\t0.373075472\t0.475849057\t0.66704717', 48: '25\t-30\t3.597688679\t4.51259434\t6.929858491', 49: '25\t-25\t2.749377358\t3.451745283\t5.085330189', 50: '25\t-20\t2.223735849\t2.706084906\t3.755896226', 51: '25\t-10\t1.369537736\t1.676632075\t2.206320755', 52: '25\t0\t0.940537736\t1.05545283\t1.290556604', 53: '25\t5\t0.797660377\t0.934160377\t1.155773585', 54: '25\t10\t0.686301887\t0.796311321\t1.028962264', 55: '25\t20\t0.501726415\t0.574943396\t0.792386792', 56: '25\t25\t0.461622642\t0.55495283\t0.739773585', 57: '25\t35\t0.382273585\t0.522698113\t0.687650943', 58: '25\t45\t0.349773585\t0.487377358\t0.617867925', 59: '25\t50\t0.353759434\t0.446415094\t0.59959434', 60: '30\t-30\t2.64306337\t2.770057921\t4.983524437', 61: '30\t-25\t2.086447367\t2.250982857\t4.314656224', 62: '30\t-20\t1.727334342\t1.854598294\t3.523595931', 63: '30\t-10\t1.165635292\t1.26288389\t1.583111294', 64: '30\t0\t0.831038221\t0.929507256\t1.153892595', 65: '30\t5\t0.743804417\t0.822642168\t1.020970617', 66: '30\t10\t0.639777679\t0.731319903\t0.907245747', 67: '30\t20\t0.480690569\t0.58496518\t0.725098507', 68: '30\t25\t0.43765325\t0.526189514\t0.651881429', 69: '30\t35\t0.400254942\t0.48262454\t0.611746277', 70: '30\t45\t0.368114597\t0.445089067\t0.576382366', 71: '30\t50\t0.353712659\t0.428235255\t0.560248926', 72: '35\t-30\t2.597669811\t2.713136792\t3.087745283', 73: '35\t-25\t2.044617925\t2.206014151\t2.537575472', 74: '35\t-20\t1.691103774\t1.808778302\t2.069207547', 75: '35\t-10\t1.144858491\t1.233957547\t1.57545283', 76: '35\t0\t0.805448113\t0.910122642\t1.114504717', 77: '35\t5\t0.728674528\t0.806490566\t0.983891509', 78: '35\t10\t0.633504717\t0.709603774\t0.882773585', 79: '35\t20\t0.472783019\t0.576292453\t0.710462264', 80: '35\t25\t0.433691038\t0.517485849\t0.635466981', 81: '35\t35\t0.397174528\t0.473948113\t0.602292453', 82: '35\t45\t0.369028302\t0.441570755\t0.571570755', 83: '35\t50\t0.354771226\t0.425964623\t0.557681604', 84: '40\t-30\t2.556584906\t2.660707547\t2.924632075', 85: '40\t-25\t2.006292453\t2.164622642\t2.403896226', 86: '40\t-20\t1.660443396\t1.771066038\t1.950245283', 87: '40\t-10\t1.127075472\t1.210349057\t1.530688679', 88: '40\t0\t0.784292453\t0.888660377\t1.081084906', 89: '40\t5\t0.717943396\t0.789933962\t0.955377358', 90: '40\t10\t0.62645283\t0.694886792\t0.861311321', 91: '40\t20\t0.466650943\t0.56954717\t0.696971698', 92: '40\t25\t0.431698113\t0.512273585\t0.623509434', 93: '40\t35\t0.395641509\t0.469349057\t0.594933962', 94: '40\t45\t0.368415094\t0.438198113\t0.567584906', 95: '40\t50\t0.354311321\t0.422745283\t0.555075472', 96: '45\t-30\t2.51795283\t2.612570755\t2.78604717', 97: '45\t-25\t1.972259434\t2.127523585\t2.288613208', 98: '45\t-20\t1.633462264\t1.737646226\t1.84354717', 99: '45\t-10\t1.111745283\t1.189806604\t1.498188679', 100: '45\t0\t0.767429245\t0.872103774\t1.053183962', 101: '45\t5\t0.709051887\t0.777056604\t0.93115566', 102: '45\t10\t0.621240566\t0.682622642\t0.843528302', 103: '45\t20\t0.461745283\t0.564028302\t0.685933962', 104: '45\t25\t0.430257075\t0.507674528\t0.613391509', 105: '45\t35\t0.394476415\t0.465363208\t0.588801887', 106: '45\t45\t0.36804717\t0.435438679\t0.564212264', 107: '45\t50\t0.354035377\t0.42007783\t0.552775943', 108: '50\t-30\t2.487324752\t2.571003179\t2.624742662', 109: '50\t-25\t1.941874744\t2.091626265\t2.198386641', 110: '50\t-20\t1.614132861\t1.717907652\t1.86246071', 111: '50\t-10\t1.101742804\t1.179615538\t1.34124724', 112: '50\t0\t0.755056968\t0.842862796\t1.030306432', 113: '50\t5\t0.707658681\t0.757797046\t0.921586561', 114: '50\t10\t0.61064567\t0.683998956\t0.82747666', 115: '50\t20\t0.461607921\t0.56313721\t0.674500603', 116: '50\t25\t0.431767087\t0.51355881\t0.612027845', 117: '50\t35\t0.395653787\t0.469831833\t0.585359573', 118: '50\t45\t0.364559062\t0.432224387\t0.5614416', 119: '50\t50\t0.350606411\t0.415369189\t0.550384704', 120: '55\t-30\t2.44804717\t2.529174528\t2.582462264', 121: '55\t-25\t1.917070755\t2.06620283\t2.113235849', 122: '55\t-20\t1.590537736\t1.683683962\t1.666943396', 123: '55\t-10\t1.088443396\t1.157919811\t1.469981132', 124: '55\t0\t0.746580189\t0.853707547\t1.013938679', 125: '55\t5\t0.696787736\t0.762339623\t0.895589623', 126: '55\t10\t0.616334906\t0.66545283\t0.819', 127: '55\t20\t0.455613208\t0.556669811\t0.671216981', 128: '55\t25\t0.42903066\t0.500316038\t0.598674528', 129: '55\t35\t0.39325\t0.459231132\t0.580216981', 130: '55\t45\t0.36804717\t0.431759434\t0.559306604', 131: '55\t50\t0.354035377\t0.416398585\t0.549096698', 132: '60\t-30\t2.416773585\t2.493915094\t2.517462264', 133: '60\t-25\t1.895915094\t2.041981132\t2.053141509', 134: '60\t-20\t1.57459434\t1.663141509\t1.597037736', 135: '60\t-10\t1.080471698\t1.146575472\t1.474273585', 136: '60\t0\t0.74259434\t0.851867925\t1.00259434', 137: '60\t5\t0.693415094\t0.7605\t0.884245283', 138: '60\t10\t0.616641509\t0.66054717\t0.812254717', 139: '60\t20\t0.454386792\t0.554830189\t0.667537736', 140: '60\t25\t0.429245283\t0.497556604\t0.594075472', 141: '60\t35\t0.393188679\t0.457084906\t0.577764151', 142: '60\t45\t0.368415094\t0.430839623\t0.557773585', 143: '60\t50\t0.354311321\t0.415386792\t0.547716981', 144: '65\t-30\t2.38795283\t2.462948113\t2.476990566', 145: '65\t-25\t1.879051887\t2.022051887\t2.011443396', 146: '65\t-20\t1.562330189\t1.646891509\t1.539396226', 147: '65\t-10\t1.07495283\t1.13829717\t1.490830189', 148: '65\t0\t0.742900943\t0.854933962\t0.996768868', 149: '65\t5\t0.691882075\t0.762339623\t0.877193396', 150: '65\t10\t0.618787736\t0.65809434\t0.809188679', 151: '65\t20\t0.454386792\t0.554216981\t0.666311321', 152: '65\t25\t0.430011792\t0.495410377\t0.591316038', 153: '65\t35\t0.393495283\t0.455551887\t0.576537736', 154: '65\t45\t0.369028302\t0.430533019\t0.556853774', 155: '65\t50\t0.354771226\t0.414926887\t0.546643868', 156: '70\t-30\t2.361584906\t2.436273585\t2.46104717', 157: '70\t-25\t1.866481132\t2.006415094\t1.988141509', 158: '70\t-20\t1.553745283\t1.634933962\t1.494018868', 159: '70\t-10\t1.071886792\t1.133084906\t1.519650943', 160: '70\t0\t0.7475\t0.86290566\t0.996462264', 161: '70\t5\t0.692188679\t0.767858491\t0.874433962', 162: '70\t10\t0.622773585\t0.65809434\t0.809801887', 163: '70\t20\t0.455613208\t0.554830189\t0.667537736', 164: '70\t25\t0.431330189\t0.493877358\t0.590396226', 165: '70\t35\t0.394169811\t0.454632075\t0.576537736', 166: '70\t45\t0.369886792\t0.430839623\t0.55654717', 167: '70\t50\t0.355415094\t0.415018868\t0.545877358', 168: '75\t-30\t2.337669811\t2.413891509\t2.469632075', 169: '75\t-25\t1.85820283\t1.995070755\t1.983235849', 170: '75\t-20\t1.548839623\t1.627268868\t1.46090566', 171: '75\t-10\t1.071273585\t1.130938679\t1.360735849', 172: '75\t0\t0.756391509\t0.875783019\t1.001674528', 173: '75\t5\t0.694334906\t0.777056604\t0.875966981', 174: '75\t10\t0.628599057\t0.66054717\t0.81409434', 175: '75\t20\t0.458066038\t0.556669811\t0.671216981', 176: '75\t25\t0.433200472\t0.492957547\t0.591316038', 177: '75\t35\t0.395212264\t0.454325472\t0.577764151', 178: '75\t45\t0.370990566\t0.431759434\t0.556853774', 179: '75\t50\t0.356242925\t0.415662736\t0.545417453', 180: '80\t-30\t2.316207547\t2.395801887\t2.502745283', 181: '80\t-25\t1.854216981\t1.988018868\t1.996726415', 182: '80\t-20\t1.547613208\t1.623896226\t1.440056604', 183: '80\t-10\t1.073113208\t1.131858491\t1.314084906', 184: '80\t0\t0.769575472\t0.893566038\t1.01240566', 185: '80\t5\t0.698320755\t0.789933962\t0.881792453', 186: '80\t10\t0.636264151\t0.66545283\t0.822066038', 187: '80\t20\t0.461745283\t0.559735849\t0.677349057', 188: '80\t25\t0.435622642\t0.492650943\t0.594075472', 189: '80\t35\t0.396622642\t0.454632075\t0.580216981', 190: '80\t45\t0.372339623\t0.433292453\t0.557773585', 191: '80\t50\t0.357254717\t0.416858491\t0.545264151', 192: '85\t-30\t2.297198113\t2.382004717\t2.560386792', 193: '85\t-25\t1.854523585\t1.985259434\t2.028613208', 194: '85\t-20\t1.550066038\t1.624816038\t1.431471698', 195: '85\t-10\t1.07740566\t1.13584434\t1.379698113', 196: '85\t0\t0.787051887\t0.916254717\t1.02865566', 197: '85\t5\t0.704146226\t0.806490566\t0.891910377', 198: '85\t10\t0.645768868\t0.672811321\t0.833716981', 199: '85\t20\t0.466650943\t0.564028302\t0.685933962', 200: '85\t25\t0.438596698\t0.492957547\t0.598674528', 201: '85\t35\t0.398400943\t0.455551887\t0.583896226', 202: '85\t45\t0.373933962\t0.435438679\t0.559306604', 203: '85\t50\t0.358450472\t0.418606132\t0.545417453', 204: '90\t-30\t2.29946844\t2.383584796\t2.489622642', 205: '90\t-25\t1.86032786\t1.974433564\t2.103911344', 206: '90\t-20\t1.566292427\t1.657804525\t1.4556559', 207: '90\t-10\t1.096469402\t1.168700917\t1.315493648', 208: '90\t0\t0.809138285\t0.89081257\t1.0451439', 209: '90\t5\t0.727080727\t0.796859124\t0.93661049', 210: '90\t10\t0.63385084\t0.715685937\t0.842639129', 211: '90\t20\t0.488533958\t0.583686013\t0.689454905', 212: '90\t25\t0.446604847\t0.529868037\t0.626826454', 213: '90\t35\t0.404214431\t0.478697896\t0.591510491', 214: '90\t45\t0.368150895\t0.435245215\t0.56020084', 215: '90\t50\t0.35210775\t0.415939509\t0.54586218', 216: '95\t-30\t2.266537736\t2.367287736\t2.549254717', 217: '95\t-25\t1.868014151\t1.992617925\t2.147575472', 218: '95\t-20\t1.566009434\t1.639533019\t1.45109434', 219: '95\t-10\t1.093349057\t1.153014151\t1.447716981', 220: '95\t0\t0.834882075\t0.976349057\t1.077712264', 221: '95\t5\t0.721316038\t0.850641509\t0.925023585', 222: '95\t10\t0.67029717\t0.694886792\t0.868056604', 223: '95\t20\t0.480141509\t0.576292453\t0.710462264', 224: '95\t25\t0.446200472\t0.495410377\t0.613391509', 225: '95\t35\t0.403061321\t0.459231132\t0.594933962', 226: '95\t45\t0.377858491\t0.441570755\t0.564212264', 227: '95\t50\t0.361393868\t0.423757075\t0.546643868', 228: '100\t-30\t2.254886792\t2.366367925\t2.580481132', 229: '100\t-25\t1.881198113\t2.002735849\t2.234650943', 230: '100\t-20\t1.5795\t1.653330189\t1.479301887', 231: '100\t-10\t1.105\t1.166198113\t1.450122642', 232: '100\t0\t0.865235849\t1.013754717\t1.110518868', 233: '100\t5\t0.732660377\t0.878235849\t0.948018868', 234: '100\t10\t0.685320755\t0.709603774\t0.890745283', 235: '100\t20\t0.488726415\t0.584264151\t0.72640566', 236: '100\t25\t0.450830189\t0.497556604\t0.623509434', 237: '100\t35\t0.405943396\t0.461990566\t0.602292453', 238: '100\t45\t0.380188679\t0.445556604\t0.567584906', 239: '100\t50\t0.363141509\t0.427160377\t0.547716981'}}

I want the following plot from this raw data (x axis = 2s, 10s and 30s; y axis = resistance data). The raw data doesn't contain any numeric information for time_seconds.

I was able to achieve this via MS Excel 2016, using pivot tables and tables. It took a while but I was able to build a template. Then I came across some plots people have uploaded to the internet using Pandas and Seaborn, which got me thinking about reducing the time and effort it took to build the excel template. I don't have anything higher than seaborn 0.8.1 and I don't think I will be able to upgrade to anything higher than that version.
My questions are: 1) is it possible to develop something similar in Python 3.6 and Pandas such that I can get a similar looking plot as the one above? 2) If yes, how would I go about accomplishing this (knowing that the raw data doesn't contain values for time (in seconds)?
Thanks

A: Yes, indeed you can do this with pandas and matplotlib. Consider for example the following function:
def myplotting(dt, SOC_p, temp):
    """plot data at selected SOC_percent and temperature.

    dt: the dataframe
    SOC_p: a list of 'SOC_percent' values. A line for each percentage will be plotted.
    temp: numeric, a single temperature value.
    """
    x = [2, 10, 30]
    selplt = dt.loc[(dt['SOC_percent'].isin(SOC_p)) & (dt['Temp_degC'] == temp)].drop('Temp_degC', axis=1).set_index('SOC_percent')
    for prc in SOC_p:
        plt.plot(x, selplt.loc[prc], label=f'SOC percent: {prc:d}')
    plt.title(f'Temp_degC: {temp:d}')
    plt.xlabel('Time (s)')
    plt.ylabel('Discharge Resistance (mOhm)')
    plt.legend()
    plt.grid(True)
    plt.show()

The function works with your dataframe. You need to give it as argument your dataframe, a list of 'SOC_percent' values and a temperature value.
First the relevant row at the requested temperature and percentage values are selected using loc. Then, the plot is produced with a for loop (a line for each percentage value). Finally, title, label and legend are added.
For example, to reproduce your plot, you do:
myplotting(df, [10, 20, 30], -10)

where df is your dataframe. The following plot will be produced:


text:
Q: Angular not submitting parameter with ng-click I'm trying to submit a standard form within an angular app.
Everything works well until I tried to add ng-click to the submit button of the form
The action on the click is just cosmetic to give the user some feedback.
The behavior I have is a bit strange. The submit is done and the call to the click behavior are both called, however, there is no parameters submitted with the form.
I've been googling a bit, and people seems to say that using ng-click on a form disable the submit, but it doesn't, Every works fine , except the form parameters which are not send.
I know I can probably redefine my own submit function, intercept the post using ng-submit and do the post myself, it just seems an overkill, as I want to do is almost working.
(in that case, how do you I get the form parameters from within the angular callback ?)
Update
Here is a live example : http://jsfiddle.net/hHapg/5/.If you check a box and submit, there is no parameter on the URL.
If you edit the file and remove the ng-click on the submit button, it works.
<form ng-app="test" action="/echo/jsonp" name="orders" target="_blank" ng-controller="test">

            <input  type="checkbox" name="order_ids{{i}}" value="{{order.orderId}}"></input>

            {{order.orderId}} : {{ order.checked}}

    <input type="submit" name="action" value="Picking List" class="btn btn-primary picked" ng-clik="submit(true)">
</form>

Solution
Found the problem. Even though the real code wasn't exactly the one I published. with the help of Langdon I manage to solve it. The problem was I had an hardcoded array in the form declaration (not in the ng-repeat as in my example). (It was hardcoded from an angular point of view, but in fact generated at runtime). Moving this array to the top (same as ng-ap), solved the prome.

A: Are you setting the name attribute on all your input and select tags?  I imagine most Angular examples do not include the name attribute because submitting forms seems a thing of the past.
The simplified example below works fine.  I would need to see your specific code to help you troubleshoot what else the problem might be.
http://jsfiddle.net/langdonx/DUV9q/
HTML:
<form ng-app="test" ng-controller="test" action="/echo/jsonp/" method="get">
    <input type="text" name="value1" ng-model="value1"/>
    <input type="text" name="value2" ng-model="value2"/>
    <input type="submit" ng-click="submit()">

JavaScript:
var app = angular.module('test', []);

app.controller('test', function ($scope, $http) {
    $scope.value1 = "val 1 here";
    $scope.value2 = "and val 2 here";

    $scope.submit = function () {
        alert('it should submit now, if it worked, you\'ll see some json');
    }
});