text:
Q: Mistake done in this P&C of seating people. Q. Let 12 seats be occupied by 4 people such that there must be at least two empty seats between any two person. Number of possible arrangement is
My approach: Arrange four people now put two-two empty seats between them like
A--B--C--D

This makes 4!
Now add left two places by 5*5 but that makes wrong answer. Final answer by me is 4! * 5 *5
What is my mistake and how to correct it by this method

A: As you say, let us first pick the order that the people are sitting ignoring the condition that there must be any empty seats in-between them at all and then place two empty seats in the middle of each.  This step has $4!$ number of ways it can occur and our current setting looks like:  $A\underline{~}\underline{~}B\underline{~}\underline{~}C\underline{~}\underline{~}D$ for some arrangement of $A,B,C,D$.
This only accounts for ten of the twelve seats however.
Additional empty seats may be placed to the left of the first person, between the first two, between the second two, between the third two, or after the fourth person in the following locations (possibly multiple seats in the same location):
$\square A\square\underline{~}\underline{~}B\square\underline{~}\underline{~}C\square\underline{~}\underline{~}D\square$
Let $x_1$ denote the number of the final empty seats that you place in the first square.  Let $x_2$ denote the number of the final empty seats that you place in the second square, etc...
We have then the following system:
$\begin{cases}x_1+x_2+x_3+x_4+x_5=2\\
0\leq x_1\\
0\leq x_2\\
\vdots\\
0\leq x_5\end{cases}$
From earlier examples using the stars-and-bars approach, we know that the number of solutions to this equation is given by $\binom{5+2-1}{5-1}=\binom{6}{4}=15$
We have then as a final answer, the total number of arrangements is $4!\cdot 15$

Your mistake in saying the final step can be accomplished in $5\cdot 5$ number of ways is that you double count some scenarios.  Say you picked to the left of $A$ as the first part and to the left of $B$ as the second part.  This is also counted in the scenario that you picked to the left of $B$ for the first and to the left of $A$ for the second.  Not every situation is double counted however, for example to the left of $A$ twice.
Specifically, each time you picked two different options, you double counted.  Taking this into consideration, by subtracting the number of ways of picking two different options, we arrive at the correct answer for the number of ways of completing the second step.  $5\cdot 5 - \binom{5}{2}=25-10=15=\binom{6}{2}$


text:
Q: Cannot create a histogram data by reading an Image file I am trying to create a histogram data by reading an Image file:
>> img = imread('Flowers.jpg');
>> g = img(:,:,2);
>> bins = 0:1:255;
>> H = hist(g(:), bins);
?? Error using ==> full
Function 'full' is not defined for values of class 'uint8'.

Error in ==> C:\MATLAB\toolbox\matlab\datafun\hist.m
On line 66  ==>     xx = full(real(xx)); y = full(real(y)); % For compatibility
>> version

ans =

6.5.0.180913a (R13)

>>

I am not sure why I am receiving this error?

A: If you have the Image Processing toolbox, I recommend you use imhist instead.  This will handle uint8 images natively, without having to do any conversion, and works on binary and greyscale images.
Similarly to hist, you can either call it without outputs to just get the image directly, or get the outputs and plot the result yourself.  Unlike hist, you can only give it a number of bins (for greyscale, this defaults to 256), not a vector.
img = imread('Flowers.jpg');
g = img(:,:,2);
[counts, x] = imhist(g);
stem(x,counts); % or bar, or whatever you prefer

The output x here will be the same as your bins.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Array Try Catch can't recognize array length in if statement I had a program that has the user enter up to 5 numbers into an array then it decides what the minimum value is out of those numbers. I tried adding a try catch to it but it won't recognize the i in the [].
I've tried initializing it in the if statement but it didn't work.
    import java.util.*;

    public class Main {

      public static void main(String[] args)
      {
         double numbers[] = new double[5];

         boolean done = false;
         java.util.Scanner sc = new java.util.Scanner(System.in);

         System.out.println("\tFind the min value ");
         System.out.println();

         while(!done)
     {
      try
      {
                System.out.println("Enter 5 double numbers:");

                for(int i = 0; i < numbers.length; i++)

                numbers[i] = sc.nextDouble();
                System.out.println();

                if (numbers[i] < 0) throw new InputMismatchException();
                done = true;
      }
              catch(InputMismatchException e)
              {
                System.out.println("");
                System.out.println("Error, enter a number greater than 0");
                sc.nextLine();
                System.out.println("");
              }
         }
           System.out.println("The min value is " +min(numbers)+ ".");
           System.out.println();
      }
        public static double min(double[] array)
        {
          double min = array[0];

          for(int i = 1; i < array.length; i++)

          if (array[i] < min)
          min = array[i];
          return min;
     }
    }

Just want the try catch to catch any numbers entered that are less than 0

A: Your error is that you are using a for loop without brackets. This means that the i is recognized only by the line after the loop declaration and not the lines after. So, instead of this:
for(int i = 0; i < numbers.length; i++)

Do this:
for(int i = 0; i < numbers.length; i++) {
    //Do your loop here. "i" will be recognized.
}

A: This is because you missed { and } in your loop condition.
Try this code:
import java.util.*;

public class Main {

  public static void main(String[] args) {
     double numbers[] = new double[5];

     boolean done = false;
     java.util.Scanner sc = new java.util.Scanner(System.in);

     System.out.println("\tFind the min value ");
     System.out.println();

     while(!done) {
         try {
            System.out.println("Enter 5 double numbers:");

            for(int i = 0; i < numbers.length; i++) {
                numbers[i] = sc.nextDouble();
                System.out.println();

                if (numbers[i] < 0) throw new InputMismatchException();
                done = true;
            }
         } catch(InputMismatchException e) {
              System.out.println("");
              System.out.println("Error, enter a number greater than 0");
              sc.nextLine();
              System.out.println("");
         }
     }
     System.out.println("The min value is " +min(numbers)+ ".");
     System.out.println();
  }

  public static double min(double[] array) {
      double min = array[0];

      for(int i = 1; i < array.length; i++) {
         if (array[i] < min)
         min = array[i];
      }

      return min;
  }
}


text:
Q: Repeats the custom attribute when I use this method to get custom attributes
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($block->getItem()->getProductId());
echo '<span>' . $_product->getData('custom_attribute'). '</span>';

in this place design/fronend/theme/Magento_Checkou/templates/cart/item/default.phtml (page checkout/cart, list products), this method repeat custom attribute. When a product has no attribute, it takes from the previous product.


text:
Q: Expose GNU Screen's entire scrollback buffer without holding up arrow forever? When I reattach to a screen session, it only fills up my current terminal's window size worth of the scrollback buffer. If I enter Copy mode (ctrl+a [) then I'm able to scroll up the buffer (using the up arrow key) and "uncover" the history of this session (one line at a time). I have my scrollback buffer set to 30000 and some of the output that I want to see is very long so this can take a long time.
I tried using the hardcopy command, but that only saves whatever has been uncovered by me. I tried using g within copy mode, but that only jumped to the top of what had been uncovered. The full scrollback buffer is clearly still there because I can uncover it using the arrow key, but I can't figure out how to access the entire thing without holding the arrow key for a very long time.
Ideally, I'd be able to issue a command to store the whole screen session's past output to a file (or at least up to my screenbuffer limit). Which is what hardcopy is supposed to do. But since it is only saving what has been uncovered by my up arrow, this is useless for my situation.


text:
Q: Unable to create Play framework web application using sbt? I've followed this documentation to create a new Play application, myFirstApp, using sbt. I've a build.sbt in the myFirstApp folder and a plugins.sbt in myFirstApp/project folder.
However, I'm getting the following error on executing sbt from myFirstApp,
~/ScalaWorkspace/myFirstApp/build.sbt:7: error: not found: value playScalaSettings
playScalaSettings
^
[error] Type error in expression
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? i
[warn] Ignoring load failure: no project loaded.

How do I solve this problem?
UPDATE 1: Getting this error:
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: play#routes-compiler_2.9.2;2.1.1: not found
[warn]  :: play#templates-compiler_2.9.2;2.1.1: not found
[warn]  :: play#console_2.9.2;2.1.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::              FAILED DOWNLOADS            ::
[warn]  :: ^ see resolution messages for details  ^ ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: play#sbt-link;2.1.1!sbt-link.jar
[warn]  :: play#play-exceptions;2.1.1!play-exceptions.jar
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
sbt.ResolveException: unresolved dependency: play#routes-compiler_2.9.2;2.1.1: not found
unresolved dependency: play#templates-compiler_2.9.2;2.1.1: not found
unresolved dependency: play#console_2.9.2;2.1.1: not found
download failed: play#sbt-link;2.1.1!sbt-link.jar
download failed: play#play-exceptions;2.1.1!play-exceptions.jar

A: That was my first sbt-centric Play development so bear with me if the solution doesn't meet acceptable quality standards.
I followed the section Create a new application without having Play installed in the document Creating a new application and ended up with the following files.
build.sbt is as described in the document.
import play.Project._

name := "My first application"

version := "1.0"

playScalaSettings

I then created project/build.properties as it's a recommended approach to have reproducible builds - the version of sbt is known and fixed.
sbt.version=0.13.0

I modified project/plugins.sbt to be as follows:
// Typesafe snapshots
resolvers += "Typesafe Snapshots" at "http://repo.typesafe.com/typesafe/snapshots/"

resolvers += "Typesafe Releases" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.0-RC2")

With the files in the project, I could execute sbt and have the project's prompt.
jacek:~/sandbox/myFirstApp
$ sbt
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Loading project definition from /Users/jacek/sandbox/myFirstApp/project
[info] Set current project to My first application (in build file:/Users/jacek/sandbox/myFirstApp/)
[My first application] $ run
...lots of [SUCCESSFUL ]'s

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Ctrl+D to stop and go back to the console...)


text:
Q: Table.TransformColumns by Columns' Value I have been stuck on something on PowerQuery for hours now and I cannot seem to find a solution to my problem.
Context
I try to use "Table.TransformColumns" to change the table.
My code is
= Table.TransformColumns(table,{"A Only",
      each Table.SelectRows(_, (X)=> Text.Contains(X[Customer Search Term], [Word A]))})

and the error msg is

Expression.Error: The column 'Word A' of the table wasn't found.

If I change the [Word A] into "AAA", the code can process normally.
Does anyone know how to use the columns[Word A] instead of the string "AAA"?

A: The problem here is that Table.Transform applies a transformation to a single column and cannot reference other columns without some sort of workaround.
See this post for more information:
Power Query Transform a Column based on Another Column
The simplest approach is to define a new custom column (which can reference multiple existing columns) and then delete the existing one that it replaces.
To do it without needing an extra column, you can use the approach in the linked post and use a row transformation, which has the other columns as part of the record you're transforming:
= Table.FromRecords(Table.TransformRows(table,
      (r) => Record.TransformFields(r, {"A Only",
          each Table.SelectRows(_, (X) => Text.Contains(X[Search Term], r[Word A]))
      })))

