text:
Q: How to build Kie session when using dsl and dslr files? I am new at drools. I have executed rules from my drl file.
Here is my drl file.
rule "Person is 21"
salience 1
    when
        $person : Person(age>=21,car.equalsIgnoreCase("duster"))
    then
        System.out.println($person.name);
end

here is my model file
public class Person
{
    private String name;
    private int age;
    private String car;

    public Person()
    {

    }

    public Person(String name, int age,String car)
    {
        this.name = name;
        this.age = age;
        this.car=car;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public String getCar() {
        return car;
    }

    public void setCar(String car) {
        this.car = car;
    }

}

Here is my rule runner method code that takes rules and facts as arguments and builds kie session and fires rules
 public void runRules(String[] rules, Object[] facts)
    {

        KieServices kieServices = KieServices.Factory.get();
        KieResources kieResources = kieServices.getResources();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        KieRepository kieRepository = kieServices.getRepository();

        for(String ruleFile : rules)
        {
            Resource resource = kieResources.newClassPathResource(ruleFile);

            // path has to start with src/main/resources
            // append it with the package from the rule
            kieFileSystem.write( resource);
        }

        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);

        kb.buildAll();

        if (kb.getResults().hasMessages(Level.ERROR))
        {
            throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
        }

        KieContainer kContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());

        KieSession kSession = kContainer.newKieSession();

        for (Object fact : facts)
        {
            kSession.insert(fact);
        }

        kSession.fireAllRules();
    }

What changes should i do when I am using a dslr file(below is the dslr file)
rule "My First Rule"

    when
        Person is at least 21 and car is "duster"
    then
        Log : "hello world"

end

In eclipse the drl file generated from the dslr file is correct.
Below is the rule in the drl file generated by the dsl expander(which I could see in the drl viewer in eclipse for the above dslr)
rule "My First Rule"

    when
        i: Person(age > 21, car=="duster")
    then
        System.out.println("hello world");

end

I tried running the same rule from my drl file and it executed successfully
The problem I am facing is that I tried passing both DSL and DSLR files as arguments to the rule resource
Resource resource = kieResources.newClassPathResource("MyDslr.dslr","dslExample.dsl");

and I am getting the following exception
Exception in thread "main" java.lang.RuntimeException: Build Errors:
Error Messages:
Message [id=1, level=ERROR, path=MyDslr.dslr, line=17, column=0
   text=[17] No mapping entries for expanding:         Person is at least 21 and
 car is "duster"]
Message [id=2, level=ERROR, path=MyDslr.dslr, line=17, column=0
   text=[17] Unable to expand: Person is at least 21 and car is "duster"]
Message [id=3, level=ERROR, path=MyDslr.dslr, line=19, column=0
   text=[19] No mapping entries for expanding:         Log : "hello world"]
Message [id=4, level=ERROR, path=MyDslr.dslr, line=19, column=0
   text=[19] Unable to expand:         Log : "hello world"]
Message [id=5, level=ERROR, path=MyDslr.dslr, line=17, column=0
   text=[ERR 102] Line 17:15 mismatched input 'is' in rule "My First Rule"]
---
Warning Messages:
---
Info Messages:

    at controller.RuleRunner.runRules(RuleRunner.java:43)
    at mainPackage.Main.main(Main.java:21)

Here is how my dsl file looks like in eclipse(and it is converting the dslr in drl and the converted rule gives no exception when is rul it directly from the drl file)

Please help me out here. And if there are examples of how to fire rules using kie api and dslr and dsl files then that will also help.
Thanks

A: The call
... = kieResources.newClassPathResource("MyDslr.dslr","dslExample.dsl")

can't be correct - compare the Javadoc for this method: the second argumen should indicate an encoding.
This sequence of statements, however, works:
FileInputStream fis1 = new FileInputStream( "simple/simple.dsl" );
kfs.write( "src/main/resources/simple.dsl",
           kieServices.getResources().newInputStreamResource( fis1 ) );