Note the r in front of [Word A]. This is the context that was missing with Table.Transform.


text:
Q: DocumentDB: Can't access documents in my collection I'm using DocumentDB, and want to access via REST-API a specific document from one of my collections with a submitted query.
I want to test the call with Postman. I configured the headers and the authentication-token, and everything works as expected (for example I'm able to get a list of all of my collections), but I can't read the documents.
I'm calling the following URI:
POST https://xxx.azure.com/dbs/testDB/colls/offer/docs

Authorization Token is generated with the following parameters:
verb: "POST"
resourceType: "docs"
resourceID: "dbs/testDB/colls/offer"
x-ms-date: ...
masterkey: "P8riQ...aMORA=="

Headers are:
x-ms-documentdb-isquery: True
x-ms-date: ...
authorization: generated token
x-ms-version: 2015-08-06
Content-Type: application/x-www-form-urlencoded

Body is (x-www-form-urlencoded):
query: SELECT * FROM offer
parameters: []

But the response from Postman is always:
{
  "code": "Unauthorized",
  "message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'post\ndocs\ndbs/testDB/colls/offer\nfri, 30 sep 2016 13:47:32 gmt\n\n'\r\nActivityId: a76408d...e08cef"
}

What am I doing wrong?

A: It seems that you have misused the Rest API. If you are attempting to Querying Offers, the POST uri should be like with https://{databaseaccount}.documents.azure.com/offers.
And if you are attempting to Query Documents (which may actually be the one you want to achieve). The POST uri should be https://{databaseaccount}.documents.azure.com/dbs/{db-id}/colls/{coll-id}/docs
Please try to follow https://msdn.microsoft.com/en-us/library/azure/mt670897.aspx to impelemnt the Rest API to query documents.
update
And try to generate Authorization token with:
verb: "POST"
resourceType: "docs"
resourceID: "dbs/{db-id}/colls/{coll-id}"
x-ms-date: ...
masterkey: "P8riQ...aMORA=="

I used the code snippet in this answer of DocumentDB REST API with Postman outputs always "Unauthorized" error,
getAuthorizationTokenUsingMasterKey("POST", "docs", "dbs/testdb/colls/offer", headers, "{key}"));

to generate the authorization token. And worked fine on PostMan:

A: I tried to reproduce your scenario, and I was able to successfully query documents using Postman.
To help you troubleshoot, here are the parameters I used to compute the token (including a dummy key so you can try as well):

*

*Auth Token Parameters:
verb: "POST"
resourceId: "dbs/testDB/colls/offer"
resourceType: "docs"
key: "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmn=="
keyType: "master"
tokenVersion: "1.0
date: "Thu, 06 Oct 2016 04:31:33 GMT"

*The resulting token is:
type%3dmaster%26ver%3d1.0%26sig%3dC373dEIadokxR4z%2bSSpmbpVYw4e7mk9Vhae%2f5nLaD%2bU%3d

*Request verb and URI
POST https://xxx.documents.azure.com/dbs/testDB/colls/offer/docs

*Headers:
authorization: type%3dmaster%26ver%3d1.0%26sig%3dC373dEIadokxR4z%2bSSpmbpVYw4e7mk9Vhae%2f5nLaD%2bU%3d
x-ms-date: Thu, 06 Oct 2016 04:31:33 GMT
x-ms-version: 2015-08-06
x-ms-documentdb-isquery: true
Content-Type: application/query+json

*Body:
{"query":"SELECT * FROM c"}

Notice I used a different Content-Type from the one you are using. I don't think this is what's causing your issue, since you would get a Bad Request response if that were the problem.
To summarize, I believe the issue is within your token generator, since I used the same parameters as you to generate the token, and the same URI for the POST request.
I am posting a dummy masterkey, date, and resulting token so you can use it to test your token generator. Hope this help to narrow down the source of your issue.

A: I found this a bit frustrating to get working too, so I created a blog post that takes you through it - using powershell to build the calls, but the process and format of the strings is the important piece.  I had issues with the date formatting, and what strings to use to identify the resources you need to query.
Take a look at Managing DocumentDB with powershell - I found the error messages were fairly important, check the inputs you create vs the detail in the output error message.


text:
Q: awking for nth column in csv Made a file.csv. There are 3 lines.
"ip","count","filename"
"1.1.1.1","57","somefilename1"
"2.2.2.2","30","2somefilename-2"

Tryed to awk for $3 so it should just list the 3rd column.
I tried a couple of methods:
awk '{print $3}' filename.csv

Output is blank, I was expecting just the 3rd column
Tried:
awk '{print $1}' filename.csv
Shows the full document instead of just the 1st column, nothing got filtered.
I searched stackoverflow and tried a few other methods. But for some reason I either get the full row or nothing.
What am I missing sounds simple enough

A: You should use -F as for "field-separator", you can find this at the man page of awk, like this:
awk -F, '{print $3}' Input_file
"filename"
"somefilename1"
"2somefilename-2"

A: Use , as field separator:
awk -F ',' '{print $3}' filename.csv

A: Following awk solutions may help you in same.
If you want to get output with " then following may help:
awk -F, '{print $3}'  Input_file

In case you need values of 3rd column without " then following may help you:
awk -F',|"' '{print $(NF-1)}'  Input_file

A: By default awk uses space as field separator, as described in the other posts you need to configure , as field separator otherwise the whole line will be treated as one field. To do this you can choose between the following 2 syntax:
awk -F',' '{print $3}' input.csv #to avoid bad surprises with you shell trying to interpret your field separator put it between simple quotes.

or you can also defined in the BEGIN clause, or at any point during the execution using the following syntax:
awk 'BEGIN{FS=","}{print $3}' input.csv


text:
Q: Ubuntu server + Samba + PAM + Apple OpenDirectory Due to various reasons, we are looking to migrate our file servers from OS X Server 10.9 over to a true Samba implementation running on Ubuntu 14.04LTS. We have Ubuntu up and running with Samba installed, and even have PAM setup to authenticate users against our Apple OpenDirectory server.
However, getting Samba to authenticate users the way we want is proving to be quite challenging. It appears we have two choices. Option 1 is to simply have Samba delegate this to the already functional PAM subsystem; Option 2 is to use Samba's built-in support for LDAP and Kerberos. The out-of-box configuration in Ubuntu seems to favor option 1, and indeed seems like that would be the simplest setup to manage long-term. (Option 2 requires a ton more configuration including modification to the Apple schema, which I understand is not a good idea in practice.)
So, that all being said, I intend to try to get option 1 to work, (which it almost does). Currently, the PAM authentication against OD already works. I can ssh and log in as OD users on the system all day long. However, what isn't good, is that the user has to do this first before Samba will recognize them as a UNIX user. In other words, until the user successfully connects via SSH at least once, Samba will not recognize their credentials. Furthermore, I don't believe that Samba is seeing the OD groups because trying to limit connectivity to certain shares based on the group names is not working either.
Once the user has logged in one time using SSH, (or when trying to use a standard local user account) Samba accepts their name and password forevermore. Until that happens, it simply rejects them.
The smb.conf file contains these relevant entries:
server role = standalone server
obey pam restrictions = yes
passdb backend = tdbsam
unix password sync = yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
pam password change = yes
guest account = nobody
map to guest = bad user

nsswitch.conf contains these relevant entries:
passwd:         compat ldap
group:          compat ldap
shadow:         compat ldap

.
Seems like there must be a simple fix or work-around to this behavior somehow. Using commands like "getent", "id", "groups", and "passwd" are correctly returning the results and behaviors that I expect. Only smbd seems to have something extra that it needs.
I have had no luck in finding the best way to go about this, and have already spent several days pouring over documentation, web sites, O'Reilly books and experimenting with both scenarios. I've also read through this similar post here. Has anyone been down this road before? Any help is greatly appreciated, including wise UNIX anecdotes and/or moral support.
Thanks!


text:
Q: Train SVM on a very large dataset stored on hard drive There exist a very large own-collected dataset of size [2000000 12672] where the rows shows the number of instances and the columns, the number of features. This dataset occupies ~60 Gigabyte on the local hard disk. I want to train a linear SVM on this dataset. The problem is that I have only 8 Gigabyte of RAM! so I cannot load all data once. Is there any solution to train the SVM on this large dataset? Generating the dataset is on my own desire, and currently are is HDF5 format.
Thanks

A: Welcome to machine learning! One of the hard things about working in this space is the compute requirements. There are two main kinds of algorithms, on-line and off-line.

*

*Online: supports feeding in examples one at a time, each one improving the model slightly

*Offline: supports feeding in the entire dataset at once, achieving higher accuracy than an On-line model

Many typical algorithms have both on-line, and off-line implementations, but an SVM is not one of them. To the best of my knowledge, SVMs are traditionally an off-line only algorithm. The reason for this is a lot of the fine details around "shattering" the dataset. I won't go too far into the math here, but if you read into it it should become apparent.
It's also worth noting that the complexity of an SVM is somewhere between n^2 and n^3, meaning that even if you could load everything into memory it would take ages to actually train the model. It's very typical to test with a much smaller portion of your dataset before moving to the full dataset.
When moving to the full dataset you would have to run this on a much larger machine than your own, but AWS should have something large enough for you, though at your size of data I highly advise using something other than an SVM. At large data sizes, neural net approaches really shine, and can be trained in a more realistic amount of time.
As alluded to in the comments, there's also the concept of an out-of-core algorithm that can operate directly on objects stored on disk. The only group I know with a good offering of out-of-core algorithms is dato. It's a commercial product, but might be your best solution here.

A: A stochastic gradient descent approach to SVM could help, as it scales well and avoids the n^2 problem. An implementation available in R is RSofia, which was created by a team at Google and is discussed in Large Scale Learning to Rank. In the paper, they show that compared to a traditional SVM, the SGD approach significantly decreases the training time (this is due to 1, the pairwise learning method and 2, only a subset of the observations end up being used to train the model).
Note that RSofia is a little more bare bones than some of the other SVM packages available in R; for example, you need to do your own centering and scaling of features.
As to your memory problem, it'd be a little surprising if you needed the entire dataset - I would expect that you'd be fine reading in a sample of your data and then training your model on that. To confirm this, you could train multiple models on different samples and then estimate performance on the same holdout set - the performance should be similar across the different models.

A: You don't say why you want Linear SVM, but if you can consider another model that often gives superior results then check out the hpelm python package. It can read an HDF5 file directly. You can find it here https://pypi.python.org/pypi/hpelm It trains on segmented data, that can even be pre-loaded (called async) to speed up reading from slow hard disks.


text:
Q: error of (Invalid parameters) from stratify method in sklearn.model_selection.train_test_split I am trying to use stratify method in sklearn.model_selection.train_test_split.
Here is my code:
x=df["x"]
y=df["y"]
X_train, X_test, Y_train, Y_test = train_test_split( x, y, test_size=0.2, random_state=42,statify= y)

but I get this error
Invalid parameters passed: {'statify': 386 real....Name: y, Length: 527, dtype: object}

I look for this answer, They mention that stratify splitting is new in version 0.17 and I have to update my sklearn.
I looked for the version of mine. It is 0.20.2
scikit-learn              0.20.2                   pypi_0    pypi

So please anyone can help me.

A: The error you have indicates the parameter statify does not exist for this function. No wonder... because there is a typo ;-) it should be stratify instead, and this should work with your version of scikit-learn.

A: This error is due to the typo 'statify' , please change it to 'stratify' it will work. Do check this link sklearn
`


text:
Q: Genus 2 hyperelliptic cryptography : typical discriminant and class number As far as I know, there is no standard yet for cryptography based on the DLP over Jacobians of genus 2 curves. Yet, what can we say about the class number, and the discriminant of the complex multiplication field of curves that would be used in practice ? I don't think we have any competitive alternative to CM-methods to generate cryptographic curves, so the class number would be small, but what does small mean ? Like 5, 1000, or more ? How about the discriminant, what would be its typical size ? Would it more likely be smooth or have large prime divisors ?

What are the typical size of the discriminant and the class number of the CM-field of genus 2 curves that would be used in practice ?


text:
Q: Lexer rule terminates without matching terminator symbol fragment
EXEC : ('E' 'X' 'E' 'C');
fragment
CMD : ('C' 'M' 'D');
fragment
BEGIN : ('B' 'E' 'G' 'I' 'N');
fragment
END : ('E' 'N' 'D');
fragment
SEMICOLON : ';';
ExecCommand :
EXEC Whitespace CMD Whitespace
BEGIN WhiteSpace? SEMICOLON
( options {greedy=false;} : . )*
END Whitespace EXEC;
Begin : BEGIN;
End : END;
Exec : EXEC;
The ExecCommand rule terminates the scan on the first 'E' following the Semicolon and then fails if the next characters are not 'END'. The scan should only terminate on 'END' and not for 'ELSE' or any other string beginning with 'E'.
The scan loop has a test for _LA(1) == 'E' instead of match('END').
Exec, Begin and End are also token rules. The ExecCommand rule is the first rule in the lexer grammar so it should have precedence.
How do I generate a rule that will accept any arbitrary text between the start and end symbols and not terminate until the end symbol is found?
I tried the following and it did not generate successfully:
ExecCommand :
EXEC Whitespace CMD Whitespace
BEGIN WhiteSpace? SEMICOLON
( options {greedy=false;} : ~(END Whitespace EXEC) )*
END Whitespace EXEC;

A: By default there's only one lookahead, so a non-greedy loop terminates as soon as the first input char after that loop is found (the 'E'). It then attempts to match 'N' and 'D' (as directed by the END rule), which fails in your case. Try to increase the lookahead (paramater k) and see if that helps. If not you have to find a different approach.
As a side note: Exec and EXEC are entirely the same (except for their names), so either remove EXEC (if you need that lexer token in your parser) or Exec (if that lexer token is exclusively used in your lexer. Similar for END and BEGIN.


text:
Q: Update only selected row on asp.net gridview Here is the scenario, I have created a program for time in and time out
a person enters at 7 am and leaves at 2 pm
PERSON A| 7:00 AM| 2PM
Person a enters again at 3pm
PERSON A| 3:00 PM|
when i click the time out button, it will update the time out column, when it does, both timeout of person A will be updated.
here is my code
 protected void EMPLOYEERECORD_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
        Label lblEditEmpName = (Label)EMPLOYEERECORD.Rows[e.RowIndex].FindControl("lblEditEmpName");
        Label lblEditTimeOut = (Label)EMPLOYEERECORD.Rows[e.RowIndex].FindControl("lblEditTimeOut");
        TextBox txtEditRemarks = (TextBox)EMPLOYEERECORD.Rows[e.RowIndex].FindControl("txtEditRemarks");

        DatabaseModule.SQcon.Open();
        string cmdstr = "update dbo.RecordEmployee set TIME_OUT=@timeout, REMARKS=@editRemarks where EMPLOYEE_NAME =@empname";
        SqlCommand cmd = new SqlCommand(cmdstr, DatabaseModule.SQcon);

        cmd.Parameters.AddWithValue("@empname", lblEditEmpName.Text);
        cmd.Parameters.AddWithValue("@editRemarks", txtEditRemarks.Text);
        cmd.Parameters.AddWithValue("@timeout", DateTime.Now.ToString("T"));

        cmd.ExecuteNonQuery();
        DatabaseModule.SQcon.Close();
        EMPLOYEERECORD.EditIndex = -1;

        BindData();

    }

How can I update only the selected row?

A: You need to have a key to each individual row.
Your example:
PERSON A| 7:00 AM| 2PM
PERSON A| 3:00 PM|

Your update statement will update all rows that have the same employee name.  Therefore, update for PERSON A will update both rows.
If you don't already, you need to create a unique identifier for each row (e.g. an int) that will allow you to update just the specific row.
For example, the table structure could be:
1 | PERSON A| 7:00 AM| 2PM
2 | PERSON A| 3:00 PM|

And the update statement would change to:
update <whatever> where RowId = @rowId


text:
Q: How to sign up user to AWSCognitoIdentityUserPool and get the JWT tokens back? How to sign up a user to AWSCognitoIdentityUserPool and get the JWT tokens back?
I got Facebook token from facebook registration. Then how can I register user in the User pool with based on that token?
I need to get JWT tokens in responce after that to use them in my own backend.
Struggling with it a week already..

A: Recognize authentication is a two step process. First, your app must authenticate with  Facebook to receive a JWT, it seems that you have done this successfully. Second, this JWT is exchanged for IAM credentials that will be used for API calls.
Authentication Flow:

*

*App authenticates with Identity provider using the SDK for that identity provider. In response, the Identity provider sends a JWT that will be cached by the app.

*App uses cached JWT to authenticate with AWS. If the Identity provider is configured in AWS, in response, AWS sends IAM credentials with the permissions granted to that identity provider.

*IAM credentials are used to make calls to other AWS resources specified in the Policy

This documentation goes into more detail for these steps in regarding Facebook.
The AWS Amplify Library has support for iOS. I would recommend using this library to handle Authentication against Facebook Federated Identities.
You do not necessarily need a user pool managed in Cognito, as the user pool function is managed by Facebook.


text:
Q: Editing Swift markup on the iPad Playgrounds app It does not appear possible to edit previous markup on the iOS Swift Playgrounds app directly. The only way that I have found is to export the file into an Xcode Playground, perform the editing, then re-import it back into the iOS app. This is a bit long winded! Has anyone found a simpler method?
Running latest Swift Playgrounds app under iOS 12.2 on an iPad Pro 2018.

A: You are right, the markup part of a playground page can only be changed in an external editor. So your workflow
Testing on iPad -> Editing in Xcode -> Syncing with iPad
is just fine.
Currently, this seems to be the philosophy behind Swift Playgrounds.
The developer is intended to build a playground in Xcode, which the user can experience on their iPad. This includes the restriction to certain editable regions within a playground page. The user is not (yet) supposed to change major parts of the source code (including markup parts) solely on iPad.


text:
Q: Silverlight Gadget, Save data on client machine i have a Silverlight base desktop gadget. it was function well but want to save settings of gadget and updated info in to Xml and save on client Machine. is that a possible or not other way is to save on Server and map with machine name , but it will required service, is it better if i can store some data on client machine
Please Suggest me some way to do
Thanks in advance

A: Silverlight has isolated storage: http://msdn.microsoft.com/en-us/library/bdts8hk0%28v=vs.95%29.aspx

A: When an application stores data in a file, the file name and storage location must be carefully chosen to minimize the possibility that the storage location will be known to another application and, therefore, will be vulnerable to corruption. Without a standard system in place to manage these problems, developing ad hoc techniques that minimize storage conflicts can be complex, and the results can be unreliable.
With isolated storage, data is always isolated by user and by assembly. Credentials such as the origin or the strong name of the assembly determine assembly identity. Data can also be isolated by application domain, using similar credentials.
When you use isolated storage, your application saves data to a unique data compartment that is associated with some aspect of the code's identity, such as its publisher or signature. The data compartment is an abstraction, not a specific storage location; it consists of one or more isolated storage files, called stores, which contain the actual directory locations where data is stored. For example, an application might have a data compartment associated with it, and a directory in the file system would implement the store that actually preserves the data for that application. The data saved in the store can be any kind of data, from user preference information to application state. For the developer, the location of the data compartment is transparent. Stores usually reside on the client, but a server application could use isolated stores to store information by impersonating the user on whose behalf it is functioning. Isolated storage can also store information on a server with a user's roaming profile so that the information will travel with the roaming user.


text:
Q: How to use System.Web.Abstractions in a Web Forms application? I'm working on a web forms application which intends to be ported over to MVC for its vNext +1 release. But at the moment it's a .NET 3.5 SP1 web forms application.
I'm wanting to have our own context which provides some helpers on top of the standard HttpContext/ HttpRequest/ HttpResponse/ etc objects. Also, I'm wanting to have decoupling of the HttpContext classes from the context.
Because there is the intention to go MVC I thought it'd be a good idea to make our custom context work with the HttpContextBase (and associated classes) which shipped in the System.Web.Abstractions assembly.
I don't want to design a solution that solves some problems at the moment but needs to be re-written to achieve testability in MVC (and is just useless in MCV) but what I've achieved so far doesn't really seem that useful.
The problem is I can't find any good examples on how to achieve this, how to extend HttpContextWrapper, or HttpContextBase so that you can maintain seperation of concern.

A: Is it not enough to write some extension methods for the HttpContext? I've done this in my current application and it works well.  I suppose it depends how complex you want you custom HttpContext class to be and whether it's intended to represent something fundamentally different than what the standard HttpContext is representing.  I can't really think of a scenario for this though.  Perhaps you can elaborate a little more on what your custom HttpContext will look like?

A: You should not need to override the HttpContextWrapper or HttpContextBase to achieve this but instead have your custom context work with a HttpContextBase object, this way you will be able to test your custom context in isolation.
public class MyContext
{

    // helper methods work with this context
    HttpContextBase _ctx;

    public MyContext(HttpContextBase context)
    {
        _ctx = context;
    }

}

And when you create the custom context in the actual application just initialise using
new MyContext(new HttpContextWrapper(HttpContext.Current));


text:
Q: python image process with multithreading problem i have a smart door lock project with using mimic passwords and i can take mimic with camera i can detect fingers, smile, eyebrows etc. but all in one script. I want to use class things for it. I construct class build but i have to use multithreading because i have to run more than one method for detect all mimics in one cam. With my code, it opens 2 cam one by one, first opened cam and detect fingers and when i close it open another cam and detect face. how can i make it with one cam?
camera.py https://www.pythonmorsels.com/p/33trh/
FaceLandMarks.py https://www.pythonmorsels.com/p/28jmh/
HandLandMarks.py https://www.pythonmorsels.com/p/33ffw/
HandTrackingModule.py https://www.pythonmorsels.com/p/39jw2/
test.py https://www.pythonmorsels.com/p/3a2e5/

A: The simplest is to create camera outside classes and send it to classes as parameter
captureMode = cv2.VideoCapture(0)

FaceLandMarks(captureMode).run()
HandLandMarks(captureMode).run()
# etc.

captureMode.release()
cv2.destroyAllWindows()

class LandMarksFace:  # without `Camera

    def __init__(self, camera):

        self.camera = camera

        # ... code ...

    def run(self):

        # ... code ...

        success, img = self.camera.read()

        # ... code ...