FileInputStream fis2 = new FileInputStream( "simple/simple.dslr" );
kfs.write( "src/main/resources/simple.dslr",
           kieServices.getResources().newInputStreamResource( fis2 ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();

You should call your method runRules(String[] rules, Object[] facts) with an array of pathnames, DSL as well as DSLR.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap checkbox size wrong with smaller body font I have set my default font size to be based on 10px via 62.5%, and then set the body to be 1.4rem. This seems to cause issues with the custom checkbox controls and they no longer align correctly.
I'm using Bootstrap 4's SASS files combined with my own. Is there something in the variables file that I'm missing to fix this? Or maybe some overrides I need to do? I've tried messing with various padding, margins, font sizes, etc. but the way they have this working isn't obvious.
Here is what I have set for the default font sizes for the site:
html {
  font-size: 62.5%;
}
body {
  font-size: 1.4rem;
}

And here is the HTML

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

JSFiddle
To sum up, basically I need the ability to change the body font size and yet still have the checkbox to still work correctly and be the same height as the input fields when they are next to each other.

A: You can make the parent element flex and use align-items to center vertically. You would also need to use non-absolute position on the checkbox element. That will keep them centered vertically regardless the font size of the page.

html {
  font-size: 62.5%;
}

body {
  font-size: 1.4rem;
}

.custom-control {
  display: flex;
  align-items: baseline;
}
.custom-control-indicator {
  position: static;
  margin: 0 .5rem 0 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

You could also use top: 50%; transform: translateY(-50%); to center the checkbox vertically, then set the line-height of the text to 1 so it doesn't affect vertical alignment.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

A: A simple solution would be to change the styles for the checkbox:
.custom-control-indicator {
    height: 1.4rem;
    width: 1.4rem;
    top: calc(1.4rem * 0.25);
}

Change the 1.4rem as required to the same size as the body font-size (you can also set this up to work automatically using SASS variables


text:
Q: Reload the current page in angula6 with MVC when we reload the current page(angular6), i got the below error.
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /chapters/chapters
Please help me.

A: Can you please elaborate a more?
Because if the route is correct and component is correctly defined in routing, then it shouldn't be throwing an error.
Server Error in '/' Application. The resource cannot be found. Description: HTTP 404.
Its clearly saying that route is not found. Please check the routing file.


text:
Q: Running frequencies to see combinations of values for one variable I have one variable (type of medication) that has about 16 different values (e.g., aspirin, metformin, etc.). As I was completing a variety of characteristics for this variable, each medication is listed as a case in SPSS (ie 16 long for 16 medications).
I was hoping there could be a way to run frequencies of combinations that occur for this variable (eg, frequency that this combination occurs in the variable: aspirin + metformin).
I hope that made sense, thank you in advance!

A: assuming you have other variables in the dataset, and that you have a single identifier column (referred to as 'Identifier', and the variable containing the medications is called 'Medications'.
Change 'FLAG.Var1 TO FLAG.VarN' to represent the first and last FLAG variables after you restructure.
DATASET COPY COMBINATIONS.
DATASET ACTIVATE COMBINATIONS.
MATCH FILES /FILE = *
/KEEP = Identifier Medications.
EXECUTE.

COMPUTE FLAG = 1.
EXECUTE.
ALTER TYPE FLAG (F12.0).
ALTER TYPE FLAG (A12).
SORT CASES BY Identifier Medications.
CASESTOVARS
  /ID= Identifier
  /INDEX=Medications
  /GROUPBY=VARIABLE.
STRING Combination (A64).
COMPUTE Combination = CONCAT(FLAG.Var1 TO FLAG.VarN).
EXECUTE.
FRE Combination.


text:
Q: On the limit of some average of the function Let $f$ be continuous, nonzero on $[a,b]$. For $p\in \mathbb R$, define
$$\Phi_p(f)=\left(\frac{1}{b-a}\int_a^b|f(x)|^pdx\right)^{1/p}$$.
Show that
$$\lim_{p\to 0} \Phi_p(f)=\exp(\frac{1}{b-a}\int_a^b \ln |f(x)|dx)$$
I have no idea on it. Once I take L' Hospital formula, I got nonsense....


text:
Q: How to prevent SharePoint site page refresh itself when jquery .load is triggered? I have a simple SharePoint site page (created in Site Page library). I added a simple jquery syntax here:

When I click the button, overview.htm is loaded for 1 sec and the entire page is refreshed. It cause the page render back to previous stage.
I have also tried .html("
hello
"). The result is "hello" show up for 1 sec and page is refreshed.
Is it default SharePoint behavior? How can I work around it?

A: As per my understanding (Correct me if I am wrong), you forgot to add the type="button" to your button element.
So, Add type="button" to the button element like:
<button type="button" id="button_overview" onclick="yourFunction()">Click Here</button>

Reference: prevent refresh of page when button inside form clicked


text:
Q: Twitter Bootstrap to print a long column on one page Using Bootstrap v3.3.7 I have a page with two columns. When I print this page I want to print only one column but I'd like it to fit onto one A4 page.

        First name
        <input class="form-control input-sm" name="firstname" type="text" value="" id="firstname">

        Last name
        <input class="form-control input-sm" name="lastname" type="text" value="" id="lastname">

I'm printing only the first column (second column will be hidden from print), but because it's quite long it spans onto two printed pages. I want to keep it on one page and since I have the right half of the page free I thought I can break the left column into two, so that it fits on one page.
Is that possible with just CSS or I'd have to change my HTML for print only?

A: Boostrap is great!
I just found a solution. Use col-md-* for desktop screen and col-xs-* for small screen and print in my case.

            First name
            <input class="form-control input-sm" name="firstname" type="text" value="" id="firstname">

            Last name
            <input class="form-control input-sm" name="lastname" type="text" value="" id="lastname">


text:
Q: Can it transform one map with number of .dita file into one html file using dita-ot 3.0? Background: I have a ditamap file with 7 .dita files. Using the default dita-ot 3.0 html5 plugin, I get 7 html files and one index.html.
Question: Can it output the map file with 7 dita file into only one html file (structured in map or index.html)?   How?
Thanks in advance.
Note: because of topic-based writing, information is divided into mini blocks, while for the output in this forms, the whole document seems to isolate. Users need to do many clicks to switch to another topics and hardly can get the big picture of the document. That is why i ask the question. Any other suggestion?

A: What you need is chunking. Simply set the  chunk="to-content" attribute on the map root element.


text:
Q: R command `group_by` I am not able to understand exactly how this code works. I have found it on a tutorial guide:
Data manipulation in R - Steph Locke
on page 133 an example that I am able to understand only partially.
library(tidyverse)
library(nycflights13)

flights %>%
group_by(month, carrier) %>%
summarise(n=n()) %>%  ##sum of items;
group_by(month) %>%
mutate(prop=scales::percent(n/sum(n)), n=NULL) %>%
spread(month, prop)

flights %>%
group_by(month, carrier) %>%    ## This is grouping by months and within the months by carrier;
summarise(n=n()) %>%        ## It is summing the items, giving for each month and each carrier the sum of items;

At this point there in another group_by(), it looks like a nested to group_by(month, carrier)
Then:
mutate(prop=scales::percent(n/sum(n)), n=NULL) %>%  ## Calculates the percentage of items over the total and store them in "prop"

Last line it creates the matrix, putting in the columns month and inside the value obtained from prop
I would like to understand better what is doing exactly the second group_by(month) %>%
Thank you in advance for every reply.

A: The second group_by is not needed here as by default summarise step argument .groups = "drop_last".  Therefore, after the first summarise, there is only a single grouping column i.e. 'month' remains.  We can change the code to
flights %>%
  group_by(month, carrier) %>%
  summarise(n=n()) %>%
  mutate(prop=scales::percent(n/sum(n)), n=NULL)

Suppose, we change the default value in .groups to "drop", then, it will drop all the grouping variables, and thus a new group_by statement is needed.  Also, after the last grouping statement, if we are using mutate, it wouldn't drop the group attributes and thus ungroup would be useful
flights %>%
  group_by(month, carrier) %>%
  summarise(n=n(), .groups = "drop") %>%
  group_by(month) %>%
  mutate(prop=scales::percent(n/sum(n)), n=NULL) %>%
  ungroup


text:
Q: Correct way to handle iOS Push Notification with killed/swiped apps After XCode 11 released Apple had restricted PushKit notifications. Now it can be used only to notify incoming call. So if app don't report incoming call via CallKit it will be crashed.
The question is how to organize push notification delivery to messaging app even when it killed.
I found some points which can be used - "silent notifications" (not PushKit) with specified push-message content (content-available=1, apns-priority=5, etc). App can handle push-notification, run some business logic to prepare message data and display UNNotification and/or update app badge.
But there are lot of posts and topics about iOS restrictions to push-notifications delivery to app killed by user - OS just doesn't launch app.
There is another plot twist - Telegram iOS source code shows exactly same application logic - PushKit notifications only to incoming calls and default PushNotifications to all other scenarios (by sources). You can kill Telegram app, but you always receive incoming message notifications - the application somehow has launched and is handling push-notifications (decrypt, load media and other).
How does it all work?


text:
Q: Combine a result file from several txt-files I need to create a summary file from a large portion of txt-files from different folders. I started to do it with python, but any provided solution is fine ie. python, awk, bash
find = "find -name \"summary.txt\" > output.txt"
os.system(find)

o = open("output.txt", "r")
read = o.readlines()
for items in read:
    pilko = items.split("/")
    id = pilko[1]

I need to search summary-files from subfolders and compile the results of the txt-file to a result file. I'm kinda stuck here how to open the txt-file in for loop, save the data to a result file and move on.
plate = pilko[4]
print id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]
foo = open("id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]", "r")

That is approach that I tried, but everything is failing there:)
I could imagine there are easier ways to do this that I haven't heard yet.

A: for f in `find -name 'summary.txt' -print` ; do cat $f >> /tmp/grandsummary.txt ; done

A: If you look at the code coloration, your quoting is incorrect in the last line. Furthermore, you should probably use the os.path APIs for your stuff. And with just in case to ensure the file is correctly closed. Finally, no need to readline, a file is an iterable of lines. Finally, why do you recompose your path manually? Why not just open(items, 'rb')?

A: Here's a python solution:
import os
with open('/path/to/result/file.txt', 'wb') as result_file:
    for root, dirs, files in os.walk('/path/to/start/directory'):  # walk the file system
        if 'file_name_I_want.txt' in files:  # This folder has the file i'm looking for!
            with open(os.path.join(root, 'file_name_I_want.txt'), 'rb') as src_file:  # open it up
                result_file.write(src_file.read())  # Read from src, store in dest.

This was written from memory, so it may need some jiggering.


text:
Q: Residual sum of squares, two different equations, why are they equal? One definition of the Residual Sum of Squares is:
$$
S_r = (y-X\hat{\beta})^T(y-X\hat{\beta})
$$
And I think I understand it.
Now I have seen a different definition:
$$
S_r = y^Ty- \hat{\beta}^TX^TX\hat{\beta}
$$
I think they supposed to be equal but I can't see why.
I can write (I leave out the \hat on $\beta$ to make the typing easier):
$$
\begin{aligned}
S_r &= y^T(y-X\beta) - \beta^TX^T(y-X\beta)\\
&= y^Ty - y^TX\beta - \beta^TX^T y + \beta^TX^TX\beta
\end{aligned}
$$
and then to make both equations equal I would need to see that $\beta^TX^TX\beta = \beta^TX^T y$ which I don't.
How, do you show that the equations are equal?

A: The most compact way to see the equality is to use the orthogonal projection matrix $P = X(X'X)^{-1}X'$ and the residual-maker matrix $M = I-P$. Both these matrices are symmetric, $P'=P,\;\; M'=M$ and idempotent $PP=P,\;\; MM = M$.
We have
$$X\hat{\beta} = Py, \;\;y-X\hat{\beta}= My$$
Then
$$S_r = (y-X\hat{\beta})'(y-X\hat{\beta}) = (My)'(My) = y'M'My = y'My$$
$$ = y'(I-P)y = y'y - y'Py = y'y-(Py)'Py=y'y- \hat{\beta}'X'X\hat{\beta}$$

A: In math, generally there are more than one way to prove a equation. I think the previous Answers are correct, but differ from your approach. Your approach is correct also, but you need one more step.
At first, you missed hat on $\beta$ in your last equation. Using the fact that $\hat \beta =(X^TX)^{-1}X^Ty$, we have
$\hat\beta^TX^Ty=y^TX(X^TX)^{-1}X^Ty = y^TX(X^TX)^{-1}(X^TX)(X^TX)^{-1}X^Ty = \hat\beta^TX^TX\hat\beta$
So finished your steps.

A: As @whuber said in the comment, it is essentially Pythagorean Theorem.
Where Let error
$$e=y-X\hat\beta$$
and prediction
$$
p=X\hat\beta
$$
The first equation is
$$
e^Te=\|e\|^2
$$
and second equation is $y^Ty-p^Tp=\|y\|^2-\|p\|^2$. Because vector $e$ and vector $p$ are perpendicular, we have $\|y\|^2-\|p\|^2=\|e\|^2$.
Details can also be found in Gilbert Strangs's linear algebra book. Sample chapter here


text:
Q: Serial Port system.unauthorizedaccess My problem is when I run program it work perfectly fine but crashes after one cycle of the program. Here is some code:
    Private Sub Receiver(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles COMPort.DataReceived
    Dim RXByte As Byte
    key = 0
    cut = False
    c.Open()
    Do
        RXCnt = 0
        Do
            RXByte = COMPort.ReadByte
            If (RXByte = 29) Then
                c.Write(Chr(10))
                cut = True
                c.Close()
                If c.IsOpen = False Then
                        ts = "BLAH"
                        Process.Start(System.Windows.Forms.Application.StartupPath & "\e.exe", ts)
                        Process.Start(System.Windows.Forms.Application.StartupPath & "\Test.exe", c.PortName)
                Else

                End If

            End If
            If (cut = True) Then
                Exit Do
            End If
            c.Write(Chr(RXByte))
            addText(Chr(RXByte))
            RXArray(RXCnt) = LookUpTable(RXByte >> 4)
            RXCnt = RXCnt + 1
            RXArray(RXCnt) = LookUpTable(RXByte And 15)
            RXCnt = RXCnt + 1
            RXArray(RXCnt) = " "
            RXCnt = RXCnt + 1
            SpaceCount = (SpaceCount + 1) And 31
            If SpaceCount = 0 Then
                RXArray(RXCnt) = Chr(13) ' CR
                RXCnt = RXCnt + 1
                RXArray(RXCnt) = Chr(10) ' LF
                RXCnt = RXCnt + 1
            Else
                If (SpaceCount And 3) = 0 Then
                    RXArray(RXCnt) = " "
                    RXCnt = RXCnt + 1
                    RXArray(RXCnt) = " "
                    RXCnt = RXCnt + 1
                End If
            End If
        Loop Until (COMPort.BytesToRead = 0)
        Me.Invoke(New MethodInvoker(AddressOf Display))
    Loop Until (COMPort.BytesToRead = 0)
    c.Close()
End Sub

The problem I believe occurs at this point in the code
Process.Start(System.Windows.Forms.Application.StartupPath & "\Test.exe", c.PortName)

The system throws a System.UnauthorizedAccessException error. Moreover the test program also communicates with the same serial port. When I run the program the process gets launched and completes but the current process throw the error out. Is it a UAC error?

A: Two programs can't have the serial port open at the same time.  Attempting to open a serial port throws that exception under these circumstances:

Access is denied to the port.
-or-
The current process, or another process on the system, already has the specified COM port open either by a SerialPort instance or in unmanaged code.

Source.  So you can't have the serial port open in your program, and also in test.exe.


text:
Q: Problems getting matrix to display this is my 1st time asking for help for programming. Anywho, I need to write a program which find the determinant of a matrix (The determinant code will be made on a later date). Problem being is that I am having trouble getting my matrix to display. It seems that I have the array written correctly, but the output would skip the for loops to write the matrix. Would there be any changes that needs to be done or if theres a certain way that I need to set my array to determine determinants?
public class DetProg {
public static void main(String[] args) {

    Scanner a = new Scanner (System.in);

    Random mNum = new Random();
    System.out.print("Enter matrix size: ");
    int num = a.nextInt();
    int numX = num;
    int numY = num;
    int [][] matNN = new int [numX] [numY];
    int det = 0;// 0 is the placeholder until det method is inputted.
    int n = mNum.nextInt(100)+1;
    if (num >= 2)
    {
        for(int x = 0; x >= numX; x++)
        {
            for(int y = 0; y >= numY; y++)
            {
                matNN [x][y] = n;
                System.out.println(matNN[x][y] + " ");
            }
        }
        System.out.println("\n");
        System.out.println("Determinant of a matrix is " + det);
    }
    else
        System.out.println("Incorrect matrix size. Exiting...");
}
}

A: In your loops, you are making mistake in placing condition. you wrote x >= numX and y >= numY which will not be satisfied to even start the loop, because your x and y are equal to 0 in the start. it should be as:
for(int x = 0; x <= numX; x++)
    {
        for(int y = 0; y <= numY; y++)
        {

A: Firstly you need to change your loop conditions.
for (int x = 0; x < numX; x++) {
    for (int y = 0; y < numY; y++) {

this will result in proper assignment of values in an array and after this you can proceed further for your code of Determinant of a matrix.


text:
Q: Can't callgrind support AVX2 instructions? I'm trying to profile my program written with Intel AVX2 instructions using valgrind. The program run smoothly under memcheck. But when I run with callgrind (valgrind --tool=callgrind), it terminates with unrecognized instruction error. I check the release note of Valgrind 3.9.0 and it says Support for Intel AVX2 instructions.  This is available only on 64 bit code.. I compile my program with g++-4.8 -std=c++11 -mavx2 -m64 but the error remains. Part of the output is as below:
vex amd64->IR: unhandled instruction bytes: 0x16 0xC5 0xDD 0x64 0xD2 0xC5 0xF5 0xDB
vex amd64->IR:   REX=0 REX.W=0 REX.R=0 REX.X=0 REX.B=0
vex amd64->IR:   VEX=0 VEX.L=0 VEX.nVVVV=0x0 ESC=NONE
vex amd64->IR:   PFX.66=0 PFX.F2=0 PFX.F3=0
 ==6775== valgrind: Unrecognised instruction at address 0x43d1c9.
==6775==    at 0x43D1C9: byteslice::ByteSliceColumnBlock<16ul, (byteslice::Direction)1>::Scan(bytes
lice::Comparator, unsigned long, byteslice::BitVectorBlock*, byteslice::Bitwise) const (avxintrin.h
:965)
==6775==    by 0x45DEAD: byteslice::Column::Scan(byteslice::Comparator, unsigned long, byteslice::B
itVector*, byteslice::Bitwise) const (column.cpp:113)
==6775==    by 0x4017C9: main (simple.cpp:89)

Edit: I find the error depends on optimization level. There's no error with -O0. But error shows up with -O1 and above.


text:
Q: XML search by tag text using python Here is my code and XML:
xml_string = """
<data>
    <user>
        <name>123</name>
    </user>
    <user>
        <name>456</name>
    </user>
</data>
"""

import xml.etree.ElementTree as ET
root = ET.fromstring(xml_string)

I'm trying to find <user> tag where <name> has text value equal to 123.
What I have tried:
result = root.findall("./user[name = '123']")
result = root.findall("./user[./name = '123']")
result = root.findall("./user[/name = '123']")
result = root.findall("./user[./name text() = '123']")

None of these attempts worked. What am I missing?
Error I'm getting:
raise SyntaxError("invalid predicate")
File "<string>", line None
SyntaxError: invalid predicate

A: As the exception says, it seems you have a syntax error in the predicate, there shouldn't be a space between the tag name and the value:
xml_string = """
<data>
    <user>
        <name>123</name>
    </user>
    <user>
        <name>456</name>
    </user>
</data>
"""

import xml.etree.ElementTree as ET
root = ET.fromstring(xml_string)

result = root.findall("./user[name='123']")

print result


text:
Q: Microsoft authentication I am trying to use microsoft graph api and I need authorization code for using that.
Redirecting the application to microsoft login site is not possible in my application.
I need to call this and for that I require authProvider:
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(authProvider)
            .buildClient();

I am using this for creating authProvider:
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(CLIENT_ID,
            Arrays.asList("https://graph.microsoft.com/user.read", "https://graph.microsoft.com/Mail.ReadWrite",
                    "https://graph.microsoft.com/Calendars.ReadWrite"),
            USERNAME, PASSWORD, NationalCloud.Global,
            TENANT, CLIENT_SECRET)

On using this I get error:
  OAuthProblemException{error='invalid_grant', description='AADSTS65001: The user or administrator has not consented to use the application with ID 'e2bfebf6-cc77-49ec-82a3-28756ad377e5' named 'Milpitas Communications'. Send an interactive authorization request for this user and resource.

Trace ID: a2b91757-4849-4680-a089-001831ef7b00
Correlation ID: ae894060-a2ce-444c-9889-96fd3cdfaea7
I also tried  to use this to create authprovider:
AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(CLIENT_ID,
            Arrays.asList("https://graph.microsoft.com/user.read", "https://graph.microsoft.com/Mail.ReadWrite",
                    "https://graph.microsoft.com/Calendars.ReadWrite"),
            AUTHORIZATION_CODE, REDIRECT_URL, NationalCloud.Global, "common",
            CLIENT_SECRET);

To run the above I need authorization code, can anyone please suggest How I can get the code internally in spring boot application, as my application cannot have client input(for auth) on this?
Or alternatively Is there some other way I can use the IGraphServiceClient for creating a calendar event?

A: Replace Arrays.asList("https://graph.microsoft.com/user.read", "https://graph.microsoft.com/Mail.ReadWrite", "https://graph.microsoft.com/Calendars.ReadWrite") with Arrays.asList("https://graph.microsoft.com/.default") can resolve this issue.
My code for your reference:
public static void main(String[] args) {

    String USERNAME = "{username}";
    String PASSWORD = "{password}";
    String TENANT = "{tenantID}";
    String CLIENT_ID = "{clientID}";
    String CLIENT_SECRET = "{clientSecret}";

    UsernamePasswordProvider authProvider = new UsernamePasswordProvider(CLIENT_ID,
            Arrays.asList("https://graph.microsoft.com/.default"),
            USERNAME, PASSWORD, NationalCloud.Global,
            TENANT, CLIENT_SECRET);

    IGraphServiceClient graphClient = GraphServiceClient
            .builder()
            .authenticationProvider(authProvider)
            .buildClient();

    User user = graphClient.me().buildRequest().get();

    System.out.println(user.userPrincipalName);
}


text:
Q: NullPointerException BillingManager.java from In-app Billing I added a new billing library to my project.
compile 'com.android.billingclient:billing:1.0'

I added a BillingManager.java class to my project from here https://github.com/googlesamples/android-play-billing/blob/master/TrivialDrive_v2/shared-module/src/main/java/com/example/billingmodule/billing/BillingManager.java
I get many exceptions, details are from Crashlytics:
Fatal Exception: java.lang.RuntimeException
Unable to resume activity {com.domain.app/com.domain.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

Caused by java.lang.NullPointerException
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

com.domain.app.BillingManager$4.run
com.domain.app.BillingManager.executeServiceRequest (Unknown Source)
com.domain.app.BillingManager.executeServiceRequest (Unknown Source)
com.domain.app.MainActivity.onResume (Unknown Source)

TXT mode:
Fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.domain.app/com.domain.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
       at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3647)
       at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3687)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1629)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:156)
       at android.app.ActivityThread.main(ActivityThread.java:6623)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

OnResume() of MainActivity contains a following code:
if (mBillingManager != null && mBillingManager.getBillingClientResponseCode() == BillingClient.BillingResponse.OK) {
                mBillingManager.queryPurchases();
            }

How can I fix it? Around 1% of DAU have a such problem.


text:
Q: Execute SQL Server stored procedure from Oracle I have an Oracle procedure that executes a SQL Server stored procedure. The SQL Server stored procedure executes one of three stored procedures based on an id field passed it from the Oracle  procedure.  Two of the stored procedure execute okay but the third does not.
The third stored procedure has several nested stored procedure calls.  It performs some calculations and then inserts to 3 different tables and then some additional calculations and updates one of the tables it just inserted to.  If I execute the stored procedure in SSMS it runs without issue.  When it is executed from Oracle side I get nothing.
Could this because of the nesting but because of the implicit commits I see it work using SMSS?  I tried doing a BEGIN Transaction in the starting stored procedure on  the MS SQL Server side and a commit at the end where it should return.  Still nothing.  I have Try and Catch blocks in the MS SQL stored procedures and don't receive any errors.
Any suggestions would be greatly appreciated.
Thank you.

A: Does nothing means none of the inserts or updates show up in the tables. No error messages
As far as posting code; what specifically would you be interested in seeing?  There are 4 stored procedures which have 100s of lines of code each.


text:
Q: AOP pointcut (using annotation) to log all methods except setters and getters from POJOs when using package by feature directory structure I am using AspectJ (AOP) for logging purpose. I have following package structure:
com.company.base

com.company.base.common.Result.java
(its a POJO containing 3 fields and their setters and getters and implements Serialize)

com.company.base.feature1.User.java
(its a POJO containing 5 fields and their setters and getters and implements Serialize)

com.company.base.feature2.Customer.java
(its a POJO containing 2 fields and their setters and getters and implements Serialize)

my requirement is:
1) log entry and exit messages when any method executes from any class except from POJO's setter and getter
2) minimum line of code should be there
I am using following pointcut definition but its also calling the advise at setters and getters time as well.
@Pointcut("execution(* com.company.base..*(..))")
void allMethodExcution() {}

Please suggest as soon as possible.

A: I think I got partial answer to my question (may be not the exact one).
1] All the POJOs are annotated with @XmlRootElement so I created one more pointcut and following advise
// join points created by following point cuts
@Pointcut("within(@javax...XmlRootElement *)")
public void beanAnnotatedWithSpecificAnnotation()

@Pointcut("execution(* com.company.base..*(..))")
public void allMethods()

// this is advise
@Before("!beanAnnotatedWithSpecificAnnotation() && allMethods()")
public void applyAdvise(JoinPoint jp) {
// TODO: advise code ...
}

2] But, what if POJO does not contain @XmlRootElement and only implements java.io.Serialize interface?


text:
Q: Retrieving Multiple Images from phpmyadmin dynamically I have a set of Multiple choice questions stored in phpmyadmin. I need to retrieve an image along with each question and answers. In other words, when the users start the test or click on the "next question" button, they need to see not only the question and answers, but also the image related to that question. I have already saved the images in Blob format in the database, but have problem for retrieving them dynamically. Would appreciate it if somebody helps me
Here is part of the code:
$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' LIMIT 1");
    while($row = mysql_fetch_array($singleSQL)){
        $id = $row['id'];
        $thisQuestion = $row['question'];
        $type = $row['type'];
        $question_id = $row['question_id'];
        $q = '
'.$thisQuestion.'
';

        $sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
        while($row2 = mysql_fetch_array($sql2)){
            $answer = $row2['answer'];
            $correct = $row2['correct'];
            $answers .= '<input type="radio" name="rads" value="'.$correct.'">'.$answer.'
            <input type="hidden" id="qid" value="'.$id.'" name="qid">

            ';
        }

        $sql3 = mysql_query("SELECT username FROM quiz_takers");
        while($row3 = mysql_fetch_array($sql3)){
        $name = $row3['username'];
            }

A: Try something like this for displaying the blob images:
$image = $row['image'];
echo '';

replacing image/type with image/jpeg or whatever type the images are.


text:
Q: NHibernate mapping with two special cases I am using NHibernate to map a class to a database table.  The Part table has an ID column (primary key) and a ParentPart column (along with a few others).
class Part
{
    public virtual long ID{ get; set; }
    public virtual Part ParentPart { get; set; }
}

The ParentPart is normally another valid part in the part table but I have two special cases.  I have a case where the ParentPart column can be 0 (zero) and another case where it can be -1.  Neither of these cases currently represent another valid Part object.  I was thinking I could make 2 subclasses of Part (ZeroPart and NegativeOnePart) that would never persist.  I want the zero and -1 values to be entered in the column but not persist the entire ZeroPart or NegativeOnePart objects. I am unsure how to map this (I'm using hbm files) or if this even the correct approach.
How can I map this so that normal valid parts are persisted but I can also handle the special cases?
As an aside: My current hbm file has the Part.ID's unsaved value as zero but I think I can just change this in the mapping to something different and default it in the class.

A: Will there be Part values in your "parts" table with the specified IDs, to maintain referential integrity?
If so, then I would suggest creating two special Part instances, each representing the special cases your model implies. You would need to fetch these instances from the database when you want to assign them, but this can be made simple with some helper methods on your repositories.

A: If I understand you correctly, you have a tree structure and you want to assign dummy-objects (with ID = 0 or ID = -1) that shall not be persisted to the database when persisting the objects. The ParentPart column shall contain ID = 0 or -1, depending on some criteria.
Based on this information I assume that you do not have foreign-keys in your table, so that saving an object with a ParentPart = 0 or -1 will not result in a violation of referential integrity. Under normal circumstances I would suggest using a foreign key and allowing NULL in the ParentPart column.
However, since you want two different values (0 and -1) as an indicator that no parent exists, I believe that your best option is probably just creating the two entries in the database (both with ParentPart = NULL).
If you strictly do not want to add those entries, you can have a look at intereceptors and events.
I don't think you can solve this within your mapping files. The NHibernate mapping feature is not designed to handle such specific logic, nor should it be able to do so.
(Having that kind of logic in the database may not be very desirable, but it sounds like this is not a new project, so we don't need to argue about it here.)


text:
Q: Определение реального типа данных в списке Требуется определить реальный тип данных в списке содержащий строки вида:
a = ['-1.8', 'a', 'b', '4']
Делаю это в цикле с использованием исключений при преобразовании типов данных так:
j = []
for i in a:
    try:
        j.append(int(i))
    except ValueError:
        try:
            j.append(float(i))
        except ValueError:
            j.append(i)
print(j)

Результатом будет:
[-1.8, 'a', 'b', 4]

Но не покидает меня стойкое ощущение что есть способ проще. Подскажите плз.

A: Считаю что этот способ хороший, т.к. гарантирует что данные будут правильно разобраны.
Чтобы ощущение, что есть вариант проще, стало меньше, оберните код разбора в функцию:
def parse_str(value):
    try:
        return int(value)
    except ValueError:
        try:
            return float(value)
        except ValueError:
            return value

items_1 = ['-1.8', 'a', 'b', '4']
print(items_1)  # ['-1.8', 'a', 'b', '4']

items_2 = [parse_str(x) for x in items_1]
print(items_2)  # [-1.8, 'a', 'b', 4]

A: Можно сократить количество кода следующим способом: применять функции из списка. В случае успеха возвращать результат. Если все вызовы закончились неудачей, возвращаем исходное значение:
def parse_str(value):
    for f in (int, float):
        try:
            return f(value)
        except ValueError:
            pass
    return value

items = ['-1.8', 'a', 'b', '4']
for v in map(parse_str, items):
    print(type(v), v)

$ python parse_list.py
<class 'float'> -1.8
<class 'str'> a
<class 'str'> b
<class 'int'> 4


text:
Q: Background color not changing in Chrome when setting css in jquery In my JQuery/JS I'm doing a check and changing the background color and border color of a button, it works fine in IE but in Chrome, Chrome doesn't set the color back to grey. IE changes, just not Chrome. When I look in the debugger at the rendered html it doesn't add the coloring, it's just not there!!! Funny thing is it adds the disabled property in Chrome, so the line of Jquery code that sets the color back to grey is def being called!
Here is my button, I initialize it with grey and being disabled
<button id="eventRegister" type="button" class="btn btn-lg btn-yb footer-button" style="background-color: grey !important; border-color: grey !important; display: none;" disabled>Register</button>

Then with a checkbox on the page for 'terms and services' I enable it and remove the grey color. But if the user un checks the checkbox and resets the button back to grey, in Chrome, it doesn't change the color. IE is fine!
$("#registerEventTerms").off('change').on('change', function () {
        if (this.checked)
            $("#eventRegister").css('background-color', '').css('border-color', '').prop('disabled', false);
        else
            $("#eventRegister").css('background-color', 'grey !important').css('border-color', 'grey !important').prop('disabled', true);
    });

FYI - I'm thinking it has something to do with my class 'btn-yb' located in my site.css file, that has these properties, but not sure

.btn-yb {
  background-color: #008489 !important;
  color: white !important;
}

.btn-yb:hover,
.btn-yb:focus {
  color: white !important;
}

.btn-yb.disabled,
[disabled].btn-yb,
fieldset[disabled] .btn-yb {
  opacity: 1;
}

A:

Also change your javascript

<script>
  src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" >
    $("#registerEventTerms").off('change').on('change', function() {
      if ($(this).prop('checked', true);)
        $("#eventRegister").css('background-color', '').css('border-color', '').prop('disabled', false);
      else
        $("#eventRegister").css('background-color', 'grey !important').css('border-color', 'grey !important').prop('disabled', true);
    });
</script>

Change CSS
  .btn-yb {
  background-color: #008489;
  color: white !important;
}

.btn-yb:hover,
.btn-yb:focus {
  color: white !important;
}

.btn-yb.disabled,
[disabled].btn-yb,
fieldset[disabled] .btn-yb {
  opacity: 1;
}

A: Things are happening in the following order:

*

*First, your inline style is getting applied, and setting the button's background-color to grey.

*Next your stylsheet is setting the background-color to #008489.

*Finally, your jQuery is removing the inline style successfully.

It's important to note that jQuery's css() method attempts to modify the style property, and thus it can only update inline styles, not external stylesheets. Your inline style is removed, and your stylesheet rule is not. As such, you see the stylesheet's #008489 background-color.
Remember, inline styles have more specificity than stylesheet styles. This can only be overridden with !important. However, things get much more confusing with multiple !important declarations, as all your rules are essentially fighting for highest specificity. Avoid using !important whenever possible, opting for more specific CSS selectors instead.
The simplest solution to this is to just remove all of your !important declarations, as this will allow the specificity to be handled in the correct order:

$("#registerEventTerms").off('change').on('change', function() {
  if (this.checked)
    $("#eventRegister").css('background-color', '').prop('disabled', false);
  else
    $("#eventRegister").css('background-color', 'grey').prop('disabled', true);
});
.btn-yb {
  background-color: #008489;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="eventRegister" type="button" class="btn-yb" style="background-color: grey" disabled>Register</button>

Alternatively, you can setup a new selector to target the disabled attribute, which would mean you don't need to worry about setting styles in either HTML or jQuery - all that needs to be handled is the .prop():

$("#registerEventTerms").off('change').on('change', function() {
  if (this.checked)
    $("#eventRegister").prop('disabled', false);
  else
    $("#eventRegister").prop('disabled', true);
});
.btn-yb {
  background-color: #008489;
  color: white;
}

.btn-yb[disabled] {
  background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="eventRegister" type="button" class="btn-yb" disabled>Register</button>

For a more comprehensive reasoning of exactly why the css() method can modify inline styles but not stylesheet styles, please see this answer I wrote yesterday.
As for why IE is behaving differently than Chrome, I assume it's based on the order of specificity of how multiple !important statements are handled.


text:
Q: Cannot find entity I have this DB table which I want to use with JPA
CREATE TABLE translations (
id  SERIAL NOT NULL,
KEY VARCHAR(255),
LANGUAGE VARCHAR(255),
TRANSLATION VARCHAR(255)
)

I created this entity:
@Entity
@Table(name = "translations")
public class TranslationTestEntitie extends AbstractEntityWithId {

    private static final long serialVersionUID = 2029240552230401080L;

    @Column(name = "id", insertable=false, updatable=false)
    private long id;
    @Column(name = "key", insertable=false, updatable=false)
    private String key;
    @Column(name = "language", insertable=false, updatable=false)

    private String language;
    @Column(name = "translation", insertable=false, updatable=false)
    private String translation;

    public TranslationTestEntitie() {
    }

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getTranslation() {
        return translation;
    }

    public void setTranslation(String translation) {
        this.translation = translation;
    }

}

When I try to make this query SELECT c FROM Translations c WHERE c.Id = 70
I get this message The abstract schema type 'Translations' is unknown.
Is this entitie correct according to the DB table.
P.S This is the code that I use to get the data:
public TData td;

    public class TData {

        private long id;
        private String key;
        private String language;
        private String translation;

        public TData() {
        };

        public TData(long id, String key, String language, String translation) {
            // super();
            this.id = id;
            this.key = key;
            this.language = language;
            this.translation = translation;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getLanguage() {
            return language;
        }

        public void setLanguage(String language) {
            this.language = language;
        }

        public String getTranslation() {
            return translation;
        }

        public void setTranslation(String translation) {
            this.translation = translation;
        }

    }

    public TData getDataObj() {
        return td;
    }

    @PostConstruct
    public void loadData() {

        td = new TData();

        String query = "SELECT c FROM Translations c WHERE c.id = 70";
        td = (TData) dao.jpqlQuerySingle(query);//(query);//jpqlQuery(query);

    }

But I still get empty Object.

A: The entity mapped to your translations database table has been named TranslationTestEntitie.
from TranslationTestEntitie c should then suit your needs.

A: Maybe because your table name is not Translations but translations.
SELECT c FROM translations c WHERE c.id = 70

And id with lowercase.


text:
Q: Is it possible to have $\operatorname{rank}(A^2) \lt \operatorname{rank}(A^3)?$ This is a question of GATE 2021.
Let $$ be a square matrix such that $\det( − ) = $
$x^4( − )^2( − )^3$
$\DeclareMathOperator{\rank}{rank}$
,
where $\det()$ denotes the determinant of a square matrix .
If $\rank(A^2) < \rank(A^3)=\rank(A^4),$
then I need to find the geometric multiplicity of
the eigenvalue $$ of $$.

But firstly can we have $\rank(^2)$ strictly less than $\rank(^)?$

If yes then how to proceed with this question? Thanks in advance.

A: The rank is the dimension of the image. The image of $A^3$ is contained in the image of $A^2$, as $A^3=A^2\circ A$, so $\operatorname{rank}(A^2)\geq \operatorname{rank}(A^3)$

A: No. It is well-known tht the rank of an $m \times n$- matrix $ \mathbf B$ agrees with the dimension of the image of the associated linear map $\phi_{ \mathbf B} : \mathbb R^n \to \mathbb R^m, \phi_{ \mathbf B} (x) =  \mathbf B \cdot x$.
Let $\phi = \phi_{\mathbf A} :  \mathbb R^n \to \mathbb R^n$. Then the rank of $\mathbf A^r$ is the dimension of $\phi^r(\mathbb R^n)$. But each linear map has the property that $\dim V \ge \dim \phi(V)$ for all linear subspaces $V \subset \mathbb R^n$. Thus $\dim \phi^{r+1}(\mathbb R^n) \le \dim \phi^r(\mathbb R^n)$ for all $r$. In other words, $\operatorname{rank} \mathbf A^{r+1} \le \operatorname{rank} \mathbf A^r$ for all $r$.


text:
Q: Platform-dependent files in Swift Package I'm developing a cross-platform C++ library which supports iOS and macOS. The library could be integrated using Swift Package Manager. In C++ it's easy to have a single header file and multiple different implementation files that will be compiled for each platform. E.g, the header has a print() method and each target implements it differently:
macOS: "print_macOS"
iOS: "print_iOS"
Windows: "print_Windows"

Is it possible to somehow to make Swift Package Manager conditionally include/exclude specific files from the target depending on the platform?
The closest functionality I found is Conditional Target Dependencies, but it is about including/excluding specific libraries and not just files. I need to have a bit more granular approach.
Currently I'm using compile-time directives to resolve this issue:
#include "Print.h"

std::string Print::PrintMethod()
{
#if TARGET_OS_IPHONE
    return "print_iOS";
#else
    return "print_macOS";
#endif
}

So, are there any ways to achieve the same result but with different files? Note, that apart from those two files the target is completely identical for both platforms (iOS and macOS).
Reference Package.swift file:
// swift-tools-version:5.4
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "ResultingTarget",
    platforms: [
        .iOS(.v13), .macOS(.v10_15)
    ],
    products: [
        .library(
            name: "ResultingTarget",
            targets: ["ResultingTarget"]),
    ],
    targets: [
        .target(
            name: "ResultingTarget",
            sources:
                [
                    // "File_for_iOS.mm", <----- Need to include only for iOS
                    "File_for_macOS.mm", <----- Need to include only for macOS
                    "Other_file.mm",
                ],
            publicHeadersPath: "Headers",
            cxxSettings: [
                .headerSearchPath("headers"),
            ]),
    ],
    cxxLanguageStandard: .cxx14
)


text:
Q: Does Webpack DefinePlugin support variables or only constants? I tries to pass an array to DefinePlugin . This array is declared globally and filled in by an another plugin (DirectoryTreePlugi, enhance method). But a browser's debuggers shows what the array is empty.
If I assign some values to the array once I declare it the debugger shows that values. It seems like DefinePlugin is called earlier than DirectoryTreePlugin, but the order of plugins in Webpack config file is DirectoryTreePlugin and then DefinePlugin.

A: In short, yes, DefinePlugin supports both variales and constants. Thanks to @MatheusSilva pointing me on my misunderstanding about the order of Webpack plugin execution.
I solved my task in the following way.
For doing its job DirectoryTreePlugin uses the directory-tree library. So I just imported it in Webpack config file, filled in my array in dirTree callback and pass it (array) to DefinePlugin.


text:
Q: there exsit postive integer $x,y$ such $p\mid(x^2+y^2+n)$ For any give the postive integer $n$,and for any give prime number $p$.
show that
there exsit  postive integer $x,y$ such
$$p\mid(x^2+y^2+n)$$
My approach is the following:
Assmue that $n=1,p=2$,we choose$(x,y)=(1,2)$
$$2\mid6=1^2+2^2+1$$
Assmue that $n=1,p=3$, we choose $(x,y)=(1,2)$
$$3\mid6=1^2+2^2+1$$
Assume that $n=1,p=5$,we choose $(x,y)=(2,5)$
$$5\mid30=2^2+5^2+1$$
Assume that $n=2,p=2$, we choose $(x,y)=(2,2)$
$$2\mid10=2^2+2^2+2$$
Assume that $n=2,p=3$ we choose $(x,y)=(2,3)$
$$3\mid15=2^2+3^2+2$$
Assume that $n=2,p=5$,we choose $(x,y)=(3,3)$
$$5\mid20=3^2+3^2+2$$
and so on
Now I'm stuck and don't know how to proceed

A: The result is easy to prove if $p=2$, so we can assume from now on that $p$ is odd.
Modulo $p$, there are $\frac{p+1}{2}$ squares, namely the $\frac{p-1}{2}$ quadratic residues of $p$, and $0$.
So modulo $p$ there are $\frac{p+1}{2}$ distinct values of $x^2$. There are also (for fixed $n$) $\frac{p+1}{2}$ distinct values of $-y^2-n$, since there are $\frac{p+1}{2}$ distinct values of $y^2$, and hence of $-y^2$.
Since $\frac{p+1}{2}+\frac{p+1}{2}=p+1\gt p$, by the Pigeonhole Principle there exist $x$ and $y$ such that $x^2\equiv -y^2-n\pmod{p}$. This implies that there are values of $x$ and $y$ such that $x^2-(-y^2-n)\equiv 0\pmod{p}$.


text:
Q: SQL 2008 Exists I have 2 tables TimetableMaster and TimetableBreakup. In my stored procedure, i need an IF condition to check whether TimetableMaster.TimetableMasterID exists in the TimetableBreakup table(for which TimetableMasterID is the foreign key). How do I frame the IF condition?

A: Try this...
 Select * from TimetableMaster where TimetableMasterID in (select TimetableMasterID  from TimeTableBreakup)

or
 Select * from TimetableMaster where TimetableMasterID exists (select TimetableMasterID  from TimeTableBreakup)


text:
Q: Reference last document in a Firestore Collection I recently learned that we can actually set FieldValue to reference a document. But what I really was curious about was if it was also possible to reference the last document of a Collection.
Say for example I have a Data Structure which looks like this:
Chat
    CHAT_ID
        last : (Reference To the Last Document in the "Messages" Collection)

Messages
    MSG_ID_001
       msg : Some Message
    MSG_ID_002
       msg : Some Message
    MSG_ID_003
       msg : Some Message

So now I want set the reference such that it always refers to the last document in the Messages Collection (In this case MSG_ID_003).
So is it possible??

A: Having a field referencing the last field of a collection, and automatically updating that reference so it always points to the last field, is not possible in Firestore.
I would recommend just making a query to get the last document reference whenever you need it. But if you want to do it, as a workaround, you can update the field yourself, and there are a couple of ways to do it:

*

*Updating it from your code every time you add a new field to the collection you want to reference with an update query.

*Creating a Cloud Function using the onCreate or onWrite triggers to update the reference field each time changes are made to the collection. Please note that this approach, although the most reliable, can be pretty expensive if you have to update that field frequently.

You  can take a look at this video that explains what reference fields are used for in Firestore.


text:
Q: Black Hat Python TCP Client I'm working through the Black Hat Python book, and though it was written in 2015 some of the code seems a little dated. For example, print statements aren't utilizing parentheses. However, i cannot seem to get the below script to run, and keep getting an error.
    # TCP Client Tool

import socket

target_host = "www.google.com"
target_port = 80

# creates a socket object. AF_INET parameter specifies IPv4 addr/host. SOCK_STREAM is TCP specific, not UDP.
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect the client
client.connect((target_host, target_port))

# sending some data
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n\")

# receive some data
response = client.recv(4096)

print(response)

The error i'm getting simply reads,  File "", line 15
    client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n\")
                                                             ^

A: You are escaping " by putting a \ before, which means python does not know that the string ends here. You can notice that in your post, all the code after that line is coloured as if it was a string.
client.send also needs a byte-like object, not a string. You can specify that by putting a b before your string:
client.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")

After that the script works fine

A: I think @Anonyme2000 answered the question in full and all the details needed to solve the issue are there. However, since this is a learning exercise from a book, others might come here and the details of what's going on in @Anonyme2000's answers are a bit short, I'll expand some more.
Strings
Python, like many other languages have what's called Escape Sequences, in short, putting \ infront of something means that - whatever follows will have a special meaning. Two examples:
Example 1: Row breaks (new-lines)
print("Something \nThis is a new line")

This will cause python to interpret n not as letter "n", but a special character indicating that "here there should be a new line", all thanks to \n being in-front of the letter n. \r is also a "new-line" but in older  days it was the equivilent of moving the carriage printer head to the start of the line - not just down one line.
Example 2: Quote escapes in strings
print("I want to print this quote: \" in my string")

In this example, because we are using the quote character " to start and end our string, adding it in the middle would break the string (hopefully this is clear to you). In order to then proceed adding quotes in the middle of the text, we need to again, add a escape sequence character \ before the quote, this tells Python not to parse the quote as a quote, but simply add it into the string. There's an alternative to doing this, and that is:
print('I want to print this quote: " in my string')

And that's because the whole string is started and ended by ' instead, which enables Python to accurately guess (parse) start and stop of the actual whole string - which makes it 100% confident that the quote in this case - just just another piece of the string. These escape sequences are described here with more examples.

Bytes vs Strings
To better understand the difference, we'll first have a look at how Python and the terminal you use interact. I'm assuming you're running your python scripts from cmd.exe, powershell.exe or in Linux something like xterm or something. Basic terminals that is.
The terminal, will try to parse anything sent to it's output buffer and represent it to you. You can test this by doing:
print('\xc3\xa5\xc3\xa4\xc3\xb6') # Most Linux systems
print('\xe5\xe4\xf6') # Most Windows systems

In theory, one of the prints above should have let you just printed a bunch of bytes that the terminal some how knew how to render as åäö. Even your browser just did that for you (Fun side note, that's how they solve the Emoji-problem too, everyone's agreed that certain byte combinations should become ). I say most windows and Linux, because this result is entirely up to what region/language you selected when you installed your operating system. I'm in EU North (Sweden) so my default codec in Windows is ISO-8859-1 and in all my Linux machines I have UTF-8. These codecs are important, as that's the machine-human interface in representing text.
Knowing this, anything you send to the output buffer of your terminal by doing either print("...") or sys.stdout.write("...") - will be interpreted by the terminal and rendered in your locale. If that's not possible, errors will occur.
This is where Python2 and Python3 starts to become two different beasts. And that's why you're here today. Putting it in simple terms, Python2 did a lot of automated and magic "guess-work" on strings, so that you could send a string to a socket - and Python would take care of the encoding for you. Python2 parsed them and converted them in all kinds of ways. In Python3 a lot of that automated guess-work was removed because it was more often than not confusing people. And the data being sent through functions and sockets was essentially a schrödingers data, it was strings some times and bytes some times. So instead, it's now up to you the developer to convert the data and encode it.. always.
So what is bytes vs strings?
bytes is in lay man terms, a string that hasn't been encoded in any way and thus can contain anything "data"-related. It doesn't have to be just a string (a-Z, 0-9, !"#¤% and so on), it can also contain special bytes like \x00 which is a Null byte/character. And Python will never try to auto-parse this data in Python3. And when doing:
print(b'\xe5\xe4\xf6')

Like above, except you define the string as a bytes string in Python3, Python will instead send a representation of the bytes not the actual bytes to the terminal buffer, thus, the terminal will never interpret them as the actual bytes they are.
Example 1: Encoding your data
Which brings us to this first example. So how do you convert your bytes containing print(b'\xe5\xe4\xf6') to the represented characters in your terminal, well, by converting it to a strings with a particular encoding. In the above example, the three characters \xe5\xe4\xf6 happens to be the ISO-8859-1 encoder in the making. I know this because I'm currently on windows and, if you run the command chcp in your terminal, you'll get which code page/encoder you're using.
There for, I can do:
print(b'\xe5\xe4\xf6'.decode('ISO-8859-1')

And that will convert the bytes objects into a string object (with a encoding).
The problem here, is that if you send this string to my Linux machine, it won't have a clue what's going on. Because, if you try:
print(b'\x86\x84\x94'.decode('UTF-8'))

You will end up with a error message like this:
>>> print(b'\x86\x84\x94'.decode('UTF-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x86 in position 0: invalid start byte

This is because, in UTF-8 land, byte \x86 doesn't exists. So it has no way of knowing what to do with it. And because my Linux machine's default encoder is UTF-8 - your windows data is garbage to my machine.
Which, brings us to..
Sockets
In Python3 and most physical realms of a computer, encodings and strings are not welcome as they aren't really a thing. Instead, machines communicate in bits, in short, 1's and 0's. 8 of those becomes a byte, and that's where Python's bytes comes in to play. When sending something from machine to machine (or application to application), we will have to convert any text-representation, into a bytes sequence - so that the machines can talk to each other. Without encodings, without parsing things. Just - take the data.
We do this in three ways and they are:
print('åäö'.encode('UTF-8'))
print(bytes('åäö', 'UTF-8'))
print(b'åäö')

The last option, will fail - but I'll leave it like this on purpose to show the differences of telling Python, "hey, this weird thing, convert it to a bytes object".
All of these options, will return a bytes representation of åäö using a encoder *(except the last one, it will only encode using the ASCII parser, which is limited at best).
In the UTF-8 case, you will be returned something like:
b'\xc3\xa5\xc3\xa4\xc3\xb6'

And this, this is something you can send out on a socket. Because it's just a series of bytes, that the terminals, machines and applications won't touch or deal with in any other way than a series of ones and zeroes *('11000011 10100101 11000011 10100100 11000011 10110110' to be specific)
Together with some network logic, that's what's going to be sent out on your socket. And that's how machines communicate.

This is an overview of what's going on. The "human" is the terminal, aka, the machine-human-interface where you input your åäö and the terminal encodes/parses it as a certain encoding. Your application has to do magic in order to convert it to something the socket/physical world can work with.


text:
Q: Using dlib-19.4.0 in android for face recognition real time I have followed this github project for loading dlib on android. I was able to run this thing on my android device. For face detection and landmark recognition it worked fine. But I want to have face recognition feature in my app, which I read is possible in dlib-19.4.0. I even tried it on python and it worked.
I want to import this feature in my android app. I followed the instructions to build .so files. But in .so files, I couldn't find the functions of face_recognition. Can you please help me proceed with this. Here is my CMAKE file:
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
cmake_minimum_required(VERSION 3.4.1)

message("Checking CMAKE_SYSTEM_NAME = '${CMAKE_SYSTEM_NAME}'")
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
  add_definitions(-DOS_OSX)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
  add_definitions(-DOS_LINUX)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "Windows")
  add_definitions(-DOS_WIN)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "Android")
  add_definitions(-DOS_ANDROID)
  message("Checking CMAKE_ABI_NAME = '${CMAKE_ANDROID_ARCH_ABI}'")
else()
  message("OS not detected.")
endif()

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Werror")

## Define each subfolders
set(JNI_DETECTION_INCLUDE jni/jni_detections)
set(JNI_DETECTION_SRC jni/jni_detections)
set(JNI_COMMON_INCLUDE jni)
set(JNI_COMMON_SRC jni/jni_common)
set(DLIB_DIR dlib)
set(EXT_DIR third_party)
set(GLOG_INCLUDE_DIR ${EXT_DIR}/miniglog)
set(OPENCV_PREBUILT ${EXT_DIR}/OpenCV-android-sdk/sdk/native/jni)

# Opencv and it will use static import
set(ANDROID_NDK_ABI_NAME ${CMAKE_ANDROID_ARCH_ABI})
include(${OPENCV_PREBUILT}/OpenCVConfig.cmake)

# Include headers
include_directories(${DLIB_DIR} ${OpenCV_INCLUDE_DIRS} ${GLOG_INCLUDE_DIR} ${JNI_COMMON_INCLUDE} ${JNI_DETECTION_INCLUDE} include)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             # Associated headers in the same location as their source
             # file are automatically included.
             ${DLIB_DIR}/dlib/cpp/cpp/native-lib.cpp
 )

add_library(dlib.cpp
             SHARED
            ${DLIB_DIR}/dlib/cpp/cpp/dlib.cpp
 )

add_library(matrix.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/matrix.cpp
 )

add_library(vector.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/vector.cpp
 )

add_library(svm_c_trainer.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/svm_c_trainer.cpp
 )

add_library(svm_rank_trainer.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/svm_rank_trainer.cpp
 )

add_library(decision_functions.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/decision_functions.cpp
 )

add_library(other.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/other.cpp
 )

add_library(basic.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/basic.cpp
 )

add_library(cca.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/cca.cpp
 )

add_library(sequence_segmenter.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/sequence_segmenter.cpp
 )

add_library(svm_struct.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/svm_struct.cpp
 )

add_library(image.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/image.cpp
 )

add_library(rectangles.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/rectangles.cpp
 )

add_library(object_detection.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/object_detection.cpp
 )

add_library(shape_predictor.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/shape_predictor.cpp
 )

add_library(correlation_tracker.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/correlation_tracker.cpp
 )

add_library(face_recognition.cpp
             SHARED
             ${DLIB_DIR}/dlib/cpp/cpp/face_recognition.cpp
 )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in the
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )


text:
Q: Python Script Hangs When Called via PHP shell_exec() I have a Python script that is called from PHP using shell_exec, all was working fine and the script came back to the PHP function after the Python script completed and everything was working as exepcted.
Now I have changed the Python script to include a class one level up from it that creates a web driver and returns the driver to the script that calls it via an object and then another function closes the driver that is passed in as a parameter.
Since setting up this new class and adding in an object to create/close a driver for webdriver using chrome the Python script hangs after completion  and it never hands back control to the PHP script to finish processing.
I've had a look at php system() shell_exec() hangs the browser and also at http://php.net/manual/it/function.shell-exec.php#106250 with no luck.
I need the PHP script to run and then pass to the Python script, wait for the Python script to complete and hand back to the PHP script to finish processing.
All this process is kicked off from Run.php with:
$reponse = shell_exec('python36 "script1.py" "https://www.example.com/" "23"');

Directory Structure
root_dir
    python_dir
        scripts_dir
            Script1.py
            Script2.py
            Script3.py
        Global.py
    run.php

Global.py
import re
from selenium import webdriver

class Global:

    def getDriver(self):
        try:
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument('headless')
            chrome_options.add_argument('no-sandbox')

            # Windows - Dev Environment
            driver = webdriver.Chrome(executable_path='C:\chromedriver.exe', chrome_options=chrome_options)
            # Linux - Prod Environment
            #driver = webdriver.Chrome(chrome_options=chrome_options)

            return driver
        except Exception as e:
            print('Error: ' + str(e.args[0]))

    def closeDriver(self, driver):
        try:
            driver.close()
            return None
        except Exception as e:
            print('Error: ' + str(e.args[0]))

All the scripts in the scripts_dir have different code in them depeneding on the task they are doing, but the new Global object stuff is the same for all scripts, the new Global object is the only change made to all the scripts since they were working fine till now where the Python scripts hang.
Script1.py
import os, sys
ROOT_DIR = os.path.normpath(os.path.join(os.path.abspath(__file__), '../..'))
sys.path.insert(0, ROOT_DIR)
from Global import Global

globalObj = Global()

try:
    # Load all items on page
    driver = globalObj.getDriver()
    driver.get(PARAMS[1])

    #... code to create a JSON file and populate it.

    # Close webdriver
    globalObj.closeDriver(driver)

    print('Completed Ref: ' + str(PARAMS[2]))

except Exception as e:
    print('Error: ' + str(e.args[0]))

There are no errors or warnings in Python or PHP or any other logs available to me, the Python scripts run and create the expected JSON files they should and all looks to be working normally, the line print('Completed Ref: ' + str(PARAMS[2])) doesn't seem to print out when the Python script hangs.
Running Script1.py on the command line takes about 35 seconds to complete successfully.
Update - 27 Feb 2018
If I remove the calls to the Global class to getDriver and closeDriver then the script runs and completes and hands back to PHP to continue processing.
Script1.py - Update
import os, sys
from selenium import webdriver

try:
    # Load all items on page
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('headless')
    chrome_options.add_argument('no-sandbox')

    driver = webdriver.Chrome(executable_path='C:\chromedriver.exe', chrome_options=chrome_options)
    driver.get(PARAMS[1])

    #... code to create a JSON file and populate it.

    # Close webdriver
    driver.close()

    print('Completed Ref: ' + str(PARAMS[2]))

except Exception as e:
    print('Error: ' + str(e.args[0]))

The script runs fine in both command line and when executed via PHP using shell_exec using the above example, so there must be something I'm missing when it comes to creating an object and call the getDriver or closeDriver classes.
Update 2 - 27 Feb 2018
After further testing, I can confirm that the issue is being caused by the script1.py script calling the class Global to create the webdriver and close it, once I remove these calls in script1.py the script runs fine.
I've tried putting in sys.exit() after the globalObj.closeDriver(), I've also tried del globalObj at the end of the script with no luck.
Update 3 - 27 Feb 2018
I've changed out the webdriver from Chrome to Firefox and PhantomJS, Other drivers are working fine with the Global class, looking like it might be related to the Chrome driver at this stage.
I'm using Chrome 64.0.3282.186 (Official Build) (64-bit) and Chromedriver 2.35.

A: you can try WebDriverWait after get params which wait till the end of the process
myElem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'name_of_element')))

*i'm using firefox driver.

A: It looks like driver.close() is the cause of the problem. You need to use .quit() with Chromedriver to end the chromedriver process otherwise the process will not terminate which is why the Python script looked like it was hanging.
From:
driver.close()

To:
driver.quit()


text:
Q: When load a dump into a database, it issues: #1100 - Table 'pma__column_info' was not locked with LOCK TABLES I load a dump into database, It issue:
#1100 - Table 'pma__column_info' was not locked with LOCK TABLES

Tell me, please, how can I solve this problem?
PS: where? how? and what tables should I disable?


text:
Q: What's the situation that requires stateful firewall? I just know there is two kind of firewalls. Stateless and  stateful.
It's hard to determine what kind of firewall I have to use. Currently I have to run firewall within same machine runs services, Basically I want stateless because of its less resource consumption. However if it is not sufficient for security, it's meaningless. I'll run HTTP, SSH, NFS (only over SSH), and some custom made server on several TCP/UDP ports. Should I use stateful firewall?

(edit) Maybe the question can be assumed as 'Should I use stateful rules?'.

A: These days, there is a very simple answer to this question: all proper firewalls are now stateful.

A: stateful rules greatly simplify design of the firewall policy and improve security. HTTP and SSH work with since tcp sessions that use single port. Any stateful firewall can handle this and all you need to do is write one rule to permit original packet that opens the session and another rule to permit reply packets that match known states. In case of iptables , the latter looks like
iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

(assuming the firewall runs on the server, hence chain INPUT).
More complex protocols, such as for example ftp, may require several sessions and state engine in the firewall needs to be able to track these separate sessions to match packets. Usually stateful firewalls support most of the popular protocols but it is unlikely that they support custom protocols. The problem with custom protocols is not that they use unique tcp or udp ports, but that they may use multiple connections that are dynamically created and torn down. The firewall can dynamically open and close "holes" for the ftp data channel  because it can track and interpret commands flowing through the fto command channel. If the protocol is proprietary and unique, the firewall won't be able to interpret it and to make it work you'll have to write stateless rules and try to make them as tight as the protocol allows.
However if the protocol uses single tcp connection, then stateful rule will work just fine.

A: The only time you might possibly need a stateless firewall nowadays, is for better speed performance.


text:
Q: Using Google Sheets API in Cloud Functions in Python I've written a piece of code that was working fine on my local machine (VS Code).
I'm trying to deploy it to cloud functions and it's failing to deploy the code. Locally I have been using a credentials json which the code obviously has to access. Google Cloud Functions can't have credentials files uploaded (I believe). It's just testing so I don't mind putting APIs/keys directly into code for now.
I have read somewhere that Cloud Functions can just access the APIs if I just share the Google Sheet with the service email address (which I have done).
Here's the imported modules it fails on:
import requests
import json
import datetime
import time
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

If I remove the above then the below code will obviously fail.
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
creds = None
if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", scopes)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                "C:\\Users\\user1\\OneDrive\\VSCode\\VS code Scripts\\filename\\credentials.json",
                scopes,
            )
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open("token.json", "w") as token:
            token.write(creds.to_json())
try:
        service = build("sheets", "v4", credentials=creds)
        # Call the Sheets API
        request = (
            service.spreadsheets()
            .values()
            .get(
                spreadsheetId=spreadsheet_id,
                range=range_,
                valueRenderOption=value_render_option,
                dateTimeRenderOption=date_time_render_option,
            )
        )

I feel like the solution to get this to work is quite simple but I just can't find it anywhere! Unfortunately I only comprehend Python syntax.
Thanks in advance!


text:
Q: How to generate a file with BOM for multiple schematics - EAGLE I've 3 boards each with it's own schematic but with a lot of common components. I want to generate an unique BOM for all this boards to know quantity of each piece I need and make a single order BOM.
For example:
I can extract a single BOM with
run bom.ulp
But now I want to merge this BOMs in a single file with quantities of a common single piece sum togheder.
There is a method in EAGLE or Excel to do this? I want avoid to manually do this becouse of risk to make errors in count or add pieces.

A: File > Import > Eagle drawing > select the schematics that you want to import

Each schematic will be a new page (you should see them on the left menu numbered as 1,2,3) then click on
File > Export > BOM

Then select values and CSV file type (shown below). CSV is an universal file format that you can open with Excell or Open Office (or a text editor).

If you use Excell, then you can use =SUM() command to get the number of components.


text:
Q: What is the difference with this and slicing? https://leetcode.com/problems/reverse-string/ Hey there, I'm doing reverse the string on leetcode and this is the solution.
def reverseString(self, s):
    """
    :type s: List[str]
    :rtype: None Do not return anything, modify s in-place instead.
    """
    s[:] = s[::-1]

The part that I'm not understanding is s[:]. Why do we need that? From what I was thinking, we could simply do:
s = s[::-1]

Not understanding this and hoping someone could guide me. Thank you!

A: s = s[::-1] creates a new variable s and assigns it to the old variable s reversed, leaving the old s unchanged. s[:] = s[::-1] keeps the same old s variable and just mutates its contents with its reversed value. Basically,
def f1(s):
    s = s[::-1]

def f2(s):
    s[:] = s[::-1]

s = ["a", "b", "c"]

f1(s)
print(s)    # Outputs ["a", "b", "c"]

f2(s)
print(s)    # Outputs ["c", "b", "a"]


text:
Q: What is the difference between bridge table and helper table in data warehouse's context? From what I could understand :- Bridge tables are used when a dimension table can not be directly associated with a fact table.
e.g. In a bank's data warehouse a fact table of balance of a customer can't be stored with a customer ID as link between fact table and customer dimension due to the fact that multiple customers can be associated with same bank account. (i.e. joint account)
So fact table store account ID and bridge table between account dimension and customer dimension is used to distinguish.
But how are they different from helper tables which resolve many to many relationships between fact table and another dimension?

A: Bridge tables are the official name according to Dimensional Modeling as defined by the Kimball methodology.
Helper tables as far as I know have been used in many (often incorrect) contexts, one of which are bridge tables by people who fail to use the correct terminology.
Some people use helper table as a synonym for bridge tables, but helper tables also seem to have gotten misused in the context of a staging database or datawarehouses to name any table that helps something.
However, in dimensional modeling "helper table" isn't really defined, if it's used it's mostly as a synonym for "bridge table" (which is an actual term) or could be used to name about any table which "helps" achieving a goal but then there isn't a real definition.

A: From the definitions I've seen, helper tables and bridge tables are the same thing.
"A bridge table sits between a fact table and a dimension table and is used to resolve many-to-many relationships between a fact and a dimension. Bridge table will contain only two dimension column, key columns in both dimension."
see: http://dwhlaureate.blogspot.com/2012/10/bridge-table-in-datawarehouse.html


text:
Q: Deformation of a family of curves in a surface Let $B$ parametrize a family of (reduced) curves in $\mathbb{P}^3$. Assume there exists a smooth hypersurface $X$. in $\mathbb{P}^3$ containing all the curves parametrized by $B$. In otherwords, for the universal family $\pi:\mathcal{C} \to B$ over $B$, every fiber is contained in $X$. Suppose $X$ is of degree $d$.
The questions are then as follows:
1) Does there exist an open subset $U$ of $B$ such that there exists another smooth surface $X'$ in $\mathbb{P}^3$ (different from $X$) of degree $d$ containing the fibers $\pi^{-1}(t)$ for all $t \in U$? If this is not the case can we impose any criterion (for example any generacity condition) under which this would hold true?
2) Suppose $C$ is a curve that intersects every fiber of $\pi$ transversally.
Also assume that for every $b \in B$, there exists a smooth degree $d+1$ surface in $\mathbb{P}^3$ containing the curve $\pi^{-1}(b)$ and $C$. Does there exist an open subset $U$ of $B$ such that there exists a smooth surface $Y$ in $\mathbb{P}^3$ of degree $d+1$ containing the fibers $\pi^{-1}(t)$ for all $t \in U$ and $C$?


text:
Q: What should I use 'abbreviate', 'concise' or 'initialize'? I am looking at some Korean words and realized some of them tend to use making short word such as BLT( A sandwich filled with Bacon, Lettuce and Tomato).
e.g., Ocbesh meaning Octopus + beef intestine + shrimp
In this case, which sentence is correct?

*

*They're using abbreviated word.

*They're using concise word.

*They're using initialize word.

A: Strictly speaking, most people would regard 'Ocbesh' as a 'condensed' word - an abreviation is normally used for things like abrev.  whereas this conjoins three words into one longish word.
Both 'concise' and 'initialise' mean rather different things, and are not appropriate here, for your 'Ocbesh' example, though 'BLT' is both an abbreviation and an initialism, though the latter term isn't as common.


text:
Q: Range of cell value based on another range value I am trying to populate column C values on my sheet based on a value in column A. So if column A value is 1, then i want the value in corresponding cell in column C to be 10, else do nothing.
Sub test()

For Each cell In Sheets("Report").Range("A9:A" & LastRow)
   If cell.Value = 1 Then
      cell.Offset(0, 2).Value = 10
   End If
Next cell

End Sub

Would appreciate any help and show me a better way if there is.
thanks

A: Try below sub.
Sub test()
Dim sh As Worksheet
Dim cel As Range
Dim LastRow As Long

    Set sh = ThisWorkbook.Worksheets("Report")
    LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row
    For Each cel In sh.Range("A9:A" & LastRow)
       If cel.Value = 1 Then
          cel.Offset(0, 2).Value = 10
       End If
    Next cel
    Set sh = Nothing

End Sub


text:
Q: Eclipse Programs to Android Studio Is there any way I can call .java files from eclipse to programs in android studio and have that code be run from android studio? I cannot have the code directly copied into android studio as it brings up multiple issues. So I am wondering if there is some way I can call the .java from Eclipse, get the result from the method within that Eclipse program, and pass that result to android studio.
Any help would be greatly appreciated!

A: Very simply, no you can't "just call" code from another IDE.
You could export the Eclipse code to a JAR, import as a library into Android Studio, then try to work around that, but that sounds like a lot of work.

In regards to your previous questions, plus your comment.

it was working in eclipse, but when I literally copy and paste that exact same code into android studio, I am getting network issues when I run it.

Android has a UI Thread that does not like to handle Network requests like your bare single-threaded Eclipse project.
You need a separate thread. Without any libraries, there is AsyncTask, and the Android documentation covers this.
Though, you may find OkHttp to be better documented, useful, and less confusing than AsyncTasks. Volley is another, though works fine, is not very well documented.
See more discussion at Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

A: No, This is not possible way to do. Android studio and eclipse are different Applications and you cannot pass the Result to each other.
You can import the project or copy the files for a new Project.


text:
Q: How to bind an objects property to a Angular2 form item using select I have a problem with angular forms.
I am trying to create a form that uses data from a mongo collection and provides it via the  <select> directive.
I have a FormBuilder that is initialized like this:
ngOnInit() {
    this.addForm = this.formBuilder.group({
        department_pk: ['', Validators.required],
        name_c: ['', Validators.required],
        location_fk: [],
        expirationdate_d: [],
    });
}

The Problem is the location_fk property. I am trying to fill the value of this property via the following <select> statement (I left the other form groups (for name_c, ...) out of this code snippet):
<form [formGroup]="addForm">
    <div class="form-group">
        <label>Location (*): </label>
        <select class="form-control" formControlName="location_fk" (ngModelChange)="onChange($event)" name="select">
              <option [ngValue]="i" *ngFor="let i of locations">{{i.name_c}}</option>
        </select>
    </div>
</form>

I managed to extract the value of i, however, I want to extract a property, i.location_pk, from the collection, while still displaying i.name_c in the selection that is visible for the user. Is there any way to do this?

A: Did you tried this?
<option [ngValue]="i['propName']" *ngFor="let i of locations">{{i.name_c}}</option>

or
<option [ngValue]="i.propName" *ngFor="let i of locations">{{i.name_c}}</option>


text:
Q: Диаграмма деятельности, параллельные процессы с зависимостью Есть два параллельных процесса. Каждый процесс состоит из двух шагов. Второй шаг первого процесса выполняется всегда после первого шага. Второй шаг второго процесса выполняется только при определенном условии.
Диаграмма деятельности:

Как отразить дополнительное условие: для выполнения второго шага второго процесса необходимо завершение первого шага первого процесса.
У меня получилось:

Недостатки:

*

*Нет соответствия между fork и join

*Если условие второго процесса не выполняется токен «висит» перед join


text:
Q: syntax error in Data Explorer The Stack Exchange Data Explorer allows SQL queries against a Stack Exchange database. I tried this one —
select
  month(CreationDate) month,
  year(CreationDate) year,
  sum(lower(left(Title,2))='wh')/count(*) wh,
  (select sum(Score)/count(*)
   from Posts u
   where month(CreationDate)=month(t.CreationDate)
     and year(CreationDate)=year(t.CreationDate)
     and lower(left(Title,2))='wh'
     and PostTypeId=1 -- question
  ) wh_score,
  sum(Score)/count(*) score,
  (select sum(AnswerCount)/count(*)
   from Posts u
   where month(CreationDate)=month(t.CreationDate)
     and year(CreationDate)=year(t.CreationDate)
     and lower(left(Title,2))='wh'
     and PostTypeId=1 -- question
  ) wh_answers,
  sum(AnswerCount)/count(*) answers
from Posts t
where PostTypeId=1 -- question
group by month,year;

— but the site told me

Incorrect syntax near ')'. Incorrect syntax near 'wh_score'. Incorrect syntax near 'wh_answers'.

and I cannot figure out why. Can anyone help, please?

Things I've tried, to no avail:

*

*datepart(month,CreationDate) instead of month(CreationDate) (and likewise for year)

*explicit as for aliases (then the latter two of the three errors complained about 'at' rather than about the aliases)

*aliases that aren't built-in function names

*left(Title,2) instead of lower(left(Title,2))

*putting parentheses around the first two, and around the last two, of the four things joined by ands

*explicit u. for column names in the subqueries

A: *

*You can't group by an alias, you need to specify the computed column

*This is not allowed : sum(lower(left(Title,2))='wh'). You have to convert it into a CASE WHEN operator.

Here a corrected query (that gives a timeout):
select
    month(CreationDate) month
  , year(CreationDate) year
  , sum(case when lower(left(Title,2))='wh' then 1 else 0 end)/count(*) wh
  , (select sum(Score)/count(*)
   from Posts u
   where month(CreationDate)=month(t.CreationDate)
     and year(CreationDate)=year(t.CreationDate)
     and lower(left(Title,2))='wh'
     and PostTypeId=1 -- question
  ) wh_score,
  sum(Score)/count(*) score,
  (select sum(AnswerCount)/count(*)
   from Posts u
   where month(CreationDate)=month(t.CreationDate)
     and year(CreationDate)=year(t.CreationDate)
     and lower(left(Title,2))='wh'
     and PostTypeId=1 -- question
  ) wh_answers,
  sum(AnswerCount)/count(*) answers
from Posts t
where PostTypeId=1 -- question
group by month(CreationDate), year(CreationDate);

What are you trying to do with this query?


text:
Q: Удалить www. из url необходимо удалить из доменного имени www
домен может быть с www или без него, если он есть требуется удалить его
пытался вот так
$search = 'www.';
$st = 'www.site.ru';
$res = preg_replace('~' . preg_quote($search) . '~', '', $st, 1);

вроде все работает, но если домен будет sitewww.ru то на выходе получаем siteru

A: Заменим только те которые идут в начале строки, или после двух косых или после пробельного символа:
<?php
$search = 'www.';
$st = 'http://www.sitewww.ru';
$res = preg_replace('/(^|\/\/|\s+)('.preg_quote($search).')/', '${1}', $st, 1);
echo $res;


text:
Q: Junit in spring based project where multiple projects are involved <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="commonBean" class="commonBean">
    </bean>

</beans>

@Configuration
@ImportResource({
    "classpath:"commonConfig.xml"
    })
public class CommonBeanConfiguration{

}

We have a common project as above.We are using this as jar in another project(Main Project).
We are using commonBean bean from another project(Main Project).
When we deploy Main Project(including jar of common project) on server.It works fine.
But we get "commonBean not found exception" if we try to run junit classes from Main Project. seems like beans from commonConfig.xml is
not being created in junit.
we are using spring for testing.
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration.

A: Use this:
@ContextConfiguration(locations = "classpath:commonConfig.xml")

instead of @import as it loads the bean during runtime while @ContextConfiguration loads bean before invoking test cases.


text:
Q: Twitter returns UserJSONImpl instead of Twitter User object When i am trying to get Twitter User from Twitter it returns me UserJsonImpl
i am not able to understand it. How to handle this return Json from twitter. it must return me Twitter User object as its function described.
User user =twitter.showUser(TwitterUserID);

Here in this line i get UserJsonImpl


text:
Q: How Would You Say: ${(x,y,z)|5x+2y+z=3}$ Currently studying systems of linear equations, and came across this statement:
$\{(x,y,z)\, |\, 5x+2y+z=3\}$
I know what what the statement means, I understand that it involves set notation, I just don't know how to
articulate statements of set notation when it involves ordered-pairs/ordered-triples.
Can someone please help me articulate this statement. Thank you.

A: This is the set of all ordered triples $(x,y,z)$ such that $5x+2y+z=3$.

A: The meaning of that can be thought of every point in space, $(x,y,z)$, such that they should solve the equation $5x+2y+z=3$. So for example:
$$
A = \left(1,\frac{1}{2},-3\right)
$$
where
$$
x=1\text{ , }
y=\frac{1}{2}\text{ , }
z=-3
$$
and is an ordered-triple that solves your equation, so that point is a point in the "solution world", because:
$$
5(1) + 2\left(\frac{1}{2}\right) (-3) = 3
$$
Another example is the origin $(0,0,0)$. It isn't in the "solution world". When I say "solution world", I mean the set of all ordered-triples that solves your equation.
I don't know if you know about planes, but $5x+2y+z = 3$ can be seen as a plane in $\mathbb{R}^3$, because when you plot all the points in the canonical coordinate system, you'll actually get a plane and see that as a geometric interpretation of the "solution world".

It's important to say that what I've just said is a geometric interpretation of what you were asking. When you go above triples, you are "kinda" losing it but everything still holds.
Hope it helps!