And if you really need to use class Camera then create it in __init__ and set instace to all classes
class Camera():

    def __init__(self):
        self.camera = cv2.VideoCapture(0)

    def getCamera(self):
        return self.camera

cam = Camera()

FaceLandMarks(cam).run()
HandLandMarks(cam).run()
# etc.

cam.getCamera().release()
cv2.destroyAllWindows()

class LandMarksFace:  # without `Camera

    def __init__(self, camera):

        self.camera = camera

        # ... code ...

    def run(self):

        # ... code ...

        success, img = self.camera.getCamera().read()

        # ... code ...


text:
Q: The waitForResponse method doesn't work with XMLHTTP I have a code in which I declared a variable like that
Dim http As New XMLHTTP60

then in the code, I used this line
http.Open "POST", urlexample, False
http.Send strArg

How can I use the waitForResponse to wait for the server to respond to the request. I tried looping like that after the .Send statement
While http.ReadyState <> 4: DoEvents: Wend

But this works sometimes well and sometimes doesn't return anything.

A: Looking through object model seems that this method is not available through MSXML2.XMLHTTP60 but is with WinHttp.WinHttpRequest. The latter does not have a ReadyState property however.

You'll need to investigate the default timeout and see if you need SetTimeOuts on WinHttp object to obtain longer times.
Option Explicit
Public Sub testing()
    Dim http As winHttp.WinHttpRequest
    Set http = New winHttp.WinHttpRequest

    With http
        '.SetTimeouts ........
        .Open "GET", "http://books.toscrape.com/", True
        .setRequestHeader "User-Agent", "Mozilla/5.0"
        .send
        .waitForResponse 1000
    End With
    Stop
End Sub

N.B. Your request will not be async if the async arg is set to FALSE in the .Open

Interesting reading: https://github.com/VBA-tools/VBA-Web/issues/337
Seems Tim Hall's VBA-Web would be a nice pre-packaged way to go about this.
WinHTTP


text:
Q: Multiple Scatter plots with corresponding regression lines (& formula) using loops in R I know most of the programers would refer me to 'LATTICE' or 'ggplot2' packages of R as a solution to this question, but there must be a way to do it with the base package. I want to plot multiple graphs with corresponding regression lines and correlation coefficients with simple loops. An easy example data may look like-
a=list(cbind(c(1,2,3), c(4,8,12)), cbind(c(5,15,25), c(10,30,50)))
par(mfrow=c(1,2))
lapply(1:length(a), function(i)
  plot(a[[i]][,1], a[[i]][,2]))
lapply(1:length(a), function(i)
  abline(lm(a[[i]][,2]~a[[i]][,1])))
require(plotrix)
lapply(1:length(a), function(i)
  boxed.labels(a[[i]][,1][1], a[[i]][,2][3],
               labels=paste(round(cor(a[[i]][,2], a[[i]][,1], use = "pairwise.complete.obs"),2)),
               border=FALSE, adj=0.5, cex=0.8))

If you run the above script you'd notice that all linear lines and r-values will plot on the top of the last graph. Is there any way to write in the call for regression along with the plot command? Or any other clever way to deal with loops to plot regressions on corresponding figures?? It works fine for a single plot (shown below), but I'm working with a considerably large list!
plot(a[[1]][,1], a[[1]][,2])
abline(lm(a[[1]][,2]~a[[1]][,1]))
boxed.labels(a[[1]][,1][1], a[[1]][,2][3],
             labels=paste(round(cor(a[[1]][,2], a[[1]][,1], use = "pairwise.complete.obs"),2)),
                          border=FALSE, adj=0.5, cex=0.8)

A: Once you call plot(), you start drawing in a new "cell". So if you want to add more to the plot before moving on to the next one, make sure you do all of your drawing before calling the next plot()
For example
a=list(cbind(c(1,2,3), c(4,8,12)), cbind(c(5,15,25), c(10,30,50)))
par(mfrow=c(1,2))
lapply(a, function(d) {
  d <- setNames(data.frame(d), c("x","y"))
  plot( y~x, d )
  abline( lm( y ~ x, d ) )
  boxed.labels(min(d$x), max(d$y),
    labels=paste(round(cor(d$y, d$x, use = "pairwise.complete.obs"),2)),
    border=FALSE, adj=0.5, cex=0.8)
})

Note how we do all the drawing inside a single lapply() so that abline and boxed.labels are called in between the multiple plot calls rather than after they are all done.


text:
Q: Why does Ubuntu keep adding additional Ubuntu operating system choices to the Grub? When I startup my machine, the Grub (Grub2 - Karmic) starts and asks if I want to run Windows or Ubuntu. But there are 6 different choices for Ubuntu and they are all the same. Plus, when I started up today I had one more - I don't know how it got added?

A: Do you actively update the system?
The entries are probably not the exact same, but appear similar. If you look closely, the last few numbers are probably different:

You will see it changes after groups of 2. Each boot entry in Ubuntu has 2 modes by default -- regular multi-user mode and recovery mode. When you update the kernel, I believe the old entries remain in grub.cfg so you can boot into older kernels if you are having trouble with an upgraded one. You can remove them by editing /boot/grub/grub.cfg.

A: This is caused by Ubuntu system updates which update the kernel. GRUB apparently allows you to boot into different versions of the kernel, hence the different entries.

A: Are there 100% the same? If not that is probably normal (at last in Ubuntu). Those are different kernels versions. They are added during system (kernel) updates.
One old entry would be useful if You you had to fall back to older version if new kernel is working wrong and You cant boot. You can safety remove other entries.

A: That is because you have installed new kernels when upgrading, and two startup actions are installed per every new kernel.
The easiest way to solve this, is to uninstall all old kernels. I would recommend you installing the GUI program ubuntu-tweak, to do this.


text:
Q: join each row to the whole second table in R dplyr I have two tables:
table 1:
|   | a  | b  |
|---|----|----|
| 1 | a1 | b1 |
| 2 | a2 | b2 |

and
table 2:
|   | c  | d  |
|---|----|----|
| 1 | c1 | d1 |
| 2 | c2 | d2 |

I want to join them in a way that each row of table one bind column-wise with table two to get this result:
|   | a  | b  | c  | d  |
|---|----|----|----|----|
| 1 | a1 | b1 | c1 | d1 |
| 2 | a1 | b1 | c2 | d2 |
| 3 | a2 | b2 | c1 | d1 |
| 4 | a2 | b2 | c2 | d2 |

I feel like this is a duplicated question, but I could not find right wordings and search terms to find the answer.

A: There is no need to join, we can use tidyr::expand_grid:
library(dplyr)
library(tidyr)

table1 <- tibble(a = c("a1", "a2"),
                 b = c("b1", "b2"))

table2 <- tibble(c = c("c1","c2"),
                 d = c("d1", "d2"))

expand_grid(table1, table2)
#> # A tibble: 4 x 4
#>   a     b     c     d
#>   <chr> <chr> <chr> <chr>
#> 1 a1    b1    c1    d1
#> 2 a1    b1    c2    d2
#> 3 a2    b2    c1    d1
#> 4 a2    b2    c2    d2

Created on 2021-09-17 by the reprex package (v2.0.1)

A: I found a crude answer:
table1$key <- 1
table2$key <- 1
result <- left_join(table1,table2, by="key") %>%
              select(-key)

Any better answers is much appreciated.


text:
Q: Export data to CSV different row using regex I used a regular expression to extract a string from a file and export to CSV. I could figure out how to extract each match value to different rows. The result would end up in single cell
{  69630e4574ec6798,  78630e4574ec6798,  68630e4574ec6798}
I need it to be in different rows in CSV as below:
69630e4574ec6798
78630e4574ec6798
68630e4574ec6798
$Regex = [regex]"\s[a-f0-9]{16}"
Select-Object @{Name="Identity";Expression={$Regex.Matches($_.Textbody)}} |
    Format-Table -Wrap |
    Export-Csv -Path c:\temp\Inbox.csv -NoTypeInformation -Append

Details screenshot:

Edit:
I have been trying to split the data I have in my CSV but I am having difficulty in splitting the output data "id" to next line as they all come in one cell "{56415465456489944,564544654564654,46565465}".
In the screenshot below the first couple lines are the source input and the highlighted lines in the second group is the output that I am trying to get.

A: Change your regular expression so that it has the hexadecimal substrings in a capturing group (to exclude the leading whitespace):
$Regex = [regex]"\s([a-f0-9]{16})"

then extract the first group from each match:
$Regex.Matches($_.Textbody) | ForEach-Object {
    $_.Groups[1].Value
} | Set-Content 'C:\temp\a.txt'

Use Set-Content rather than Out-File, because the latter will create the output file in Unicode format by default whereas the former defaults to ASCII output (both cmdlets allow overriding the default via a parameter -Encoding).

Edit:
To split the data from you id column and create individual rows for each ID you could do something like this:
Import-Csv 'C:\path\to\input.csv' | ForEach-Object {
  $row = $_
  $row.id -replace '[{}]' -split ',' | ForEach-Object {
    $row | Select-Object -Property *,@{n='id';e={$_}} -ExcludeProperty id
  }
} | Export-Csv 'C:\path\to\output.csv' -NoType


text:
Q: MySqli Commands out of sync; you can't run this command now I have converted my register script from mysql to mysqli. I worked fine as mysql however it now gives me the error
Commands out of sync; you can't run this command now

This is the function I use to register the user
function register_user($register_data) {
global $myConnection;
array_walk($register_data, 'array_sanitize');
//Make the array readable and seperate the fields from data
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
//Insert the data and email an activation email to the user
mysqli_query($myConnection, "INSERT INTO `members` ($fields) VALUES ($data)") or die(mysqli_error($myConnection));
email($register_data['mem_email'], 'Activate your account', "Hello " . $register_data['mem_first_name'] . ",\n\nThank you for creating an account with H Fencing. Please use the link below to activate your account so we can confirm you identity:\n\nhttp://blah.blah.co.uk/activate.php?mem_email=" . $register_data['mem_email'] . "&email_code=" . $register_data['email_code'] . "\n\n - David & Jay ");
}

The email sends fine with the correct data from my array. However no data is inserted into the database and I get the error mentioned above. I have never come across this error before.

A:
If you get Commands out of sync; you can't run this command now in your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between.

From here:
http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html
Update
If you make the a variable for the query and paste the variable directly into something like MySQL Workbench you can check the syntax prior to execution.
<?php
            function myConnection(){
              $myConnection = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
              return $myConnection;
            }

    function register_user($register_data) {
        array_walk($register_data, 'array_sanitize');
        //Make the array readable and seperate the fields from data
        $fields = '`' . implode('`, `', array_keys($register_data)) . '`';
        $data = "'" . implode("', '", $register_data) . "'";
        //Insert the data and email an activation email to the user
        $query = "INSERT INTO `members` ($fields) VALUES ($data)";
                    $myNewConnection = myConnection();

                    if($result = mysqli_query($myNewConnection, $query)){
        email($register_data['mem_email'], 'Activate your account', "Hello " . $register_data['mem_first_name'] . ",\n\nThank you for creating an account with H Fencing. Please use the link below to activate your account so we can confirm you identity:\n\nhttp://blah.blah.co.uk/activate.php?mem_email=" . $register_data['mem_email'] . "&email_code=" . $register_data['email_code'] . "\n\n - David & Jay ");
        mysqli_free_result($result);
         return ("Success");
        } else {
            echo $query;
            die(mysqli_error($myNewConnection));
        }

    }

?>


text:
Q: Не работает [(ngModel)] в md-select(Angular Material) Вывожу в компоненте
<md-select [(ngModel)]="selectedOne">
    <md-option *ngFor="let food of selected" [value]="food.value" select="true">
        {{food.viewValue}}
    </md-option>
 </md-select>

Браузер выдаёт ошибку:
В классе пишу:
selected: any = [
    {viewValue: "Элемент 1", value: "0"},
    {viewValue: "Элемент 2", value: "1"},
    {viewValue: "Элемент 3", value: "2"},
    {viewValue: "Элемент 4", value: "3"},
];
selectedOne: string = "0";

Делаю всё по доке Material Angular
Но всё равно не хочется ставить элемент по умолчанию. Кто знает в чём может быть причина?
Angular cli 4.3; material 2.0

A: Директива ngModel расположена в модуле FormsModule из @angular/forms.
Поэтому для ее использования нужно импортировать этот модуль в модуль где находит указанный компонент.


text:
Q: net::ERR_INSUFFICIENT_RESOURCES error on ajax clock I have an ajax php clock set up and for some reason it's giving me thousands of net::ERR_INSUFFICIENT_RESOURCES errors in my console.
What's the reason behind this?
Code that calls out the clock function
$(document).ready(function(){
    setInterval(function(){
        $(".clock").load('<?php echo get_template_directory_uri(); ?>/melbourne.php');;
    });
}(), 1000);

Melbourne.php
<?php

date_default_timezone_set('Australia/Melbourne');

echo $date = date('H:i:s');

?>

A: You misplaced the setInterval delay. You provided it to the $(document).ready()... Which is probably discarding it. So the interval having no delay, it is sending some requests one after the other non-stop.
Look at the difference below:
$(document).ready(function(){
  setInterval(function(){
    $(".clock").load('<?php echo get_template_directory_uri(); ?>/melbourne.php');;
  },1000);
});

Also, be careful with the parenthesis after a function expression.
This is an IIFE: <-- Read that!
function something(){
  // .. some code
}()

Event handlers expect a function expression, so they can execute it at a later time. If you provide an IIFE, the event handler will receive the result of the function execution...

A: You are making AJAX calls to the Melbourne.php file every second, thus establishing a connection and killing it every second. This uses up plenty of resources and as the calls increase, the request threshold is met depending on what browser you are using.
I would suggest you use websockets (https://socket.io/docs/v4/) to request for data from melbourne.php as communication is in full duplex mode and connection is made only once.


text:
Q: Is there any way to use COUNT variable in having clause when direct count is not possible in long multi table query I have been getting this logical error, I need to get rows that have count data more than 0. I have tried

'HAVING c>0'

but it return as error

'ORA-00904: "C": invalid identifier'

Following is the query i have been trying to give me results.
SELECT ACCOUNTS.ACCOUNT_NO,(Select count(*) as cc from SALE where sale.account_no=accounts.account_no and DATED >= add_months(sysdate, -6) ) as c, (select LISTAGG(v.TYPE_NAME, ',') WITHIN GROUP (ORDER BY v.TYPE_NAME) AS deals  from  DEALSIN v  where account_no=accounts.account_no ) as deals FROM ACCOUNTS,DETAIL_ACCOUNTS,CITY WHERE ACCOUNTS.ACCOUNT_NO = DETAIL_ACCOUNTS.ACCOUNT_NO AND DETAIL_ACCOUNTS.CITY = REGISTRATION_NO AND PARENT_CODE = 111 AND STATUS = 'A' AND CITY =:CITY_Name having c>0 order by c desc

I want output as
ACCOUNT_NO  C   DEALS
1           10  deal1,deal2
2           9   deal1,deal3
3           3   deal4

but what I am getting is
ACCOUNT_NO  C   DEALS
1           10  deal1,deal2
2           9   deal1,deal3
3           3   deal4
4           0   deal  ----> DON'T WANT THIS ROW
5           0   deal0 ----> DON'T WANT THIS ROW

I dont want this row with count=0.

A: I suggest rephrasing your query to do away with those inlined correlated subqueries in the select clause.  Instead, left join to separate subqueries on the SALE and DEALSIN tables.
SELECT
    a.ACCOUNT_NO,
    COALESCE(s.cc, 0) AS c,
    COALESCE(v.deals, 'NA') AS deals,
FROM ACCOUNTS a
LEFT JOIN
(
    SELECT account_no, COUNT(*) AS cc
    FROM SALE
    WHERE DATED >= ADD_MONTHS(SYSDATE, -6)
    GROUP BY account_no
) s
    ON s.account_no = a.account_no
LEFT JOIN
(
    SELECT account_no,
        LISTAGG(v.TYPE_NAME, ',') WITHIN GROUP (ORDER BY v.TYPE_NAME) AS deals
    FROM DEALSIN
    GROUP BY account_no
) v
    ON v.account_no = a.account_no
INNER JOIN DETAIL_ACCOUNTS da
    ON a.ACCOUNT_NO = da.ACCOUNT_NO
INNER JOIN CITY c
    ON da.CITY = c.REGISTRATION_NO
WHERE
    PARENT_CODE = 111 AND
    STATUS = 'A' AND
    CITY =:CITY_Name AND
    COALESCE(s.cc, 0) > 0   -- your previous HAVING clause now appears in WHERE
ORDER BY
    c DESC;


text:
Q: Python standard logging I like using the python logging module because it standardizes my application and easier to get metrics. The problem I face is, for every application (or file.py) I am keep putting this on top of my code.
logger = logging.getLogger(__name__)
if not os.path.exists('log'):
    os.makedirs('log')

logName=time.strftime("%Y%m%d.log")
hdlr = logging.FileHandler('log/%s'%(logName))

logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s %(levelname)s - %(message)s')

ch.setFormatter(formatter)
hdlr.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(hdlr)

This is tedious and repetitive. Is there a better way to do this?
How do people log for a large application with multiple modules?

A: Take a look at logging.basicConfig().
If you wrap the basicConfig() in a function then you can just import your function and pass specific args (i.e. log filename, format, level, etc).
It will help to condense the code a bit and make it more extensible.
For example -
import logging

def test_logging(filename, format):
    logging.basicConfig(filename=filename, format=format, level=logging.DEBUG)

    # test
    logging.info('Info test...')
    logging.debug('Debug test...')

Then just import the test_logging() function into other programs.
Hope that this helps.

A: Read Using logging in multiple modules from Logging Cookbook.
What you need to do is to use getLogger() function to get a logger with a pre-defined settings.
import logging
logger = logging.getLogger('some_logger')

You set those settings just once at application startup time.


text:
Q: "Extending" an interface to allow for optional usage of function in instances I am trying to add optional spacing into generated source code, the source code is generated into several languages like Python and Java.
I have an abstract file (non final code language specific) I have a function for creating the "if" control statement. It is similar to:
ifConditions :: (RendererSym r) => (Doc -> Doc) -> Doc -> Doc -> Doc -> [(SyValue r, MBody r)] -> MBody r -> MStatement r
ifConditions a startIf c d (x:xs) z = .....

That part is not too important here other than in the body of this function there is something like
<+> startIf which I want to turn into <> optionalSpace startIf
No I could have instead simply changed <+> startIf to <> startIf and gone into each language specific file and changed the following
instance ControlStatements JavaGenCode where
  ifConditions = G.ifConditions a startIf b c

into the following if I wanted a space. prepSpace could be imported from an "abstract" file into each language specific rendering file as needed.
prepSpace :: Doc -> Doc
prepSpace x = space <> x

instance ControlStatements JavaGenCode where
  ifConditions = K.ifConditions a (prepSpace startIf) b c

Instead is it possible (a good idea) to add this to the ControlStatements class?
class (BSym r, VSym r) => ControlStatements r where
  ifConditions :: [(SyValue r, MBody r)] -> MBody r -> MStatement r
  optionalSpace :: Label -> MStatement r

Then in each language specific rendering file:

instance ControlStatements JavaGenCode where
  ifConditions = K.ifConditions a startIf b c  --same as before
  optionalSpace = K.optSpace Empty

and in K file:
optionalSpace :: (RendererSym r) => Label -> MStatement r
optionalSpace n = ...

My main confusion is tying it all back into ifConditions. Now that

*

*I have optionalSpace in the ControlStatements class

*I have an instance in instance ControlStatements JavaGenCode, as needed

*optionalSpace is defined in K

How can I tie this back into the ifConditions function, so that I can use <> optionalSpace startIf? What am I overlooking here?

A: There's a lot of missing context (why is optionalSpace :: Label -> MStatement r being used like it's Doc -> Doc (in <> optionalSpace startIf)? Why is ifConditions a method if you're always going to implement it using K.ifConditions? ...)
A shot in the dark.
Try defining a wrapper around K.ifConditions in the file containing the ControlStatements class,
class ControlStatements r where
  ifConditions :: ...
  optionalSpace :: ...

kifConditions :: ControlStatements r => ...
kifConditions a startIf b c = K.ifConditions a (optionalSpace startIf) b c


text:
Q: Sets cut into two halves of equal size by any straight line through a particular point Is there an easy characterization of all sets $M \subseteq \mathbb{R}^2$ with the following property?
A point $(x_M,y_M)$ (which may depend on $M$) exists such that each straight line through $(x_M,y_M)$ cuts $M$ into two halves of equal Lebesgue measure.

A: Let's use a polar coordinate system with $M$ as the  origin.  Then the property can be stated as: the area of $M$ within the angular range $\alpha\le \theta\le \alpha+\pi$ is independent of $\alpha$. This area is
$$\frac12 \int_\alpha^{\alpha+\pi} \int_0^\infty \chi_M(r,\theta) r\,dr\,d\theta$$
where $\chi_M$ is the characteristic function of $M$. Differentiation with respect to $\alpha$ yields
$$I(\alpha) =I(\alpha+\pi) \quad \text{for a.e. } \alpha,  \text{ where }\ I(\alpha) = \int_0^\infty \chi_M(r,\alpha) r\,dr$$
This is a necessary and sufficient condition. It doesn't look particularly geometric, but that's what it is.
In the special case when the region is star-shaped about $M$, i.e., is described by $r\le f(\theta)$, the condition becomes $f(\theta)=f(\theta+\pi)$ a.e., which is central symmetry (up to a set of zero measure).
A non-centrally symmetric example: annulus-type domain
$$
\sqrt{1+\cos\theta}\le r\le \sqrt{2+\cos\theta}
$$
pictured below:

Of course,   $\sqrt{f(\theta)}\le r\le \sqrt{A+f(\theta)}$ works as well, for any function $f$ and any constant $A$.


text:
Q: What is the mean and variance of the averaged value over $n$ random variables with Rice distributions? Assuming there are $n$ uncorrelated random variables (RVs) with Rice (Rician) distributions $R1~N(u_1,s_1) \ldots R_n~N(u_n,s_n)$, with non-zero mean and different variance, what is the mean and variance of $Z= \displaystyle \frac{R1+\ldots+Rn}{n}$?
Thank you!

A: check out the following wikipedia link http://en.wikipedia.org/wiki/Rice_distribution and use the commented hint


text:
Q: Received email pdf display no name i have created custom form module that send the email with pdf,
attachment sends but in email it shows no name, in image it shows error,
My Code..........
TransportBuilder.php
app/code/Vendor/Module/Magento/Mail/Template
<?php
namespace Vendor\Module\Magento\Mail\Template;

use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\MessageInterfaceFactory;
use Magento\Framework\Mail\Template\FactoryInterface;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Magento\Framework\ObjectManagerInterface;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\PartFactory as MimePartFactory;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\MessageFactory as MimeMessageFactory;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    /** @var MimePart[] */
    private $parts = [];

    /** @var MimeMessageFactory */
    private $mimeMessageFactory;

    /** @var MimePartFactory */
    private $mimePartFactory;

    public function __construct(
        FactoryInterface $templateFactory,
        MessageInterface $message,
        SenderResolverInterface $senderResolver,
        ObjectManagerInterface $objectManager,
        TransportInterfaceFactory $mailTransportFactory,
        MimePartFactory $mimePartFactory,
        MimeMessageFactory $mimeMessageFactory,
        MessageInterfaceFactory $messageFactory = null
    ) {
        parent::__construct(
            $templateFactory,
            $message,
            $senderResolver,
            $objectManager,
            $mailTransportFactory,
            $messageFactory
        );

        $this->mimePartFactory    = $mimePartFactory;
        $this->mimeMessageFactory = $mimeMessageFactory;
    }

    protected function prepareMessage()
    {
        parent::prepareMessage();

        $mimeMessage = $this->getMimeMessage($this->message);

        foreach ($this->parts as $part) {
            $mimeMessage->addPart($part);
        }

        $this->message->setBody($mimeMessage);

        return $this;
    }

    public function addAttachment(
        $body,
        $mimeType = Mime::TYPE_OCTETSTREAM,
        $disposition = Mime::DISPOSITION_ATTACHMENT,
        $encoding = Mime::ENCODING_BASE64,
        $filename = null
    ) {
        $this->parts[] = $this->createMimePart($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }

    private function createMimePart(
        $content,
        $type = Mime::TYPE_OCTETSTREAM,
        $disposition = Mime::DISPOSITION_ATTACHMENT,
        $encoding = Mime::ENCODING_BASE64,
        $filename = null
    ) {
        /** @var MimePart $mimePart */
        $mimePart = $this->mimePartFactory->create(['content' => $content]);
        $mimePart->setType($type);
        $mimePart->setDisposition($disposition);
        $mimePart->setEncoding($encoding);

        if ($filename) {
            $mimePart->setFileName($filename);
        }

        return $mimePart;
    }

    private function getMimeMessage(MessageInterface $message)
    {
        $body = $message->getBody();

        if ($body instanceof MimeMessage) {
            return $body;
        }

        /** @var MimeMessage $mimeMessage */
        $mimeMessage = $this->mimeMessageFactory->create();

        if ($body) {
            $mimePart = $this->createMimePart((string)$body, Mime::TYPE_TEXT, Mime::DISPOSITION_INLINE);
            $mimeMessage->setParts([$mimePart]);
        }

        return $mimeMessage;
    }
}

Post.phtml
app/code/Vendor/Module/Controller/Index
<?php
namespace Vendor\Module\Controller\Index;

use Zend\Log\Filter\Timestamp;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Post extends \Magento\Framework\App\Action\Action
{
    const XML_PATH_EMAIL_RECIPIENT_NAME = 'trans_email/ident_support/name';
    const XML_PATH_EMAIL_RECIPIENT_EMAIL = 'trans_email/ident_support/email';

    protected $_inlineTranslation;
    protected $_transportBuilder;
    protected $_scopeConfig;
    protected $_logLoggerInterface;

      private $fileUploaderFactory;
        private $fileSystem;
        //protected $_transportBuilder;
        //protected $inlineTranslation;
        //protected $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
         \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
         Filesystem $fileSystem,
        \Psr\Log\LoggerInterface $loggerInterface,
        array $data = []

        )
    {
        $this->_inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder;
        $this->_scopeConfig = $scopeConfig;
        $this->_logLoggerInterface = $loggerInterface;
        $this->messageManager = $context->getMessageManager();
        $this->fileUploaderFactory = $fileUploaderFactory;
        $this->fileSystem          = $fileSystem;
        parent::__construct($context);
    }

    public function execute()
    {
        $post = $this->getRequest()->getPost();
        //echo "<pre>";print_r($post); die();
       // $filesData = $this->getRequest()->getFiles('attachment');
       // print_r($filesData);die;
        try
        {

           $filesData = $this->getRequest()->getFiles('attachment');

            if ($filesData['name']) {
             $uploader = $this->fileUploaderFactory->create(['fileId' => 'attachment']);
             $uploader->setAllowRenameFiles(true);
             $uploader->setFilesDispersion(true);
             $uploader->setAllowCreateFolders(true);
             $path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('test-doc');
             $result = $uploader->save($path);
             $attachment = 'test-doc'.$uploader->getUploadedFilename();
             $filePath = $result['path'].$result['file'];
             $fileName = $result['name'];
        } else {
             $attachment = '';
             $filePath = '';
             $fileName = '';
        }

            // Send Mail
            $this->_inlineTranslation->suspend();
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

            $senderName = $post['name'];
            $senderAddress = $post['address'];
            $senderCity = $post['city'];
            $senderState = $post['state'];
            $senderZipcode = $post['zipcode'];
            $senderEmail = $post['email'];
            $senderHomephone = $post['homephone'];
            $senderCellphone = $post['cellphone'];
            $senderSalesexperience = $post['salesexperience'];

            $sender = [
                'name' => $post['name'],
                'address' => $post['address'],
                'city' => $post['city'],
                'state' => $post['state'],
                'zipcode' => $post['zipcode'],
                'email' => $post['email'],
                'homephone' => $post['homephone'],
                'cellphone' => $post['cellphone'],
                'salesexperience' => $post['salesexperience']
            ];

            $sentToEmail = $this->_scopeConfig ->getValue('trans_email/ident_general/email',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);

            $sentToName = $this->_scopeConfig ->getValue('trans_email/ident_general/name',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);

            $transport = $this->_transportBuilder
            ->setTemplateIdentifier('customemail_email_template')
            ->setTemplateOptions(
                [
                    'area' => 'frontend',
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                ]
                )
                ->setTemplateVars([
                    'name' => $post['name'],
                    'address' => $post['address'],
                    'city' => $post['city'],
                    'state' => $post['state'],
                    'zipcode' => $post['zipcode'],
                    'email' => $post['email'],
                    'homephone' => $post['homephone'],
                    'cellphone' => $post['cellphone'],
                    'salesexperience' => $post['salesexperience']
                ])
                ->setFrom($sender)
                ->addTo($sentToEmail,$sentToName)
                ->addAttachment($filePath, $fileName)
                //->addTo('owner@example.com','owner')*/
                ->getTransport();

                $transport->sendMessage();

                $this->_inlineTranslation->resume();
                $this->messageManager->addSuccess('Email sent successfully');
                $this->_redirect('customemail/index/index');

        } catch(\Exception $e){
            $this->messageManager->addError($e->getMessage());
            $this->_logLoggerInterface->debug($e->getMessage());
            exit;
        }
    }
}

i dont know where is the mistake..
pls help me..
tthanks

A: you put null in your file name  in TransportBuilder.php
public function addAttachment(
        $body,
        $mimeType = Mime::TYPE_OCTETSTREAM,
        $disposition = Mime::DISPOSITION_ATTACHMENT,
        $encoding = Mime::ENCODING_BASE64,
        $filename = *<here get cuurent file name>*
    ) {
        $this->parts[] = $this->createMimePart($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }

A: use this for encoding
$encoding = '8bit'


text:
Q: Insert into a table on the basis of condition in mysql 5.7 I have a table named 'Student' with columns Name, Role, Class and Subject.
I have another table named 'StudentClass' with columns Name and Class. I have to insert Name and Class columns of 'StudentClass' table from 'Student' table if the Name and his corresponding Class do not exist in the 'StudentClass' table. If Name exist in the 'StudentClass' table but its corresponding Class value is different for that row, then update the Class value for that row in 'StudentClass' table
I can't simply truncate the 'StudentClass' table and insert Name and Class from 'Student' table because I have keep track of any change made in the 'StudentClass' table.
So is there any mySQL query which inserts Name and Class from 'Student' table into 'StudentClass' table if the Name and its corresponding Class do not exist in 'StudentClass' table else update the row if Name exist but its corresponding Class value is different.

A: Try this:
INSERT INTO StudentClass (Name, Class)
SELECT Name, Class FROM Student AS S
  WHERE NOT EXISTS (SELECT * FROM StudentClass AS SC
                    WHERE SC.Name = S.Name AND SC.Class=S.Class);

You can find out more about EXISTS and NOT EXISTS here.

A: The query posted by you worked only for inserting new entries. I does not provide the update function. So I modified the your query and added an update query with the insert query which solved my issue.
INSERT INTO StudentClass (Name, Class)
SELECT Name, Class FROM Student AS S
  WHERE NOT EXISTS (SELECT * FROM StudentClass AS SC
                    WHERE SC.Name = S.Name);

UPDATE StudentClass SC INNER JOIN Student S ON SC.Name = S.Name
      SET SC.Class = S.Class WHERE SC.Class != S.Class

Thanks for help


text:
Q: Capture sound from headphones in OpenAL I want to record sound from headphones with OpenAL. I know how to record microphone, I know how to save a data into .wav file. But I can't find a way to record a headphones.
I have a name of a headphones device, but when I pass it to alcCaptureOpenDevice() this function returns NULL and the only way to make this function return not NULL is to pass a default capture device(which is a microphone). Maybe I understand something wrong about this function.
So my question is there any way to record a sound from headphones in OpenAL?


text:
Q: object Object displaying in browser with Ext.DomHelper.insertHtml I appreciate the patience in advance, as I am new to ExtJS. I am trying to add an html element when loading my store. Currently, it is appending the object [object Object] to the page, but I need to display the div itself. The tileDiv in the DomHelper line is my issue. My code is as follows:
function handleKeyUp(e) {
   var code = e.keyCode ? e.keyCode : e.which;
   if (code === 38) { //up key
      alert('up');
   } else if (code === 40) { //down key
      alert('down');
   }
}
var tileDiv = new Ext.Element({
   tag: 'div',
   id: tileId,
   cls: 'tile',
   html: html,
   listeners: {
      keyup: handleKeyUp,
      scope: this
   }
});
Ext.DomHelper.insertHtml('beforeEnd', this.el.dom, tileDiv);

A: You are confusing Ext elements with HTML DOM elements. An Ext Element is an object created by ExtJS that wraps a DOM element.
Look at the doc:
insertHtml( where, el, html ) : HTMLElement
Inserts an HTML fragment into the DOM.

It expects the last statement to be an HTML fragment. You are passing an Ext.Element.
What you are probably trying to do is something like this:
Ext.onReady(function(){
    Ext.DomHelper.append(Ext.getBody(), {
        tag: 'div',
        id: 'tileId',
        cls: 'tile',
        html: '
Hello world
',
        listeners: {
           keyup: function handleKeyUp(e) {
                var code = e.keyCode ? e.keyCode : e.which;
                if (code === 38) { //up key
                    alert('up');
                } else if (code === 40) { //down key
                    alert('down');
                }
            },
           scope: this
        }
    });
});

http://jsfiddle.net/RCXdL/
Please note that your event handler onKeyUp will only work on focusable elements. (see http://www.quirksmode.org/dom/events/keys.html)


text:
Q: AUI Scheduler trigger modal instead tooltip maybe someone could help me. I want to open a modal instead of the standard event tooltip, but i'm a .js noob and i can't solve this problem.
For now #myModal opens after i pressed the "save" Button of the appearing tooltip, but i want to open the modal on mouse release and prevent the tooltip from appearing. Is this understandable?
Here is my code:
<script type="text/javascript">
YUI().use(
  'aui-scheduler',
  function(Y) {
      var events = [
                    {
                      content: 'Partial Lunar Eclipse',
                      endDate: new Date(2013, 3, 25, 5),
                      startDate: new Date(2013, 3, 25, 1)
                    }
                  ];

                  var agendaView = new Y.SchedulerAgendaView();
                  var dayView = new Y.SchedulerDayView();
                  var eventRecorder = new Y.SchedulerEventRecorder();
                  var monthView = new Y.SchedulerMonthView();
                  var weekView = new Y.SchedulerWeekView();

                  new Y.Scheduler(
                    {
                        activeView: weekView,
                      boundingBox: '#myScheduler',
                      date: new Date(2015, 5, 22),
                      eventRecorder: eventRecorder,
                      items: events,
                      render: true,
                      views: [dayView, weekView, monthView, agendaView]
                    }
                  );
                  Y.Do.before(function() {
                      this.on("save",function(data){
                          $('#myModal').modal('show');
                        });
                        }, eventRecorder, 'showPopover');
  }

);

A: Just found out how to fix this. Just changed:
  Y.Do.before(function() {
                  this.on("save",function(data){
                      $('#myModal').modal('show');
                    });
                    }, eventRecorder, 'showPopover');

to
  $( "#myScheduler" ).mouseup(function() {
      $('#myModal').modal('show');
                    });


text:
Q: How is the string column in DataFrame split into multiple columns when Spark Structed Streaming This is the current code:
from pyspark.sql import SparkSession

park_session = SparkSession\
    .builder\
    .appName("test")\
    .getOrCreate()

lines = spark_session\
    .readStream\
    .format("socket")\
    .option("host", "127.0.0.1")\
    .option("port", 9998)\
    .load()

The 'lines' looks like this:
+-------------+
|    value    |
+-------------+
|     a,b,c   |
+-------------+

But I want to look like this:
+---+---+---+
| a | b | c |
+---+---+---+

I tried using the 'split()' method, but it didn't work. You could only split each string into a list in a column, not into multiple columns
What should I do?

A: Split the value column and by accessing array index (or) element_at(from spark-2.4) (or) getItem() functions to create new columns.

from pyspark.sql.functions import *

lines.withColumn("tmp",split(col("value"),',')).\
withColumn("col1",col("tmp")[0]).\
withColumn("col2",col("tmp").getItem(1)).\
withColumn("col3",element_at(col("tmp"),3))
drop("tmp","value").\
show()
#+----+----+----+
#|col1|col2|col3|
#+----+----+----+
#|   a|   b|   c|
#+----+----+----+

A: from pyspark.sql.functions import *
import pyspark.sql.functions as f
from pyspark.sql import SparkSession

spark_session = SparkSession\
    .builder\
    .appName("test")\
    .getOrCreate()

lines = spark_session\
    .readStream\
    .format("socket")\
    .option("host", "127.0.0.1")\
    .option("port", 9998)\
    .load()

split_col = f.split(lines['value'], ",")
df = df.withColumn('col1', split_col.getItem(0))
df = df.withColumn('col2', split_col.getItem(1))
df = df.withColumn('col2', split_col.getItem(2))

df.show()

A: Incase you have different numbers of delimiters and not just 3 for each row , you can use the below:
Input:
+-------+
|value  |
+-------+
|a,b,c  |
|d,e,f,g|
+-------+

Solution
import pyspark.sql.functions as F

max_size = df.select(F.max(F.length(F.regexp_replace('value','[^,]','')))).first()[0]
out = df.select([F.split("value",',')[x].alias(f"Col{x+1}") for x in range(max_size+1)])

Output
out.show()

+----+----+----+----+
|Col1|Col2|Col3|Col4|
+----+----+----+----+
|   a|   b|   c|null|
|   d|   e|   f|   g|
+----+----+----+----+


text:
Q: change stroke-width inside a circular svg Trying to change stroke-width of paths inside a svg.
Both paths should be 9 instead of 3 and 5.
As a result I'm getting deformed (not circular) paths.
Any help and a short explaination, pls.

.single{
width:120px;
height:120px;
}

 <svg viewBox="0 0 100 100" style="display: block; width: 100%;"><path d="M 50,50 m 0,-47.5 a 47.5,47.5 0 1 1 0,95 a 47.5,47.5 0 1 1 0,-95" stroke="#4598C9" stroke-width="3" fill-opacity="0"></path>

  <path d="M 50,50 m 0,-47.5 a 47.5,47.5 0 1 1 0,95 a 47.5,47.5 0 1 1 0,-95" stroke="#dd4b39" stroke-width="5" fill-opacity="0" class = "xpath" style="stroke-dasharray: 300, 300; stroke-dashoffset: 255;"></path></svg>

A: Your shape is bigger than the viewBox if you make the stroke-width larger. One way to fix that is to change the viewBox sizing so the shape appears a little smaller and fits in the drawing area.

.single{
width:120px;
height:120px;
}

 <svg viewBox="-3 -3 106 106" style="display: block; width: 100%;"><path d="M 50,50 m 0,-47.5 a 47.5,47.5 0 1 1 0,95 a 47.5,47.5 0 1 1 0,-95" stroke="#4598C9" stroke-width="9" fill-opacity="0"></path>

  <path d="M 50,50 m 0,-47.5 a 47.5,47.5 0 1 1 0,95 a 47.5,47.5 0 1 1 0,-95" stroke="#dd4b39" stroke-width="9" fill-opacity="0" class = "xpath" style="stroke-dasharray: 300, 300; stroke-dashoffset: 255;"></path></svg>


text:
Q: How download all version of a git hub file I would like to know how to locally download all versions of a file from git hub.
I know I can get them directly from the browser but I don't want just a few but all of them even a hundred.
If I use git log I can see all the commits that have been made but I can't download all the versions of that file to my computer.
Can someone help me?
I expect all versions of a git hub file on my computer


text:
Q: How to return data from a private access variable? This is a program that asks the user to enter 1 to store name. Then the program will prompt the user to enter his/her name. After, the program stores the data in an array. Then i have to use a method to do the storage. However, I have a getter and setter methods but i get an error "error: Name has private access in className".
I would like to return the name from my "className" constructors.
I appreciate your assistance. Thanks.
Main Class "ReturnName"
import javax.swing.JOptionPane;

   public class ReturnName
    {
  public static void main (String[] args)
    {

className x = new className();

int menu = Integer.parseInt(JOptionPane.showInputDialog("Choose an option:" + "\n" +
                                                        "Enter 1 to store name"));

if(menu == 1){
String[] input1 = new String[1];

for(int i = 0; i < input1.length; i ++){

String str1 = JOptionPane.showInputDialog("Enter your name");

input1[i] = str1;

}
method(input1);

}

}public static void method(String [] input1){

String Name = "";

for(int i = 0; i < input1.length; i++){

    Name = input1[i];

}
className HoldName = new className();
System.out.println(HoldName.Name);

   }

   }

className
class className{

private int Menu;
private String Name;

public className(){

   Menu = 0;
   Name = "";

}

public className(String n, int m){

   Menu = m;
   Name = n;

}
public String getName(){

    return Name;
}

public int getMenu(){

    return Menu;
}

public void setName(String n){

    Name = n;
}

public void setMenu(int m){

    Menu = m;
}

     }

A: Yes because the access modifier of Name is private and you can't access it this way, so instead of directly calling HoldName.Name use getter method HoldName.getName()

A: The issue is that ReturnName attempts to read the value of the private variable Name. Remember that a private variable is just that: private, i.e. it can only be read and written from the object where that variable is declared. If other objects want to access that variable, they must go through the getter method.
EDIT: the name is not printed because the method setName is never called. The for loop in method is also wrong.
Do:
 public static void method(String name){
  className holdName = new className();
  className.set(name);
  System.out.println(holdName.getName());
 }

And call it as:
 String str1 = JOptionPane.showInputDialog("Enter your name");
 method(str1);


text:
Q: Can tsqlt table accessed outside of tSqlt scope? I am writing a tsqlt unit testing where I am not faking the table and I am using the real SQL table ex:sendEmail to test the email sending functionality.
I am inserting the value like below from tsqlt to the sendEmail table
Email: 'test@test.com'
Status : 0
Template : 'New User Creation'

There is an automation job outside of tsqlt that will look for these table entries which have Status :0 process the email to the sender address and update back to the table's column value as Status:1
But I am not seeing the automation job is able to do success with email sending during this tsqlt regression scenario. Can't we access the SQL table and its value outside use when tsqlt is running? Any guidance would be highly appreciated.
tSqlt will be running only in the isolated way and can't integrate with any other code or application?


text:
Q: Service Fabric, Akka.net and Persistent actor integration I have some snippet of code from a working example. This example is to make a REST call (WebAPI) and a poller in the service fabric to poll the requests. There are five actors (1) FileImportValidator to validate the file name (2) FileParser to parse the file (3) AgeValidator to validate the age (4) FilePersister to persist the name and age as an event.
Please share whether this design is what expected of actor modeling with AKKA.NET for a Event Sourced system.
PS. The file to parse has been already uploaded. The REST call is to provide the file name only. I have purposefully eliminated some validation logic.
//WebAPI:

        [HttpPost]
        [Route("import")]
        public async Task<IHttpActionResult> Import(FileImportRequest request)
        {
            IReliableQueue<string> queue = await stateManager.GetOrAddAsync<IReliableQueue<string>>("inputQueue");

            using (ITransaction tx = stateManager.CreateTransaction())
            {
                await queue.EnqueueAsync(tx, request.FileName);

                await tx.CommitAsync();
            }

            return Ok();
        }

  // Poller in Microsoft Service Fabric MicroService:

    public class FileImportMicroService : StatefulService
    {
        public FileImportMicroService()
        {
            domainActorSystem = ActorSystem.Create("DomainActorSystem");

            fileImportValidator = domainActorSystem.ActorOf(Props.Create<FileImportValidator>(), "FileImportValidator");
        }

        protected override ICommunicationListener CreateCommunicationListener()
        {
            ServiceEventSource.Current.CreateCommunicationListener(typeof(FileImportMicroService).Name);

            return new OwinCommunicationListener(typeof(FileImportMicroService).Name, new StartUp(StateManager));
        }

        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var queue = await StateManager.GetOrAddAsync<IReliableQueue<string>>("inputQueue");

            while (!cancellationToken.IsCancellationRequested)
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    ConditionalResult<string> dequeuReply = await queue.TryDequeueAsync(tx);

                    if (dequeuReply.HasValue)
                    {
                        FileImportValidator.Tell(new ValidateFileCommand(dequeuReply.Value));
                    }

                    ServiceEventSource.Current.Message(dequeuReply.Value);

                    await tx.CommitAsync();
                }

                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
        }

        ActorSystem domainActorSystem;

        IActorRef fileImportValidator;
    }

//FileImportValidator Actor

    public class FileImportValidator : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            Handle((dynamic) message);
        }

        public void Handle(ValidateFileCommand command)
        {
            _fileParser = Context.ActorOf(Props.Create(() => new FileParser()));

            ...

            _fileParser.Tell(new ValidationSuccessfulEvent(command.FileName));
        }

        private IActorRef _fileParser;
    }

//FileParser Actor:

    public class FileParser : UntypedActor
    {
        private IActorRef _ageValidator;

        protected override void OnReceive(object message)
        {
            Handle((dynamic) message);
        }

        public void Handle(ValidationSuccessfulEvent message)
        {
            var lines = File.ReadLines(message.FileName);

            foreach(var line in lines)
            {
                var cols = line.Split(',');

                var File = new { Name = cols[0], Age = cols[1] };

                _ageValidator.Tell(new ValidateAge(File.Name, File.Age));
            }
        }

        protected override void PreStart()
        {
            _ageValidator = Context.ActorOf(Props.Create(() => new AgeValidator()));

            base.PreStart();
        }
    }

//AgeValidator Actor:

    public class AgeValidator : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            if (message is ValidateAge)
            {
                _filePersistor.Tell(new SaveNameAndAge(message));
            }
        }

        protected override void PreStart()
        {
            _filePersistor = Context.ActorOf(Props.Create<FilePersistor>(), "file-persistor");

            base.PreStart();
        }

        private IActorRef _filePersistor;
    }

//Persistent Actor:

    public class FilePersistor : PersistentActor
    {
...
        protected override bool ReceiveCommand(object message)
        {
            Persist(/* Handler to persist name and age */);

            return true;
        }
...
    }

A: Another approach you may consider is to use a ReliableDictionary in a Service to 'persist' the state of the system (files that have been processed). When a new file is uploaded you create a new actor and you pass a FileId so the actor can retrieve the data and process it. When it is done it calls the Service so the item can be removed from the list. In this way you can parallelize file processing.


text:
Q: fmdb ios create and insert query I am using this query to populate and create my table.But Its not creating the table and not inserting values.Using FMDB for ios.I am a noob in ios database and this is not working.Please guide me how should I make it work.Thanks in Advance.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *docsPath = [paths objectAtIndex:0];
 NSString *path = [docsPath stringByAppendingPathComponent:@"example.db"];

  database = [FMDatabase databaseWithPath:path];

 [database open];

 [database executeUpdate:@"CREATE TABLE `report` (`id` int(100) NOT NULL AUTO_INCREMENT,`Date` double NOT NULL,`product` varchar(200) NOT NULL,`Description` varchar(200) NOT NULL,`price` varchar(200) NOT NULL,`address` varchar(200) NOT NULL,`payment` varchar(200) NOT NULL, PRIMARY KEY (`id`))"];

 [database executeUpdate:@"insert into report(Date, product, Description, price, address,payment) values(?,?,?,?,?,?)",
 1/1/05,abc,example,example123,example456,123,nil];

A: It`s a SQLite , not MySQL
use this query to create table if it does not exist
CREATE  TABLE  IF NOT EXISTS report (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , date DOUBLE NOT NULL , product VARCHAR NOT NULL , description VARCHAR NOT NULL , price VARCHAR NOT NULL , address VARCHAR NOT NULL , payment VARCHAR NOT NULL )


text:
Q: Confused with cookies I am trying to figure out cookies with JS and I am totally lost, it is so much easier with PHP. I have this line of code could someone explain to me what it means?
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : ";
expires=" + expires.toGMTString());
}

A: http://www.quirksmode.org/js/cookies.html has more information...
the + in JS is equivalent to . in PHP (concatenates)...so you're building a string from the inputs, and formatting the various pieces accordingly (like converting expires)
then, document.cookie={that string} sets it

A: Explanation to your code
document.cookie accept a string of the form key=value to set the cookie.
A reference could be find from Mozilla

cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:

According to this specification, this string should be name=value ;expires=date ;domain=domain ;path=path
In your case, the + operator behaves the same like . operator in PHP. It performs string concaction.
var b = 'I' + ' am' + ' a' + ' JavaScript' +' hacker.'
>>'I am a JavaScript hacker.'

A Better Solution
To ease your pain, I suggest using the jquery.cookie plugin.
To set a cookie
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

To get a cookie
$.cookie('the_cookie');

To delete the cookie
$.cookie('the_cookie', null);

A: Cookies have several parts many of them optional
 Tokens: name=value ;expires=date ;domain=domain ;path=path

escape(value)
Escape non alphanumeric characters such as spaces and special characters and
replaces them with there hexadecimal equilivments
like %hh, A space would would be %20
path=/"  A subset of paths at domain "/" everything from and beneath the first path
path=/users/  eg to access it you would need to be in the /users/
+ ((expires == null) ? "" : " ; expires=" + expires.toGMTString());
?: oporator
(expression) ? if-true-statement : if-false-statement;
?: oporator can be used whare an if cannot
dose (expires equal null) ?
// cookies that are set without the expires field are called session cookies.
( if true set empty string "" )
else
// set the token expires width the date
( if not null set the expires token)


text:
Q: Install4J will not launch an application if installed with Admin user We are trying to install our Eclipse RCP application with admin user permissions.
It picks up default directory of C:\Program_Files<Path given in media options> during installation.
Our requirement is to have unattended installation and user should not get a chance to pick up directory.
However as normal users do not have necessary permissions to directory C:\Program_Files<Path given in media options>, our application will not launch.
Is there anyway to configure default directory of installation to logged in user space than C:\Program_Files<...> by default?
Any help will be appreciated.

A: You can add a "Run script" action to the "Startup" node of your installer and use your own logic to set the installation directory, for example with the script
if (context.isUnattended() && Util.isWindows() && !Util.hasFullAdminRights()) {
    context.setInstallationDirectory(
        new File((String)context.getVariable("sys.localAppdataDir"), "myApp")
    );
}
return true;


text:
Q: prevent arrow from being "fatter" when longer when created with ModelBuilder.createArrow In my libgdx android app I'm creating arrows with the following code
 @Override
 public void onAxonConnected(Pos one, Pos two) {

  Model lineModel = build.createArrow(one.x, one.y, one.z, two.x, two.y, two.z, 0.15 f, 0.05 f, 5, GL20.GL_TRIANGLES, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
  ModelInstance line = new ModelInstance(lineModel);
  this.addArrowModelInstanceToRender(line);
 }

How can I prevent the longer arrows from becoming "fatter" than the shorter connection arrows?
I assume there is some multiplication going on somewhere, but I'd rather have them all rendering with the same width and arrow head size. Is that achievable with the createArrow function or do I have to roll my own model for that?

A: One solution would be to calculate the distance between the two vectors representing the start and end of the arrow, then pass that value in to the capLength and stemThickness multiplied or divided by a constant (or two).
Vector3 start = new Vector3(one.x, one.y, one.z);
Vector3 end = new  Vector3(two.x, two.y, two.z);
float distance = start.dst(end);
Model lineModel = build.createArrow(one.x, one.y, one.z, two.x, two.y, two.z, CAP_LENGTH_CONSTANT / distance, STEM_THICKNESS_CONSTANT / distance, 5, GL20.GL_TRIANGLES, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);

You may need to test numbers a bit to find the right constants