text:
Q: Splitting an array of child in columns Flutter I just started flutter, and i managed to make the 4 buttons for a quiz and in portrait they appear properly in 1 column but when i turn to landscape i want them to be slpit in 2 columns (2 buttons left 2 buttons on the right)
  var questions = <Widget>[];
      for (int i = 0; i < quizClass.getOptionsLength(); i++) {
        questions.add(
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(10.0),
              child: FlatButton(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(18.0),
                  ),
                  textColor: Colors.white,
                  color: Colors.yellow.shade500,
                  onPressed: () {
                    checkAnswer(quizClass.getQuestionOption(i));
                  },
                  child: Text(
                    quizClass.getQuestionOption(i),
                    style: TextStyle(color: Colors.white, fontSize: 20.0),
                  )),
            ),
          ),

A: One way to do that is using an OrientationBuilder

OrientationBuilder(
          builder: (context, orientation) {
          return Center(

            child: orientation == Orientation.portrait?
             Column(
              children: <Widget>[
               button1,
               button2,
               button3,
               button4,
            ]):
            Row(
             children:<Widget>[

             Column(
              children: <Widget>[
               button1,
               button2,
               ]),

             Column(
              children: <Widget>[
               button3,
               button4,
               ])
            ])
            );
           }
          )

This will change the displayed widget depending on the current orientation of the screen. Hope it works for you!

A: List<Widget> widgets = questions.map((q) => q).toList();

var column = Column(children: widgets);
var row = Row(children: widgets);

bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

return Scaffold(
   body: isProtrait ? column : row,
);


text:
Q: Mysql query to show value that matches exact values only I have a table table1 in mysql containing a column named data_id INT (11).The table contains a record having data_id = 7.But when I execute the query
SELECT * FROM table1 WHERE data_id='7Îüï´Ü' ,
it returns row having data_id=7. But I want the query to show results only when exactly '7' as the data_id value is supplied, i.e.,
SELECT * FROM table1 WHERE data_id='7'

How this can be done?

A: One way I can think of is checking the input value with an additional regex
SELECT * FROM table1
WHERE data_id = $value
AND $value regexp '^[0-9]+$'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I block the keyboard from appearing even though I need to set my webView contentEditable=true? I am using a webView to display text content, and I am trying to use javascript to highlight text that the user selects. This becomes possible when contentEditable = yes, but that also brings up the keyboard whenever the user taps on any text.
How can I have the contentEditable = yes, but not have the keyboard show up so that the text is editable?
EDIT: Here is the code I am using to do the highlighting
- (void)highlight {
     NSString *currentColor = [webView stringByEvaluatingJavaScriptFromString:@"document.queryCommandValue('backColor')"];
     if ([currentColor isEqualToString:@"rgb(255, 255, 0)"]) {
         [webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'white')"];
     } else {
         [webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'yellow')"];
     }
}

I found it on this tutorial.

A: You need to use the  WebEditingDelegate that is part of the WebKitFramwork. Then you can do:
 -(BOOL)webView:(WebView *)shouldBeginEditingInDOMRange:(DOMRange *)range: {
     return NO;
  }

This is the documentation.

A: So thanks to this post, I was able to come across a solution to this problem:
[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('target').setAttribute('contentEditable','true')"];

if ([currentColor isEqualToString:@"rgb(255, 255, 0)"]) {
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'white')"];
} else {
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.execCommand('backColor', false, 'yellow')"];
}

[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('target').setAttribute('contentEditable','false')"];

I basically turn on editing only long enough to make a highlight in the webView, and then turn it back off right after I'm done. Probably not the most elegant solution, but the keyboard doesn't ever show up, and the highlighting works like a charm.


text:
Q: Hbase command line cannot edit or delete I'm very confuse why on the Hbase command line the input command can not be deleted,
If I made a mistake I have to in another prompt rewrite the command.
I feel this is very stupid,why?! Is my configuration wrong or other reason.
Or Base realy stupid?
I'm using contos 6.1,Hbase 0.94
Thanks in advance!

A: HBase command line has history feature and it also can delete typed command before submittion

A: Move the cursor to the content you want to delete, and press the Del key.


text:
Q: javascript random color with 7digits must I found the following awesome script to create a random color with javascript.
var randColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

only problem I have with this script is that it's not garanteed that it returns a normal 7digit hex string.
sometimes it's just 6 digits long like #e1d19.
is there a way to kind of force a 7 digit hex value?
thank you for your help.
edit: this is my actual problem:
function randColor() {
    var randColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    return randColor;
}

for (var i=0; i<100; i++) {
    $("#colorpicker").append("

");
}

I'm creating little divs with a random color, when I click on them I grab their title attribute and I'm coloring the background of my body.
however currently my code ends in

so when I grab the title attribute the color I'm giving my body is a different one than the little div shows.

A: You could just pad it yourself:
function randomColor() {
  var rc = (~~(Math.random() * 0xFFFFFF)).toString(16);
  return '#' + new Array(7 - rc.length).join('0') + rc;
}

This trick:
new Array(n).join(char)

is a way to get n - 1 copies of "char" in a string. I subtracted the raw length of the value from 7 instead of 6 so that when the string is 5 characters long I get one zero, when 4 I get two, etc.
edit — of course (as mentioned in other answers) you can get pad zeros like this too:
  return '#' + "000000".slice(rc.length) + rc;

I'd have to do one of those silly jsperf things to see which is faster :-)

A: var randColor = '#'+(0xFFFFFFFF-Math.random()*0xFFFFFFFF).toString(16).substr(0, 6);

A: Here's my (low tech) attempt:
var randColor = (Math.random()*0xFFFFFF<<0).toString(16);
while( randColor.length < 6 ) {
    randColor = '0' + randColor;
}
randColor = '#' + randColor;

A: I think your best bet is to make 3 sets of 2-digit hex numbers (one for each R, G, and B). Then, simply pad-left each with a 0 to ensure they are all two digits. Maybe something like this untested code I am providing for reference :)
//I am GUESSING that this is how you get a 2-digit hex value ranging 0-255
var r = PadDigits(Math.random()*0xFF<<0).toString(16),2);
var g = PadDigits(Math.random()*0xFF<<0).toString(16),2);
var b = PadDigits(Math.random()*0xFF<<0).toString(16),2);

var randColor = '#'+r+g+b;

function PadDigits(n, totalDigits)
{
    n = n.toString();
    var pd = '';
    if (totalDigits > n.length)
    {
        for (i=0; i < (totalDigits-n.length); i++)
        {
            pd += '0';
        }
    }
    return pd + n.toString();
}

A: You want it to be six digits, not seven, but the resulting string should be seven characters long including the hash. Nitpicking, I know, but still. How about this:
var color = (Math.random() * 0xFFFFFF << 0).toString(16);
"#" + String(color + "000000").slice(0, 6);

If you want to pad in the beginning instead, this should do it:
var color = (Math.random() * 0xFFFFFF << 0).toString(16);
"#" + String("000000" + color).slice(-6);

To clarify, this will pad the whole string, not separate channels. I'm thinking that since you're not randomizing per channel, there's really only the red or blue channel you're looking to pad (probably red, i.e., the second snippet).
Your second problem is that you're calling randColor twice, giving you two different colors. You'll want to store the generated color in a variable and use the variable twice instead.
for (var i=0; i<100; i++) {
    var color = randColor();
    $("#colorpicker").append("

");
}

A: Nobody posted it and this is the shortest code i got to get a random color.
'#'+Math.random().toString(16).slice(-6)

*

*It will get a random float number 0.437920...

*Convert it to Hexadecimal, you'll get something like that 0.7c13b41830e33

*Take the 6 last character which will provide you a random color #

Easy to understand, short and efficient.


text:
Q: How Web broswer's ssl works When a user selects using the ssl of web browser, for example,
a user selects the option of using ssl in FireFox, how the Web browser sets the ssl connection? Does the browser has a public key ?

A: The browser has public keys from root certificate authorities. If a key from a website is signed by one of the root CA's in the browser, it can be verified as trustworthy automatically and ssl communication can start. Otherwise, you get prompted by the unknown/self-signed certificate dialog and decide for yourself whether to trust it or not.

A: When a user selects the option of using ssl in firefox,it allows the the browser to establish connection with ssl enabled websites.The browser has a set of root certificate authorities like verisign which are well known around the world.So when a website gives a certificate signed by these CAs then our browser automatically recognizes the identity of the website.However,if that certificate is signed by a unknown authority ,then the browser gives a pop-up of unknown certificate and it depends on the user to trust it or not.If you trust it then it gets installed in your browser and that pop up does not come up the next time you connect to that website.Similarly,some websites require client certificates in order to recognize the client.In that case,you need to install your certificate(generally provided by them to a set of users) in the browser so that those websites can identify you.You can say that it is a two communication and involves exchange of certificates from both server and client.


text:
Q: Why does /**[newline] not always insert the Javadoc template including @param and @return in Eclipse? I'm documenting code in Eclipse and have been using the /** followed by Enter a lot to insert the Javadoc template. However this does not always work for some reason, it will create the template for writing comments but it won't automatically insert the @param and @return text. If I copy the exact same method to another class it will insert the full template.
It would be a big help if anyone could tell me why it won't do this in some situations.

A: As far as I know this usually happens when Eclipse doesn't know for sure which method you want to document.
A more reliable way would be to select the method/class etc. you want to create the JavaDoc for and press ALT + SHIFT + J or right click on the method in the class outline and clicking Source -> Generate element comment.

A: It always works for me UNLESS there's a comment above the method I'm trying to add the documentation for. Here's an example of some code and an undocumented method where it wouldn't work:
public class Test {
    // Declare some fields. Bla bla bla.

    // ~ Constructors

    public Test() { // <-- If I insert /** above this line it fails to work
    }
}

My fix is usually to temporarily declare a variable that separates my method from the comments so the Eclipse recognises what I'm doing...
public class Test {
    // Declare some fields. Bla bla bla.

    // ~ Constructors
    int i;
    public Test() { // <-- If I insert /** above this line it works. Then discard the temp var.
    }
}

A: This started happening with me occasionally with the last build, Mars.  Restarting Eclipse fixes it.  It seems that I really need to restart Eclipse every day in order to avoid random problems like this.


text:
Q: Only create executable jar-with-dependencies in Maven In my pom.xml I use the maven-assembly-plugin to create an executable jar-with-dependencies when running "mvn clean install".
Now it first creates the non-executable "name-version.jar" and after that the "name-version-jar-with-dependencies.jar".
Can I configure the pom.xml somehow, so that it doesn't create the non-executable JAR file?
At the moment I use <appendAssemblyId>false</appendAssemblyId> so it just overwrites the first file...
Also I get several "... already added, skipping" messages. Can I somehow prevent them?
This is the maven-assembly-plugin definition in my pom.xml:
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-5</version>
    <configuration>
        <appendAssemblyId>false</appendAssemblyId>
        <archive>
            <manifest>
                <mainClass>my.main.class</mainClass>
            </manifest>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

A: You could try setting  to pom.  This will prevent the creation of the default jar.
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  ...
  <packaging>pom</packaging>
  ...
</project>

A: You can use this build below and compile with this command :
mvn clean compile assembly:single
<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.1.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>youMainClass</mainClass>
                        </manifest>
                    </archive>

                    <finalName>${artifactId}</finalName>
                    <appendAssemblyId>false</appendAssemblyId>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
        </plugin>
    </plugins>
</build>

A: I got it to work using the maven-jar-plugin and the single goal of maven-assembly-plugin like this
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <finalName>finalName</finalName>
                <archive>
                    <manifest>
                        <mainClass>
                            mainClass
                        </mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>

Anyway the most important thing is to tell maven not to generate the default jar using this configuration of the maven-jar-plugin
<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.0.2</version>
    <executions>
        <execution>
            <id>default-jar</id>
            <phase>none</phase>
        </execution>
    </executions>
</plugin>

A: I think I've figured out how to do this. You have to leave the jar, otherwise you'll lose the compiler and resource copying, and everything else that goes along with building a jar that you need.
My solution involves essentially tricking maven, so I guess the thing to beware of is that it's very possible that in future releases this won't work...
<build>
    <defaultGoal>install</defaultGoal>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <finalName>dumpster-diver</finalName>
                <appendAssemblyId>false</appendAssemblyId>
                <archive>
                    <manifest>
                        <mainClass>DumpsterDiver</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <finalName>${project.artifactId}</finalName>
</build>

Note that in the build configuration listed, the finalName of both the maven-assembly-plugin AND the build itself match. Also note the <appendAssemblyId>false</appendAssemblyId>. If you do this, the output filename of the build and of the assembly jar will match exactly. Maven will definitely warn you about this, but will put the jar you want in your target directory AND in your local repository.
Here is the output of 'mvn clean install' on this project, as well as jar -tvf on both the jar in the target directory and in the local repository:
$ mvn clean install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building dumpster-diver
[INFO]    task-segment: [clean, install]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory <currentDirectory>/target
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to <currentDirectory>/target/classes
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory <currentDirectory>/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] No sources to compile
[INFO] [surefire:test {execution: default-test}]
[INFO] No tests to run.
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: <currentDirectory>/target/dumpster-diver.jar
[INFO] [assembly:single {execution: default}]
[INFO] Processing DependencySet (output=)
[WARNING] Artifact: <groupId>:dumpster-diver:jar:0.1.0-SNAPSHOT references the same file as the assembly destination file. Moving it to a temporary location for inclusion.
[INFO] Building jar: <currentDirectory>/target/dumpster-diver.jar
[WARNING] Configuration options: 'appendAssemblyId' is set to false, and 'classifier' is missing.
Instead of attaching the assembly file: <currentDirectory>/target/dumpster-diver.jar, it will become the file for main project artifact.
NOTE: If multiple descriptors or descriptor-formats are provided for this project, the value of this file will be non-deterministic!
[WARNING] Replacing pre-existing project main-artifact file: <currentDirectory>/target/archive-tmp/dumpster-diver.jar
with assembly file: <currentDirectory>/target/dumpster-diver.jar
[INFO] [install:install {execution: default-install}]
[INFO] Installing <currentDirectory>/target/dumpster-diver.jar to /opt/m2repo/<groupId>/dumpster-diver/0.1.0-SNAPSHOT/dumpster-diver-0.1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4 seconds
[INFO] Finished at: Thu Aug 18 13:08:56 EDT 2011
[INFO] Final Memory: 22M/618M
[INFO] ------------------------------------------------------------------------
krohr@krohr-Latitude-E6500:<currentDirectory>
$ jar -tvf ./target/dumpster-diver.jar | grep -i "dump"
  6831 Thu Aug 18 13:08:54 EDT 2011 DumpsterDiver.class
  6831 Thu Aug 18 13:08:54 EDT 2011 DumpsterDiver.class
     0 Thu Aug 18 13:08:56 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/
  2580 Thu Aug 18 13:01:46 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/pom.xml
       126 Thu Aug 18 13:08:54 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/pom.properties
krohr@krohr-Latitude-E6500:<currentDirectory>
$ jar -tvf /opt/m2repo/<groupId>/dumpster-diver/0.1.0-SNAPSHOT/dumpster-diver-0.1.0-SNAPSHOT.jar | grep -i "dump"
  6831 Thu Aug 18 13:08:54 EDT 2011 DumpsterDiver.class
  6831 Thu Aug 18 13:08:54 EDT 2011 DumpsterDiver.class
     0 Thu Aug 18 13:08:56 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/
  2580 Thu Aug 18 13:01:46 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/pom.xml
   126 Thu Aug 18 13:08:54 EDT 2011 META-INF/maven/<groupId>/dumpster-diver/pom.properties

A: If it helps, I was able to resolve this as follows, which gets rid of all warnings and replaces the uber jar in the same location as the original output jar, more like what the spring boot uber jar plugin does without the spring boot dependencies.
Key aspects:

*

*appendAssemblyId = true

*attach = false

*antrun renames files

*plugin execution order is defined by order in POM file

<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
      <configuration>
        <appendAssemblyId>true</appendAssemblyId>
        <attach>false</attach>
        <archive>
          <manifest>
            <mainClass>foo.bar.Baz</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </execution>
  </executions>
</plugin>
<plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <executions>
    <execution>
      <id>rename-jar-with-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <target>
          <move file="${project.build.directory}/${project.build.finalName}.jar"
            tofile="${project.build.directory}/${project.build.finalName}.jar.original" />
          <move file="${project.build.directory}/${project.build.finalName}-jar-with-dependencies.jar"
            tofile="${project.build.directory}/${project.build.finalName}.jar" />
        </target>
      </configuration>
    </execution>
  </executions>
</plugin>

A: Maybe im missing something about your question but the following code makes me a single executable jar:  Is this what you are looking for?
              <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <version>2.3.1</version>
              <configuration>
                    <archive>
                          <manifest>
                              <addClasspath>true</addClasspath>
                                <mainClass>some.main.class</mainClass>
                          </manifest>
                    </archive>
                    <finalName>Proj-${project.version}</finalName>
                    <outputDirectory>target</outputDirectory>
              </configuration>
        </plugin>


text:
Q: Which version of R is compatible with the newest version of Blavaan (August 3rd, 2019)? I would like to use blavaan (version 0.3-5) for my analysis. Installing the package blavaan seems to work (i.e., no error messages), but when I try to load the library 'blavaan', I receive the following error message:

Error: package or namespace load failed for 'blavaan' in
  loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck =
  vI[[j]]):  there is no package called 'pkgbuild'

This is the error message I receive in the newest version of R (3.6.1). I checked, and it appears af if the package pkgbuild may not compatible with this version. Therefore, I tried an older version of R (3.5.3) in which blavaan was created. So then it should work, right?
But then again I receive a similar error message. This time for a package called vctrs.
For some background: I have experience with lavaan ('regular' SEM), and wanted to give blavaan a try. I know my way around lavaan and basic R, but I am not a programmer/mathematician or something like that. I think the best solution for me is to just use a version of R that others know will work, rather than having to program my way around.
This is the code I used, but I don't think that is the issue:
install.packages("blavaan", dep = TRUE)

library(blavaan)

After installing 'blavaan', I get the following message:

package 'blavaan' successfully unpacked and MD5 sums checked The
  downloaded binary packages are in [location]

However, after opening the library 'blavaan', I receive the following error:

Error: package or namespace load failed for 'blavaan' in
  loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck =
  vI[[j]]):  there is no package called 'pkgbuild' [or 'vctrs' etc.]

I have only just started using blavaan (or: trying to...), so I only have tried the newest version of blavaan (0.3-5) that was updated on August 3rd, 2019.
Has anybody since then used blavaan? And if so, which version of R did you use?


text:
Q: Using while loop for nested if statements Although I know I'm missing something, can't seem to get my head around a simple loop.
while (true){
if (n < 0)
    System.out.print("less than 0")
else if (n > 35)
    System.out.print("greater than 35")
else
    calc(n)
}

I'm trying to use a while loop to loop the code and asks for input until the user inputs a value greater than 0 and less than 35, I have tried using continue but too no avail, thanks in advanceenter image description here
I have added sc of full code, the while loop will go after requesting input at the bottom of the code

A: Well you aren't "asking for input".  Also the while loop will NEVER exit. You probably at the minimum want a break in there somewhere.

A: I think you are missing the input for the user:
Scanner in = new Scanner(System.in);
int n = 0;
while (n != 27){ /*Can be any number here instead of 27, even -1*/
n = in.nextInt();
if (n < 0)
    System.out.print("less than 0")
else if (n > 35)
    System.out.print("greater than 35")
else
    calc(n)
}

Also i would suggest you to not use while(true) becuase you will have endless loop, you can put instead a condition: while(n != 27)
So each time you enter 27 it will end the loop.

A: I am also not sure of that calc method but maybe you could use something like this?
Boolean checked = true;
While(checked) {
 if (n < 0) {
    System.out.print("less than 0");
 }
 else if (n > 35) {
    System.out.print("greater than 35")'
 }
 else {
    calc(n)
    checked = false;
 }
}

Hope it helps. Cheers

A: You are missing two things in your code.
1) Inside while loop, there is no mechanism to update the value of variable n. i.e, if outside loop, the value of n is set to say 2, the loop will keep on printing Greater than 35. So a mechanism is needed to update it's value
2) Breaking mechanism for while loop. Because the condition is while(true) and there is no break inside the loop, the loop will continue endlessly. So, a loop breaking mechanism is needed
Below is a sample code where input is taken from console using Scanner and break is used for loop breaking condition
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = 0;
    while (true) {
        n = scan.nextInt();
        if (n < 0)
            System.out.print("less than 0");
        else if (n > 35)
            System.out.print("greater than 35");
        else {
            calc(n);
            break;
        }
    }
    scan.close();
}

A: How about:
   Scanner in = new Scanner(System.in);
   int n = 0;

   while (true){
         n = in.nextInt();
         if (n < 0)
            System.out.print("less than 0");
         else if (n > 35)
            System.out.print("greater than 35");
         else{
            calc(n);
            break;
         }
     }

A:     // if using jdk 1.7 or above else close scanner in finally block.
    try (Scanner s = new Scanner(System.in)) {

        int n;
        while (true) {
            n = s.nextInt();
            if (n < 0) {
                // ask for value greater then 0
                System.out.print("Please enter a value greater then 0 ");
                // extra print statement so input will be printed on next line after message
                System.out.println();
            } else if (n > 35) {
                // ask for value less then 35
                System.out.print("Please enter a value less then 35");
                System.out.println();
            } else {
                // process input and break if correct input has received
                calc(n);
                break;
            }
        }
    }

A: you can use do while. like this:
do {
   calc(n);
} while(n < 0 || n > 35)

expect calc(n) function read user input value and put it in n variable.


text:
Q: can't insert json data into mysql database in php I have a json format data without key value pair. when i insert data my table only the 1st data is inserted(of the array). how i insert the all data into my databse table?
<?php

$mysqli = new mysqli('localhost','root','','user');
$my_json_data = file_get_contents('./jason_data.txt');
$my_data = json_decode($my_json_data,true);

foreach($my_data as $data){

    $sql = "INSERT INTO demo_table (data) VALUES ('$data');";
    $mysqli->query($sql);
}

echo "done...";

?>

my database table name is 'demo_table' and json data fromat like this
["hello-world","sample-page","privacy-policy","2-revision-v1","the-banner-title"]

which is a .txt format in the same directory of my workspace
my  table schema is like this
CREATE TABLE `demo_table` (
 `id` int(5) NOT NULL,
 `data` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

A: Seems you have not a proper primary key.
Try create in  the demo_table  a proper  primary key based  on auto increment column
based  on  your schema add  autoincrement
CREATE TABLE `demo_table` (
  `id` int(5) NOT NULL  AUTO_INCREMENT,
  `data` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

in this each row inserted  have a automatic different primary key  ..  otherwise  the first insertion create an id = 0 and the second try to do the same ..but 0 already exist


text:
Q: android, recording audio with the emulator i just new in the android world.
Basically i just want to record the users voice.
I have downloaded some samples and i have not been able to test them using the emulator.
Sine it's possible to enable "audio recording support" when creating a new Android Virtual Device, i'm just guessing what's wrong here.
questions:
is it possible to use the emulator for audio recording? how?
thanks

A: Media Recorder can be used to record video and audio. However it mentions that currently, MediaRecorder does not work on the emulator. If your samples are using this class, it seems it will not work on the emulator.
Also, it would be a good idea to post links to the samples you mentioned.


text:
Q: How to recover data when the SSD read test failed Unfortunately, the SSD device on my Notebook LENOVO ThinkPad T590 has a reading failure. When running diagnostic at the Boot Menu, the SSD read test failed (see image below). The laptop is unable to load the OS (Ubuntu) and has no response.
I was wondering if there is an option of running a light version of Linux on a USB stick and then use some software that can access the SSD drive and attempt some data recovery. Or something similar.


text:
Q: py2neo cursor appears to consume everything into memory rather than stream data I am running a query to a Neo4J server, which I expect to return >100M rows (but just a few columns) and then write the results into a CSV file. This works well for queries that return up to 10-20M rows but becomes tricky as the resultant rows go up into 10^8 numbers.
I thought, writing the results row by row (ideally buffered) should be a solution but the csv.Writer appears to only write into disk once the whole code executes (i.e. at the end of the iteration), rather than in chunks as expected. In this example below, I tried explicitly flushing the file (which did not work). I also do not get any output on stdout indicating that the iteration is not occurring as intended.
The mem usage of the process is growing rapidly however, over 12GBs last I checked. That makes me think that the cursor is trying to get all the data before starting iteration, which it should not do, unless I misunderstood something.
Any ideas?
from py2neo import Graph
import csv

cursor = g.run(query)
with open('bigfile.csv', 'w') as csvfile:
    fieldnames = cursor.keys()
    writer = csv.Writer(csvfile)

#    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#    writer.writeheader()
    i = 0
    j = 1
    for rec in cursor:
#        writer.writerow(dict(rec))
        writer.writerow(rec.values())
        i +=1
        if i == 50000:
            print(str(i*j) + '...')
            csvfile.flush()
            i = 0
            j +=1

A: Isn't the main problem the size of the query, rather than the method of writing the results to the CSV file? If you're chunking the writing process, perhaps you should chunk the querying process aswell, since the results are stored in memory while the file writing is taking place.


text:
Q: Cygwin/X and Windows Subsystem for Linux I have a functioning Cygwin installation on my Windows 10 device (a Surface 3, in case that matters), including a functioning Xorg windowing environment.  I've just begun to experiment with with the Windows Subsystem for Linux, as well.  It seems like the advice for running GUI applications from WSL is to install another X server. Usually Xming is recommended, but I haven't seen any suggestions that Cygwin shouldn't work.
However, the simple way fails:
WSL $ export DISPLAY=:0
WSL $ emacs &
Display :0 unavailable, simulating -nw

I suspected it might be a networking issue, because of
WSL $ telnet localhost 6000
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
WSL $ /sbin/ifconfig
Warning: cannot open /proc/net/dev (No such file or directory). Limited output.
WSL $ # there was no output at all, actually

... but ssh to a remote machine works fine, and apparently Xservers have stopped listening on port 6000 since the last time I debugged one.
I tried running cygwin $ xhost +localhost, only to discover that xhost isn't currently installed there. Which might be the next thing to try, or might be a wild goose chase --- xhost (or at least, a naked xhost +) was mostly discouraged the last time I debugged an X server.
Is there some fundamental flaw preventing WSL from using the Cygwin X server?
If not, how shall I proceed?

A: You need to tell Cygwin/X to listen to TCP, which it does not do by default. You do this by passing the option  -listen tcp to XLaunch. When you do this, it works really fine. I do actually prefer Cygwin/X to Xming. More details in the manual.

Find the shortcut that you're using to start Cygwin/X.  (Per-user startup shortcuts are in C:\Users\<you>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup, while system-wide startup shortcuts are in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp.  Open the "Properties" of this link, and change the target from
C:\cygwin64\bin\run.exe --quote /usr/bin/bash.exe -l -c "cd; exec /usr/bin/startxwin"

to
C:\cygwin64\bin\run.exe --quote /usr/bin/bash.exe -l -c "cd; exec /usr/bin/startxwin -- -listen tcp"

For xauth support, you should copy ~/.Xauthority from your Cygwin's home dir to your WSL's home dir.
Or if you wish to disable xauth, you can edit Cygwin's /usr/bin/startxwin, changing the appropriate line near the top to enable_xauth=0.

A: You have to start the X server with startx. If you don't have X Windows installed, run the Cygwin setup.exe and select all of the X Windows systems and a window manager.


text:
Q: Laguerre diferential equation for the radial part of the Hydrogen atom I am working on understanding the solution to the Schrödinger equation for the Hydrogen atom and I am now stuck on something concerning the Radial part of the equation.
After the change of variables $\rho = kr$ with $k^2 = - \frac{2 \mu E}{\hbar^2}$ and some work on the equations I got
$$\dfrac{d^2 u(\rho)}{d\rho^2} \rho + \left[ (2l+1) +1 - 2\rho \right] \frac{du(\rho)}{d\rho} + 2(n-l-1) u(\rho) = 0$$
I know that the solution to this equation is the Laguerre polynomial $u(\rho) = L_{n-l-1}^{2l+1}(2\rho)$. Aaccording to the equation on wikipedia the Laguerre polynomial is the solution to the following differential equation
$$ \frac{d^2 L_m^\alpha(x)}{dx^2} x + (\alpha+1-x)\frac{d L_m^\alpha(x)}{dx} + m L_m^\alpha(x) = 0 $$
I can identify that $m = n-l-1 $ and $\alpha = 2l+1$ but there is a slight difference in my equation (the factor $2$ in front of $n-l-1$ and $\rho$ that should be $2\rho$ in the first term of the equation). I am however confident that my equation is correct as it is the same as the one I found in some textbooks, and I would very much appreciate some explanation on my issue.


text:
Q: jszip image is saving but image size showing as zero byte Images are saved properly but their size comes out to be zero bytes help me out please.
Here is the code:
$(function() {
    $(document).on('click', '#submitId', function() {
        var zip = new JSZip();
        var file = $('#pan')[0].files[0];
        zip.file($('#pan')[0].files[0].name, getBase64(file), {
            base64 : true
        });
        zip.generateAsync({
            type : "blob"
        }).then(function(content) {
            var fd = new FormData();
            fd.append('file1', content);
            $.ajax({
                type : 'POST',
                url : 'URL',
                data : fd,
                processData : false,
                contentType : false
                }).done(function(data) {
                console.log(data);
            });
        });
    });
});


text:
Q: How to calculate P(X1>X2) using naive bayes? Hello I'm struggling with how to calculate P(X1≥X2) using the table and the Naïve Bayes from this question

A: Hint : Evaluate $X_1 \geq X_2$ into a new column. Consider it as a variable just like you would do with $X_1$ or $X_2$ and then calculate the resulting individual and conditional probabilities.


text:
Q: Send Form data on base of selected User in angular5 I am using common reactive form for multiple types of user data .like some users have additional data like teacher,student,guard etc . Form is selected from drop down list
I want to send just specific data object according to selected user. I have create a Model named as "user" that contains all common and diff fields . now i want to send data as below
 selectedUser:string; //form selected like teacher etc
 submit(data){
   if(selectedUser === 'Teacher'){
     let techobj =new User(data.name,data.address,data.degree);
        this.userservice.post(url,teachobj);
        }
   if(selectedUser === 'Student'){
     let stuobj =new User(data.name,data.address,data.semester);
       this.userservice.post(url,stuobj);
      }
    ..... so on
}

Model class
export class User{
    //all fields here

     constructor(name :string,address:string,semester ?:string ,degree?:string)
}

Problem
        can't overload constructor or create object with diff params like Java or C#

A: You can create an interface with mandatory and optional propertes which you require to be passed in special cases like below
export interface IUser{
  name: string;
  address: string;
  semester?: string,
  degree?: string
}

Here name,address are mandatory for each case but semester and degree can be passed based on condition.
You can use this interface in the constructor of your User class like below to set the value of the properties.
export class User{
    //all fields here
  public name: string;
  public address: string;
  public semester?: string;
  public degree?: string;

  constructor(user:IUser) {
    this.name = user.name;
    this.address = user.address;
    this.semester = user.semester;
    this.degree = user.degree;
  }

}

Finally you can create the instance of the class like the below approach -
let data2:IUser = { name: data.name, address: data.address, degree: data.degree};
let techobj = new User(data2);

OR you can do it like this
let techobj2 = new User({ name: data.name, address: data.address, degree: data.degree});

Similarly for Student you can create the instance like this -
let techobj3 = new User({ name: data.name, address: data.address, semester:data.semester });

Here is the complete code -
export interface IUser{
  name: string;
  address: string;
  semester?: string,
  degree?: string
}

 export class User{
    //all fields here
  public name: string;
  public address: string;
  public semester?: string;
  public degree?: string;

  constructor(user:IUser) {
    this.name = user.name;
    this.address = user.address;
    this.semester = user.semester;
    this.degree = user.degree;
  }

}

let data:IUser = { name: "Niladri", address: "123", degree: "GRAD" };
let techobj = new User(data);

///OR
let techobj2 = new User({ name: "Niladri", address: "123", degree: "GRAD" });

//Similary

let techobj3 = new User({ name: "Niladri", address: "123", semester:"6th" });

console.log(techobj2.degree); //GRAD
console.log(techobj3.semester); //6th

And your service call should be like this -
selectedUser:string; //form selected like teacher etc
 submit(data){
   if(selectedUser === 'Teacher'){
     let techobj =new User({ name: data.name, address: data.address, degree: data.degree});
        this.userservice.post(url,teachobj);
        }
   if(selectedUser === 'Student'){
     let stuobj =new User({ name: data.name, address: data.address, semester:data.semester });
       this.userservice.post(url,stuobj);
      }
    ..... so on
}

P.S - if you pass null in your current constructor for the undesired params then it would also work
Edit 2: Another approach is to create a base class User and inherit from that class to create Student and Teacher class, then call super() in the constructor of the child classes to pass the name,address property value to the base User class.But there will be many child classes in this case depending on the number of if conditions
working demo :
Link

A: Maybe consider creating a class User that contains all the fields that are same for the Teacher and the Student. Then you can create separate classes for Teacher and Student which will extend the class User, and contain the other fields that are unique for them, in this case degree for the teacher, and semester for the Student. Maybe this will help: Extending Classes in Typescript.


text:
Q: uploading/retrieve image to mysql database Can anybody help me? I am trying to upload image to database as LONGBLOB but when i check on the database the uploaded image have only 12 B instead of 148KiB, hence it can't display!!
I wanted to upload the image on a file and store the image path on the database but i don't know how to do it, because i want to display image on a table respective to component information/details.
<?php

include "conn.php";

if(isset($_POST['submit'])) {

  $comp_id=$_POST['comp_id'];
  $compname=$_POST['compname'];
  $image=$_POST['image'];
  $description=$_POST['description'];
  $category=$_POST['category'];
  $subcat=$_POST['subcat'];
  $tech_id=$_POST['tech_id'];

  $query = mysql_query("INSERT INTO `resourcesys`.`ecomp_t`
    (`comp_id`,`compname`,`image`,`description`,`category`,`subcat`,`tech_id`)
    VALUES ('$comp_id','$compname','$image','$description','$category','$subcat','$tech_id')")
    or die(mysql_error());

  echo "<script>alert('Your component has been added successfully !!');</script>";

}

A: Without any code posted, it's hard to debug your specific use-case.
As an alternative (and, in my opinion, better) answer to your original question, I opine that, depending on what you're trying to do with your application, storing images may not be the best idea. There's far lower overhead that is invoked when you manipulate files using the local filesystem.
There are some use-cases for what you're trying to do (such as if you needed transactional integrity, or if you're consistently using <250kB image files). There are serious pros and cons either way.
Here are some good write-ups on the debate:
Storing Images in DB - Yea or Nay?
Is it a bad practice to store large files (10 MB) in a database?
Instead, I would use a more traditional method, such as using a form to collect user input, validating for security purposes, and posting the file to the server.
Link to the PHP documentation
Link to a step-by-step walkthrough


text:
Q: Mapbox: how to set a layer's fill color with MGL_MATCH expression I'm trying to set the fill color of individual features in a Mapbox map layer using the MGL_MATCH expression, but I keep getting:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString mgl_color]: unrecognized selector sent to instance ...

func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
        let layer = mapView.style!.layer(withIdentifier: "powiaty-1") as! MGLFillStyleLayer
        let source = mapView.style!.source(withIdentifier: "composite") as! MGLVectorTileSource
        let features = source.features(sourceLayerIdentifiers: NSSet(object: "powiaty") as! Set<String>, predicate: nil);
        let query = NSMutableString(format: "MGL_MATCH(jpt_kod_je, ");
        for feature in features {
            let code = feature.attribute(forKey: "jpt_kod_je") as! String
            let color = code.prefix(2) == "06" ? UIColor.red : UIColor.white;
            query.appendFormat("%@, %@, ", code, color)
        }
        query.appendFormat("%@)", UIColor.white);
        print(query);
        layer.fillColor = NSExpression(format: "%@", query);
    }

The expected results:
Features whose 4-digit code (jpt_kod_je : String property) starts with "06" to be filled with red, all others with white.
Actual results:
Crash with the stack:
0   CoreFoundation                      0x0000000106f456fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x00000001064e9ac5 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106f63ab4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x0000000106f4a443 ___forwarding___ + 1443
    4   CoreFoundation                      0x0000000106f4c238 _CF_forwarding_prep_0 + 120
    5   Mapbox                              0x000000010575d629 _ZN24MGLStyleValueTransformerIN4mbgl5ColorEU8__strongP7UIColorS1_S4_E15toPropertyValueINS0_5style13PropertyValueIS1_EEEENSt3__19enable_ifIXntsr3std7is_sameIT_NS7_22ColorRampPropertyValueEEE5valueESC_E4typeEP12NSExpressionb + 257
    6   Mapbox                              0x000000010582845e -[MGLFillStyleLayer setFillColor:] + 123
    7   MapboxExpressions                   0x0000000105443eb3 $s17MapboxExpressions14ViewControllerC03mapC19DidFinishLoadingMapyySo06MGLMapC0CF + 4867 ...


text:
Q: Use functions or loops to create shiny UI elements I am creating a shiny app and realized I am repeating a particular UI element so I am wondering if there is a way to wrap this in a function and supply parameters to make it work in different cases. In my server file, I have
output$loss <- renderUI({
    req(input$got)
    if(input$got %in% Years) return(numericInput('got_snow', label = 'John Snow', value = NA))
    if(!input$got %in% Years) return(fluidRow(column(3)))
})

and in the ui file, I have:
splitLayout(
  cellWidths = c("30%","70%"),
  selectInput('got', label = 'Select age', choices = c('',Years) , selected = NULL),
  uiOutput("loss")
)

Since I find myself using these several times and only changing a few things in both the UI and server files, I wanted to wrap these in a function and use them as and when I please. I tried this for the server file
ui_renderer <- function(in_put, label, id){
  renderUI({
    req(input[[in_put]])
    if(input[[in_put]] %in% Years) return(numericInput(id, label = label, value = NA))
    if(!input[[in_put]] %in% Years) return(fluidRow(column(3)))
  })

}
output$p_li <- ui_renderer(input='li', "Enter age", id="c_li")

and in my ui file, I put
uiOutput('c_li')

but it's not working. Any help is greatly appreciated.

A: I was unable to test your code since there was no minimal working example. I don't know if this is a typo in your example, but your are trying to render c_li, but your output is called p_li. Not sure how wrapping a render object in a standard function works, but I have done something similar using reactive values instead.
This is a minimal example using some of your terminology. It is not a working example, but an outline of the idea to my proposed solution.
# Set up the UI ----
ui <- fluidPage(
  uiOutput("loss")
)

# Set up the server side ----
server <- function(input, output, session) {

  # Let us define reactive values for the function inputs
  func <- reactiveValues(
    value <- "got",
    label <- "select age",
    id <- "xyz"
  )

  # Set up an observer for when any of the reactive values change
  observeEvent({
    func$value
    func$label
    func$id
  }, {
    # Render a new UI any time a reactive value changes
    output[["loss"]] <- renderUI(
      if (input[[func$value]] %in% years) {
        numericInput(func$id, label = func$label, value = NA)
      } else {
        fluidRow(
          column(3)
        )
      }
    )
  })
}

# Combine into an app ----
shinyApp(ui = ui, server = server)

The general idea is to define a set of reactive values and set up an observer that will render the UI every time one or more of the reactive values change. You can assign a new value to any of the reactive values using direct assignment, e.g. current$value <- "object_two". Making that change will update the UI using Shiny's reactive pattern, which means you only need to change one value to update the UI.


text: Q: Can you get CPU usage percentage based on profiling data displayed on a FlameGraph Initial Background: I am working with eBPF for CPU profiling, using BCC,  and then dumping the output of the profiling tool to a FlameGraph. I have also tried passing a PID to trace a single process but I am having difficulties understanding how to get CPU usage in percentage based on this flamegraph. My goal is to, based on this process that I am tracing and its corresponding flamegraph, know what is the percentage of CPU I am using? e.g I trace a work intensive python script and determine that it is using 30 of CPU based on the flamegraph.


text: Q: Is Kernel of a map from free module to finitely generated graded module graded? Let $R$ be a Noetherian (or $K$-algebra for some field $K$.) Assume that $R$ is graded by some abelian group. Let $M$ be a finitely generated $R$-module. Then, we may assume $M=Rm_{1} \oplus \cdots \oplus Rm_{n}$ for some $m_{i} \in M$, hence we have a kernel of the surjective map $R^{n} \to M$. My question is that, is the kernel graded so that we can write it as $R/I_{1} \oplus \cdots \oplus R/I_{n}$? I know this holds for PID, however, I don't know whether it is true or not for UFD or any higher cases. It would be appreciated to give any example/counterexamples and the condition the above statement should be true.


text:
Q: Is there a way to retrieve all the queries in a Business unit using API call? I need to move a data extension to the shared, so I need to update all the running Automation query activities which are referencing this DE.
Instead of manually checking all the query activities, if there is a way to retrieve all the queries with an API call I'd like to try that.

A: There is a way to retrieve all queries in a BU via API, but I think there is a more efficient way to do this.
If you are looking for those that target it, you can define your filter as:
        <Filter xmlns:q1="http://exacttarget.com/wsdl/partnerAPI" xsi:type="q1:SimpleFilterPart">
           <q1:Property>DataExtensionTarget.Name</q1:Property>
           <q1:SimpleOperator>equals</q1:SimpleOperator>
           <q1:Value>{{yourDE}}</q1:Value>
        </Filter>

or if you are looking for those that use it as a reference in the query, you can define the filter as:
        <Filter xmlns:q1="http://exacttarget.com/wsdl/partnerAPI" xsi:type="q1:SimpleFilterPart">
           <q1:Property>QueryText</q1:Property>
           <q1:SimpleOperator>like</q1:SimpleOperator>
           <q1:Value>{{yourDE}}</q1:Value>
        </Filter>

or a combination of both:
        <Filter xsi:type="par:ComplexFilterPart" xmlns:par="http://exacttarget.com/wsdl/partnerAPI">
           <LeftOperand xsi:type="par:SimpleFilterPart">
              <Property>DataExtensionTarget.Name</Property>
              <SimpleOperator>equals</SimpleOperator>
              <Value>{{yourDE}}</Value>
           </LeftOperand>
           <LogicalOperator>OR</LogicalOperator>
           <RightOperand xsi:type="par:SimpleFilterPart">
              <Property>QueryText</Property>
              <SimpleOperator>like</SimpleOperator>
              <Value>{{yourDE}}</Value>
           </RightOperand>
        </Filter>

and all together it would be:
  <RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
     <RetrieveRequest>
        <ObjectType>QueryDefinition</ObjectType>
        <Properties>Name</Properties>
        <Properties>CustomerKey</Properties>
        <Properties>DataExtensionTarget.Name</Properties>
        <Properties>DataExtensionTarget.CustomerKey</Properties>
        <Properties>QueryText</Properties>
        <Properties>CategoryID</Properties>
        <Filter xsi:type="par:ComplexFilterPart" xmlns:par="http://exacttarget.com/wsdl/partnerAPI">
           <LeftOperand xsi:type="par:SimpleFilterPart">
              <Property>DataExtensionTarget.Name</Property>
              <SimpleOperator>equals</SimpleOperator>
              <Value>{{yourDE}}</Value>
           </LeftOperand>
           <LogicalOperator>OR</LogicalOperator>
           <RightOperand xsi:type="par:SimpleFilterPart">
              <Property>QueryText</Property>
              <SimpleOperator>like</SimpleOperator>
              <Value>{{yourDE}}</Value>
           </RightOperand>
        </Filter>
     </RetrieveRequest>
  </RetrieveRequestMsg>


text:
Q: multiuser in symfony using fosuserBundle I have three tables in my database: Simpleuser and Admin and StudentUser, I would like use this 3 table to connect in my symphony app , but I know that with fosuserBundle I should configurate just one table to be able to connect to the application.
I already change the first one using config.yml
here :
fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: MyApp\UserBundle\Entity\StudentUser

i'm searching  solution that let me log in my symfony application with many users , any one have an idea ?
thank you :)

A: You can use PUGXMultiuserBundle to handle multiple user classes.


text:
Q: Trouble creating/manipulating Pandas DataFrame from given list of JSON records I have json records in the file json_data. I used pd.DataFrame(json_data) to make a new table, pd_json_data, using these records.
pandas table pd_json_data
I want to manipulate pd_json_data to return a new table with primary key (url,hour), and then a column updated that contains a boolean value.
hour is based on the number of checks. For example, if number of checks contains 378 at row 0, the new table should have the numbers 1 through 378 in hour, with True in updated if the number in hour is a number in positive checks.
Any ideas for how I should approach this?

A: Updated Answer
Make fake data
df = pd.DataFrame({'number of checks': [5, 10, 300, 8],
                   'positive checks':[[1,3,10], [10,11], [9,200], [1,8,7]],
                   'url': ['a', 'b', 'c', 'd']})

Output
   number of checks positive checks url
0                 5      [1, 3, 10]   a
1                10        [10, 11]   b
2               300        [9, 200]   c
3                 8       [1, 8, 7]   d

Iterate and create new dataframes, then concatenate
dfs = []
for i, row in df.iterrows():
    hour =  np.arange(1, row['number of checks'] + 1)
    df_cur = pd.DataFrame({'hour' : hour,
                          'url': row['url'],
                          'updated': np.in1d(hour, row['positive checks'])})
    dfs.append(df_cur)
df_final = pd.concat(dfs)

    hour updated url
0       1    True   a
1       2   False   a
2       3    True   a
3       4   False   a
4       5   False   a
0       1   False   b
1       2   False   b
2       3   False   b
3       4   False   b
4       5   False   b
5       6   False   b
6       7   False   b
7       8   False   b
8       9   False   b
9      10    True   b
0       1   False   c
1       2   False   c

Old answer
Now build new dataframe
df1 = df[['url']].copy()
df1['hour'] = df['number of checks'].map(lambda x: list(range(1, x + 1)))
df1['updated'] = df.apply(lambda x: x['number of checks'] in x['positive checks'], axis=1)

Output
  url                                            hour updated
0   a                                 [1, 2, 3, 4, 5]   False
1   b                 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]    True
2   c  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...   False
3   d                        [1, 2, 3, 4, 5, 6, 7, 8]    True


text:
Q: 3-D Object Disappears When I Hit Save in Unity Why does this happen? Has anyone had this happen before? I have tried it numerous times to make sure I am not crazy and I can't find anyone who has had this problem before when I searched le internet.
This is what I am doing:
Step 1:
Put 3-D object on scene view.
Step 2:
Click Save
Edit:
Here is some more information:
Unity Version: 2019.2.21
What I did specifically:
I am following the directions listed here. One of the things that I did, that wasn't listed on the link is try to add a cube onto the scene view.
I did this by right clicking on "MixedRealityToolkit", choosing "3-D" object, and then selecting "cube".
I then hit save and my cube disappeared.

A: The MixedRealityToolkit is the MR dev toolkit itself, and providing the central configuration entry point for the entire framework.
We should not add any game object under the MixedRealityToolkit object. Therefore, the best practice is creating an empty object as a root game object, and then move all your scene contents as child to it.


text:
Q: Issue with app.EnterText for Android API 29 ONLY Xamarin.UITest I have been having an issue with Xamarin.UITest after the application that I am working on was updated to the latest android version (API 29). This issue did not happen before the application updates and automation worked as intended on API 29. Before the application was updated and you did a fresh install the application would have an "OS" prompt stating that the "Application was out of Date" once the application was updated that prompt no longer displayed however the Xamarin.UITest issues appeared.
The issue is that when automation runs on a device with API 29 ONLY and when the code app.EnterText runs the text that was requested via code to be inputted does not get input. The same applies to app.ClearText, once the command is done the text in the field does not get cleared. its as if there is a permission issue with the automation interacting with the application text fields only. Note, the test does not fail with an error and the test keeps running like it did the commend, which makes it header to know why it's doing this.
I did work with my DEV's to see if this is an application issue and his theory is that it's a permission issue but we are both not sure where the issue is of what permission is being blocked any help of shedding light would be very helpful.
Environment replication that I am seeing the issues on:
Device/OS: Pixel 3 XL (real device)/ Android version 10(API 29)
Xamarin.UITest version: 3.0.4
Application:
Rinning the latest updates for packages including Xamrin.Forms and the application is configured for API(29)
Note: the text fields work just fine outside of automation and if a user inputs the text it works as intended, just an Automation issue
VS/Xcode version:
Visual Studio Enterprise 2019 for Mac
Version 8.3.10 (build 2)
Installation UUID: 87bfc8d6-bb7e-4416-8725-c451ad424835
GTK+ 2.24.23 (Raleigh theme)
Xamarin.Mac 5.16.1.24 (d16-3 / 08809f5b)
Package version: 604000208
Mono Framework MDK
Runtime:
Mono 6.4.0.208 (2019-06/07c23f2ca43) (64-bit)
Package version: 604000208
NuGet
Version: 5.3.0.6192
.NET Core SDK
SDK: /usr/local/share/dotnet/sdk/3.0.100/Sdks
SDK Versions:
3.0.100
2.1.700
2.1.505
2.1.504
2.1.503
2.1.302
2.1.301
2.1.4
MSBuild SDKs: /Library/Frameworks/Mono.framework/Versions/6.4.0/lib/mono/msbuild/Current/bin/Sdks
.NET Core Runtime
Runtime: /usr/local/share/dotnet/dotnet
Runtime Versions:
3.0.0
2.1.13
2.1.11
2.1.9
2.1.8
2.1.7
2.1.2
2.1.1
2.0.5
Xamarin.Profiler
Version: 1.6.12.29
Location: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler
Updater
Version: 11
Apple Developer Tools
Xcode 11.2.1 (15526.1)
Build 11B500
Xamarin Designer
Version: 16.3.0.256
Hash: 8a223bfd7
Branch: remotes/origin/d16-3
Build date: 2019-11-01 21:02:02 UTC
Xamarin.Mac
Version: 6.6.0.12 (Visual Studio Enterprise)
Hash: e3c2b406d
Branch: xcode11.2
Build date: 2019-11-01 00:12:07-0400
Xamarin.iOS
Version: 13.6.0.12 (Visual Studio Enterprise)
Hash: e3c2b406d
Branch: xcode11.2
Build date: 2019-11-01 00:12:08-0400
Xamarin.Android
Version: 10.0.6.2 (Visual Studio Enterprise)
Commit: xamarin-android/d16-3/c407838
Android SDK: /Users/{*}/Library/Developer/Xamarin/android-sdk-macosx
Supported Android versions:
5.0 (API level 21)
5.1 (API level 22)
6.0 (API level 23)
7.0 (API level 24)
7.1 (API level 25)
8.0 (API level 26)
8.1 (API level 27)
SDK Tools Version: 26.1.1
SDK Platform Tools Version: 29.0.5
SDK Build Tools Version: 28.0.3
Build Information:
Mono: mono/mono/2019-06@476d72b9e32
Java.Interop: xamarin/java.interop/d16-3@5836f58
LibZipSharp: grendello/LibZipSharp/d16-3@71f4a94
LibZip: nih-at/libzip/rel-1-5-1@b95cf3fd
ProGuard: xamarin/proguard/master@905836d
SQLite: xamarin/sqlite/3.27.1@8212a2d
Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-3@cb41333
Microsoft Mobile OpenJDK
Java SDK: /Users/mmoadeb/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_1.8.0.25
1.8.0-25
Android Designer EPL code available here:
https://github.com/xamarin/AndroidDesigner.EPL
Android SDK Manager
Version: 1.4.0.65
Hash: c33b107
Branch: remotes/origin/d16-3
Build date: 2019-11-19 20:33:22 UTC
Android Device Manager
Version: 1.2.0.116
Hash: d2b2af0
Branch: remotes/origin/d16-3
Build date: 2019-11-19 20:33:42 UTC
Xamarin Inspector
Version: 1.4.3
Hash: db27525
Branch: 1.4-release
Build date: Mon, 09 Jul 2018 21:20:18 GMT
Client compatibility: 1
Build Information
Release ID: 803100002
Git revision: add3a4998a5cb5b081e0404e1fe13acfecb7801d
Build date: 2019-11-20 13:35:15+00
Build branch: release-8.3
Xamarin extensions: 79c69708816813b498283eeda7bcb4d464433a04
Operating System
Mac OS X 10.15.1
Darwin 19.0.0 Darwin Kernel Version 19.0.0
Thu Oct 17 16:17:15 PDT 2019
root:xnu-6153.41.3~29/RELEASE_X86_64 x86_64
Enabled user installed extensions
Straight8's SpecFlow Integration 1.11.3.0
XAML Styler 1.1.5
The only error that I see when debugging the test is below, I am not sure if this has any relevance:
'''
[0x7000100bc000] The instruction pointer of the currently executing method(Xamarin.UITest.Queries.AppQuery:tokensFromObjectArray (object[])) is not on the recorded stack. This is likely due to a runtime bug. The 15 frames are as follow:
[0x7000100bc000] Frame (0 / 15): (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo:InternalInvoke (System.Reflection.RuntimeMethodInfo,object,object[],System.Exception&)
[0x7000100bc000] Frame (1 / 15): System.Reflection.RuntimeMethodInfo:Invoke (object,System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo)
[0x7000100bc000] Frame (2 / 15): System.Reflection.MethodBase:Invoke (object,object[])
[0x7000100bc000] Frame (3 / 15): System.Delegate:DynamicInvokeImpl (object[])
[0x7000100bc000] Frame (4 / 15): System.MulticastDelegate:DynamicInvokeImpl (object[])
[0x7000100bc000] Frame (5 / 15): System.Delegate:DynamicInvoke (object[])
[0x7000100bc000] Frame (6 / 15): TechTalk.SpecFlow.Bindings.BindingInvoker:InvokeBinding (TechTalk.SpecFlow.Bindings.IBinding,TechTalk.SpecFlow.Infrastructure.IContextManager,object[],TechTalk.SpecFlow.Tracing.ITestTracer,System.TimeSpan&)
[0x7000100bc000] Frame (7 / 15): TechTalk.SpecFlow.Infrastructure.TestExecutionEngine:ExecuteStepMatch (TechTalk.SpecFlow.Bindings.BindingMatch,object[])
[0x7000100bc000] Frame (8 / 15): TechTalk.SpecFlow.Infrastructure.TestExecutionEngine:ExecuteStep (TechTalk.SpecFlow.Infrastructure.IContextManager,TechTalk.SpecFlow.Bindings.StepInstance)
[0x7000100bc000] Frame (9 / 15): TechTalk.SpecFlow.Infrastructure.TestExecutionEngine:Step (TechTalk.SpecFlow.Bindings.StepDefinitionKeyword,string,string,string,TechTalk.SpecFlow.Table)
[0x7000100bc000] Frame (10 / 15): TechTalk.SpecFlow.TestRunner:When (string,string,TechTalk.SpecFlow.Table,string)
[0x7000100bc000] Frame (11 / 15): TechTalk.SpecFlow.Steps:When (string,string,TechTalk.SpecFlow.Table)
[0x7000100bc000] Frame (12 / 15): TechTalk.SpecFlow.Steps:When (string)
[0x7000100bc000] Frame (13 / 15): WellRx.UITests.Steps.DashboardSteps:GivenIAmOnTheHomePage ()
[0x7000100bc000] Frame (14 / 15): (wrapper dynamic-method) object:lambda_method (System.Runtime.CompilerServices.Closure,TechTalk.SpecFlow.Infrastructure.IContextManager)
'''


text:
Q: What exactly does this jQuery selector do? I have been studying a piece of jQuery script and editing it for my needs for a few days now. It contains the following lines.
var newElement = $("#featured-post").clone();
var inputField = $("select", newElement);

I just don't understand what exactly the second line does as I haven't seen such a selector before (yes, I'm new to jQuery).
I can guess that it selects "" elements within the cloned element. But I have not read about this method of selection before. Could somebody explain a little bit about this selector? I've done some googling but didn't find anything related to this. Thanks a lot.

A: To make it simple for you, the below code:
$("select", newElement);

is same as doing:
$(newElement).find("select");

So, the selector will look for the select element inside the newElement cloned element.

A:
jQuery( selector [, context ] )
selector

*

*Type: Selector

*A string containing a selector expression

context

*

*Type: Element or jQuery

*A DOM Element, Document, or jQuery to use as context

Source: http://api.jquery.com/jQuery/#jQuery-selector-context


text:
Q: Oracle Retrieve correct records using bind variable I have the following query where it retrieves records as per the join and bind variable input
select distinct G.GAME_ID,  G.GAME_TYPE_ID, G.GAME_DATE,  CY.DISPLAY_NAME AS NAME

            FROM FOOTBALL.FY_CALENDAR_MV CL
                 JOIN FIFA_OWNR.GAME G
                    ON TO_DATE ( TO_CHAR (G.GAME_DATE, 'MM/DD/YYYY'), 'MM/DD/YYYY') = CL.CAL_DT

                 JOIN FIFA_OWNR.ICE_MANAGER IM
                    ON G.CREATED_BY = IM.USER_ID
                 JOIN FIFA_OWNR.MANAGER_HIST MH
                    ON     MH.MANAGER_ID = IM.MANAGER_ID
                 JOIN FIFA_OWNR.MV_COUNTRY_LOCATION_LKUP CY
                    ON CY.LOCATION_CODE = MH.OFFICE_LOCATION_CODE
                 and CY.DISPLAY_NAME in (:LOCAL_OFFICE)

Upon providing the value of bind variable it retrieves the records as per the bind value
Actual Output / ERROR / ISSUE
ENTER BINDS     ----    LOCAL_OFFICE    ----    Value = ASIA

GAME_ID GAME_TYPE_ID    GAME_DATE           NAME
1362    Friendly2       21-JAN-20           ASIA
1540    Friendly2       21-JAN-20           ASIA
1680    Friendly2       24-JAN-20           ASIA
1607    Competition3    25-JAN-20           ASIA

ENTER BINDS     ----    LOCAL_OFFICE    ----    Value = EUROPE

GAME_ID GAME_TYPE_ID    GAME_DATE           NAME
NO Records show up

Expected / Correct Output
ENTER BINDS     ----    LOCAL_OFFICE    ----    Value = ASIA

GAME_ID GAME_TYPE_ID    GAME_DATE           NAME
1680    Friendly2       24-JAN-20           ASIA
1607    Competition3    25-JAN-20           ASIA

ENTER BINDS     ----    LOCAL_OFFICE    ----    Value = EUROPE

GAME_ID GAME_TYPE_ID    GAME_DATE           NAME
1362    Friendly2       21-JAN-20           EUROPE
1540    Friendly2       21-JAN-20           EUROPE

I have created a sample sql fiddle
Bound variables for the fiddle
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=735a8ad9dd4ca4c9b145ca0b41ec886c
and CY.DISPLAY_NAME ='ASIA';
  and CY.DISPLAY_NAME ='EUROPE';
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=ea07dac8b7f35a5b5c3005531f7a5190
TABLE   FIFA_OWNR.GAME;
  GAME_ID,              GAME_DATE,               GAME_TYPE_ID,      CATEGORY_ID, ,COUNTRY_CODE,    CREATED_BY
  1362,         to_date('21-JAN-20','DD-MON-RR'),Friendly2,             9,         '08',          'beckham'
  1540                  21-JAN-20                Friendly2              9           08             beckham
  1680                  24-JAN-20                Friendly2              9           07             beckham
  1607                  25-JAN-20                Competition3           17          07             beckham
  1687                  25-JAN-20                Competition3           17          04             beckham

In the lookup table the location code 6 represents ASIA location code 8 EUROPE
TABLE   FIFA_OWNR.MV_COUNTRY_LOCATION_LKUP
LOCATION_CODE,      DISPLAY_NAME                    LOCATION_ABBR
1                   AMERICA                         01/02/03
4                   AFRICA                          04
5                   AUS PACIFIC                     05/06
6                   ASIA                            07
8                   EUROPE                          08

TABLE   FIFA_OWNR.MANAGER_HIST
MANAGER_ID,DEFAULT_COUNTRY_CODE,OFFICE_LOCATION_CODE
242         01                      1
238         08                      8
239         08                      8
240         06                      5
243         7B                      6

TABLE   FIFA_OWNR.ICE_MANAGER
USER_ID          MANAGER_ID
beckham             242
beckham             238
beckham             239
beckham             240
beckham             243

TABLE   FOOTBALL.FY_CALENDAR_MV;
CAL_DT      CAL_MTH             YEAR
21-JAN-20   1                   2020
21-JAN-20   1                   2020
24-JAN-20   1                   2020
25-JAN-20   1                   2020

Issue is it is unable to retrieve the records as per the bind values

A: You need to change the join in your query:
select distinct G.GAME_ID,  G.GAME_TYPE_ID, G.GAME_DATE,  CY.DISPLAY_NAME AS NAME
            FROM FY_CALENDAR_MV CL
                 JOIN GAME G
                    ON G.GAME_DATE = CL.CAL_DT
                 JOIN ICE_MANAGER IM
                    ON G.CREATED_BY = IM.USER_ID
                 JOIN MANAGER_HIST MH
                    ON     MH.MANAGER_ID = IM.MANAGER_ID
                 JOIN MV_COUNTRY_LOCATION_LKUP CY
                    ON CY.LOCATION_ABBR = G.COUNTRY_CODE -- This join is changed
                 and CY.DISPLAY_NAME ='ASIA';

see db<>fiddle for correct output for ASIA and EUROPE


text:
Q: Why do i get Tearing/Graphics lag when FPS >= 60 on Rainbow Six Game / All games? no matter on which way i achieve FPS >= 60 on Rainbow 6 (and other games), there is screen lag or tearing i do not know what it is exactly. Can anyone help?
I have tried all kind of monitors, starting from non HD, 60Hz all the way up to 144Hz.
Here are my specs:

*

*i7-2600 @ 3.40 GHz

*GTX 1060

*16 GB RAM

In game settings: doesn't matter. The only way i can play right now is with Vsync on :( But as soon as there is an FPS drop, i get 55 which is not really nice.

A: Tearing

The only way i can play right now is with Vsync on

That's because it is literally the only way to eliminate screen tearing. For more information about tearing, see: https://gaming.stackexchange.com/a/198195/46740
Obviously, when you play at over 60 FPS on a 60 Hz screen, you get tearing because your screen receives more frames than it can possibly display. As a result, you see stripes of all the different frames the screen has received, which looks like the screen has been torn.
As for why you still see tearing above 60 FPS on a 144 Hz screen, the likeliest reason is that the games you were using did not properly support screens above 60 Hz. In other words, you could only get over 60 FPS by disabling V-Sync, which is what causes tearing in the first place.
This can happen if the game engine implements V-Sync correctly, but still assumes that every screen is 60 Hz, and therefore limits its framerate to 60 FPS when V-Sync is turned on. Alternatively, the game actually lets you choose a different frame limit, but you left it at "default", which is usually 60 FPS.

Lags
When you push your GPU to its limit, framerates can vary wildly from low to high. This huge discrepancy can be perceived as a lag.
Imagine seeing a frame every 33.3 ms (30 FPS). Eventually, you get used to it, and you perceive it as (relatively) fluid. When the scene gets simpler, your GPU provides you with new frames every 16.6 ms (60 FPS), which is even more fluid. Eventually, you get used to that.
Now, when the GPU is alternating between 60 FPS and 30 FPS, you experience a fluid (60 FPS) framerate, which is occasionally interrupted by a lag (30 FPS). One way to prevent this, would be to limit your framerate to 30 FPS (aka. frame smoothing).
In your case, your GPU appears to be fast enough to output a constant 60 FPS, but struggles to keep up a constant 144 FPS. When you get used to 144 FPS, the sudden switch to 60 FPS is perceived as a lag.
The above phenomenon can get worse with V-Sync, but can be avoided with G-Sync or FreeSync (aka. Adaptive Sync). If your GPU can't provide a new frame when the screen is ready to display it, the GPU will have to wait for the next time the screen is ready. Suddenly, you need to wait much longer for the next frame, which is perceived as a lag.
G-Sync/FreeSync fix this by having the screen wait for the GPU in such circumstances. Thus, if your GPU can't provide a constant 60 FPS, but can still deliver a constant 59-60 FPS, you won't notice the lag as you would if the framerate changed between 30 and 60 FPS.


text:
Q: ancient use of stereographic projection I just started reviewing Differential Geometry extrinsically. I came across the following information:
"... .Now suppose our user is content to have a $map^1$ which makes it easy to navigate along the shortest path connecting the two paths. Ideally the user would use a straight edge, magnetic compass, and protractor to do this. S/he would draw a straight line on the map connecting p and q and steer a course which maintains a constant angle (on the map) between the course and meridians. This can be done by the method of stereographic projection. This chart is conformal (which means that it preserves angles). According to Wikipedia stereographic projection was known to the ancient Greeks and a map using stereographic projection was constructed in the early 16th century."
$^1$ By a map here is meant a chart on the sphere $S^2$ as in the theory of topological manifolds.
I did not understand if the straight line would be drawn in the image of the chart or in the ambient space where the sphere lies. Also, where would this line end up useful in the construction of the minimal geodesic?


text:
Q: Can this theorem be extended to sequences and other functions?
If $\lim_{n \to \infty} |a_n| = 0$, then $\lim_{n \to \infty} a_n = 0$

I read the proof by Squeeze Theorem, and it doesn't seem like the limit can only be $0$. I wonder if I can extend it to

If $\lim_{x \to a} |f(x)| = 0$, then $\lim_{x \to a} f(x) = 0$.

If this holds, it would also seem I can extend the idea to functions in higher dimensions, that is

If $\lim_{(x,y) \to (a,b)} |f(x,y)| = 0$, then $\lim_{(x,y) \to (a,b)} f(x,y) = 0$

A: Assuming $\lim_{n\to\infty} |a_n| = 0$, this means that given any $\varepsilon > 0$, there is an integer $N$ such that for $n \ge N$,
$$
\big| |a_n| - 0 \big| < \varepsilon \quad\Leftrightarrow\quad
\big| a_n | < \varepsilon \quad\Leftrightarrow\quad
\big| a_n - 0| < \varepsilon,
$$
which shows that $\lim_{n\to\infty} a_n = 0$. (In fact the argument shows that the two statements are equivalent.)
The same argument generalizes to the other situations you list.


text:
Q: Django - Select field not showing Options model.py
from django.db import models
from django import forms
class CharApp(forms.Form):
    VAMPIRE = 'VP'
    DRAUGR = 'DR'
    BAELNORN = 'BN'
    LICH = 'LH'
    SHADOW = 'SW'
    RACE_CHOICES = (
        ('VP', 'Vampire'),
        ('DR', 'Draugr'),
        ('BN', 'Baelnorn'),
        ('LH', 'Lich'),
        ('SW', 'Shadow'),
    )
    app_id = models.AutoField(primary_key=True)
    char_name = models.CharField(max_length=80, verbose_name='Character Name')
    race = forms.Form(forms.ChoiceField( choices = RACE_CHOICES))
    date_applied = models.DateTimeField(verbose_name='Date Applied')
    background = models.TextField(verbose_name='Background')
    account_id = models.IntegerField(default=1, verbose_name='Account ID')
    submitted = models.BooleanField(default=False)

create.html

Race:
        <select name="{{ form.race.choices }}">
            {% for choices in form.race.choices %}
                {{ form.race.choices }}
            {% endfor %}
        </select>

For some reason the select section of the html doesn't loop at all and shows no value at all or the text.

A: Why you dont use builtin django Select?
from django import forms
>>> CHOICES = (('1', 'First',), ('2', 'Second',))
>>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
>>> choice_field.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices = ()
>>> choice_field.choices = (('1', 'First and only',),)
>>> choice_field.widget.choices
[('1', 'First and only')]

https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#widgets-inheriting-from-the-select-widget
EDIT: As im looking at your code you doing something pretty weird... you can defing your Form in your models and you settings the models fields in your form? i guess you missplacing the concepts
models.py
from django.db import models

# THIS IS YOUR MODEL, WILL BE PERSISTED IN YOUR DATABASE
class Race(models.Model):
    ... # Here you will place fields related to the race, as name, date and etc...

class CharApp(models.Model):
    VAMPIRE = 'VP'
    DRAUGR = 'DR'
    BAELNORN = 'BN'
    LICH = 'LH'
    SHADOW = 'SW'
    RACE_CHOICES = (
        ('VP', 'Vampire'),
        ('DR', 'Draugr'),
        ('BN', 'Baelnorn'),
        ('LH', 'Lich'),
        ('SW', 'Shadow'),
    )

    app_id = models.AutoField(primary_key=True)
    char_name = models.CharField(max_length=80, verbose_name='Character Name')
    race = models.ForenignKey(Race, related_name="charapp_race")
    date_applied = models.DateTimeField(verbose_name='Date Applied')
    background = models.TextField(verbose_name='Background')
    account_id = models.IntegerField(default=1, verbose_name='Account ID')
    submitted = models.BooleanField(default=False)

forms.py #create this file at your app folder
from django.forms import ModelForm
from myapp.models import Article

from .models import CharApp, RACE_CHOICES

# this is your form
class CharAppForm(ModelForm):
    # Here you can change the widget or add new fields that is not related your model form
    race = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) #if you want to change the default form widget to this field

    class Meta:
        model = CharApp
        fields = ['__all__'] # This will get all fields from your form, or just place each field you want to display

Keep in mind to create your form instance at your view.py
from .models import CharApp
from .forms import CharAppForm

# The function that will render your html or give you responses from your backend to your frontend

def your_view(request):
    form = ConfigAppForm() # This will render your form with no value (so when pages render)
    if request.method == "POST:
        form = ConfigAppForm(request.POST) # This will bring the data that user have filled at your html and sended to your backend
        if form.is_valid(): # Check if the form is valid and able to save
            form.save() # will save the instance of your ConfigApp at your database

In your html you can call

{{ form.as_p}}

Some following guides to understand the concept of MVC (or MTV of django)
MVC: https://softwareengineering.stackexchange.com/questions/127624/what-is-mvc-really
MTV Django: https://docs.djangoproject.com/en/2.0/faq/general/
Django Views: https://docs.djangoproject.com/en/2.0/topics/http/views/
Django Models: https://docs.djangoproject.com/en/2.0/topics/db/models/
Django Models Forms: https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/
EDIT
If you want to make your code works without doing anything i said before just do that
VAMPIRE = 'VP'
DRAUGR = 'DR'
BAELNORN = 'BN'
LICH = 'LH'
SHADOW = 'SW'
RACE_CHOICES = (
    ('VP', 'Vampire'),
    ('DR', 'Draugr'),
    ('BN', 'Baelnorn'),
    ('LH', 'Lich'),
    ('SW', 'Shadow'),

class CharApp(forms.Form):
    ...
    race = forms.Form(forms.ChoiceField( choices = RACE_CHOICES))

A: you must declear race field in form as CharField not Form. look this
race = forms.ChoiceField(choices = RACE_CHOICES, widget=forms.Select())

then in your template print options like this
{% for key, value in form.race.choices %}
    <option value="{{ key }}">{{ value }}</option>
{% endfor %}


text:
Q: Как правильно сделать форк ещё несмерженной ветки? Есть ветка master. Я сделал её форк feature_1, реализовал фичу и поставил merge pull request в master. Пока админ рассматривает PR, я хочу добавить ещё одну фичу, но она использует в себе код из feature_1. Как правильно форкаться и мержить в такой ситуации?
Ситуацию осложняет то, что после PR feature_1, но до PR feature_2, админ может принять чей-то чужой PR в master.

A: Чтобы изменения из feature_1 были в feature_2 нужно либо создавать feature_2 напрямую от feature_1:
git checkout feautre_1
git checkout -b feature_2

либо создать ветку от master и потом слить feature_1 в feature_2:
git checkout master
git checkout -b feature_2
git merge feature_1

При создании PR есть два варианта:

*

*PR из feature_2 в feature_1

*PR из feature_2 в master
У каждого из вариантов есть плюсы и минусы описанные ниже и вам выбирать, какой лучше в вашем случае.
В первом случае более удобно делать инспекцию (code review), так как в PR видно только изменения сделанные непосредственно в feature_2, а изменения из feature_1 не показываются. Минус этого варианта в том, что после того как PR из feature_1 в master будет принят, нужно будет отредактировать PR из feature_2 изменив целевую ветку на master.
Во втором варианте есть неудобство инспекции PR пока не будет слита ветка feature_1, т.к. в feature_2 присутствуют изменения из feature_1 и пока feature_1 не слита в master эти изменения видно и в PR для feature_2. Но плюс в том, что не нужно делать дополнительных действий после принятия PR для feature_1.
Наличие других PR в master никак не влияет на процесс, разве что в них есть изменения конфликтующие с изменениями в feature_1 или feature_2. Если это случится, то о конфликтах интерфейс github сообщит и не даст принять PR. В таком случае сначала нужно залить master в feature_2 и разрешить конфликты перед тем так появится возможность принять PR.


text:
Q: Como criar um executável monolítico da aplicação .NET? Não gostaria de fazer o deploy da aplicação cheio de DLL, queria algo simples, sem instalador, queria gerar um só arquivo executável, mas o .NET é todo baseado em DLL.
Tem como gerar um executável único?

A: Executável monolítico mesmo só com o .NET Native. Ou Mono ou agora com o .NET 5 usando o runtime do Mono.
Com o .NET Core é fácil gerar um executável único, mas ainda precisará do runtime separado, pelo menos reduz para uma única DLL. E não precisa ter o .NET Framework instalado.
Mais recentemente no .NET Core pode embalar tudo em um único arquivo, ainda que não seja um único executável. Para maioria dos cenários isso já resolve o que quer.
Se for uma aplicação normal .NET Framework pode usar o ilmerge que é feito pra juntar tudo em um arquivo só.
Mas se tiver DLL não gerenciada, em C ou C++, por exemplo, aí ele não funciona. O único jeito é adicionar a DLL como recurso e fazer a separação antes da execução, pelo menos você garante que o transporte para o deploy vai ok e se o usuário acabar apagando acidentalmente você pode restaurar do executável principal. O máximo que dá para fazer é embalar tudo em um arquivo, mas serão vários arquivos internos dentro desse.
Algumas pessoas preferem fazer manualmente até mesmo DLLs gerenciadas.
Outras preferem outros utilitários mais completos. Talvez o exemplo mais popular seja o Fody Costura, que alias faz parte de um utilitário maior bem interessante. Outros:

*

*ilrepack

*mkbundle (vem com mono)

*.NETZ

*SmartAssembly (pago)


text:
Q: Stored Procedure for insert I am taking a datatable as parameter in my stored procedure and I am trying to insert a few of its column in one of the database tables but I don't know the correct syntax.
This is what I have tried
ALTER PROCEDURE [dbo].[spInsertInvoice]
    @tblInvoice [TypeExcel] READONLY
AS
BEGIN
    SET NOCOUNT ON;

    INSERT into Invoice(InvoiceNo, InvoiceDate, CustomerName,[Subject], Reference)
    VALUES (SELECT Template, Invoice_No, InvoiceDate, Cust_Name,[Subject], Reference FROM @tblInvoice)
END

Please guide me how can I correctly insert values in my table.

A: You need the form of insert that takes a select rather than a values:
insert into theTable (col1, col2, ...)
select col1, col2, ...
from ...
where...

All the features of a select are available (column aliases, grouping, joins, sub queries, ...).


text:
Q: How can insert order of an enter selection be controlled? I have an enter selection with two elements that I want to prepend to a svg container such that the order of the two elements is maintained. I have tried using insert using the :first-child selector like this
var newlayers = layer.enter();
newlayers.insert("g",":first-child")

As a result of using the :first-child selector the second element in the enter selection ends up being the first element in the svg container after insertion. How can I avoid this behavior?

A: Ok I was able to reorder the elements using .sort after the insert selection is created in this way:
var newlayers = layer.enter();
newlayers.insert("g",":first-child")
.sort(function(a,b){ return b-a; });

This leaves the ordering of the data intact while only reordering the inserted elements in DOM. I went down the route of reordering the data returned on enter() itself and that opened a whole new bunch of other problems.


text:
Q: ListView with Custom Adapter - IndexOutOfBoundsException when list is empty I have a List in which i store some strings that i get from server. I have a custom adapter for the ListView. Each item has a TextView and a Switch.
In the onCreate method, the list will be empty and after the data is received from server, i am calling notifyDataSetChanged on the adapter.
My query is specific to Switch(or a Checkbox in similar case). Please look at the code below. I will do my best to explain it using quotes.
public class DetailDOMActivity extends AppCompatActivity {

   ListView listview;
   DealofTheMonthAdapter mDealofTheMonthAdapter;
   List<String> mTitles = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_detail_dom);
      ....
      ....

      // Clearing the List before getting values from server
      mTitles.clear();

      listview = (ListView) findViewById(R.id.listView);

      // If i remove the below 2 lines,
      // and add them after getting the data from server,
      // everything works fine.

      // My query here is, when the list is empty,
      // and when getCount() in adapter returns 0,
      // why is getView() being called?
      // Is this the normal behaviour?
      mDealofTheMonthAdapter = new DealofTheMonthAdapter(this);
      listview.setAdapter(mDealofTheMonthAdapter);

      // Gets Values from server and
      // stores them in mTitles List.
      // At the end notifyDataSetChanged()
      // is called on the adapter
      getDataFromServer();
    }

   private class DealofTheMonthAdapter extends BaseAdapter {

    final Context context;

    List<Boolean> mProgress = new ArrayList<Boolean>();

    public DealofTheMonthAdapter(Context context) {
        this.context = context;
        mProgress.clear();
    }

    @Override
    public int getCount() {
        return mTitles.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_detail_dom, null);

            holder = new ViewHolder();
            holder.mTextView = (TextView) convertView.findViewById(R.id.textView);
            holder.mImageView = (ImageView) convertView.findViewById(R.id.imageView);
            holder.mSwitch = (SwitchCompat) convertView.findViewById(R.id.switch_dom);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.mTextView.setText(mTitles.get(position));
        holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked)
                    mProgress.set(position, true);
                else
                    mProgress.set(position, false);
            }
        });

        // IndexOutOfBoundsException at the below line
        holder.mSwitch.setChecked(mProgress.get(position));

        return convertView;
    }
}

public static class ViewHolder {

    TextView mTextView;
    ImageView mImageView;
    SwitchCompat mSwitch;
}

}

As far as my knowledge goes, getView() will be called depending on the count returned by getCount(). So, when the list is empty, it should return 0 and hence, getView() should not be called.
Can someone please explain me this behaviour? Let me know if you need anything else.
Logcat:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                                         at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                         at java.util.ArrayList.get(ArrayList.java:308)
                                                                         at com.xxx.xx.DetailDOMActivity$DealofTheMonthAdapter.getView(DetailDOMActivity.java:285)
                                                                         at android.widget.AbsListView.obtainView(AbsListView.java:2346)
                                                                         at android.widget.ListView.measureHeightOfChildren(ListView.java:1281)

A: the IndexOutOfBoundsException is caused by mProgress which is empty while mTitles is not. Dealing with multiple collections on ListView can be tricky, since you have always to make sure that all the collections have at least getCount()'s size. That's of course possible, but is error prone. What you can do is to wrap all the information around a Model class. E.g.
 public class MyModel {
    public String name;
    public boolean isChecked
 }

and change from List<String> mTitles to List<MyModel> mTitles. This way you can deal with only one collection, and easily retrieve and change the property of the the item at position


text:
Q: How to find text reuse with fuzzy match? I try to find, effectively, a similarity between a short phrase and a large corpus. For example, suppose my corpus is the book   Moby Dick. This book has tens of thousands of words.
In addition to that, I have a few short phrases. for example:
phrase1 = "Call me Ishmael" # This is the first sentence in the book exactly.
phrase2 = "Call me Isabel" # This is like the previous with changes of few letters from the third word.
phrase3 =  "Call me Is mael" #It's a similar sentence but one word split in two.

In addition, I have of course many other sentences that are not similar to sentences from the book.
I wonder what is the generic and effective way to identify sentences that have a sentence similar to them in the book.
What have I tried to do that seems less appropriate to me?

*

*I split all the input sentences into 3/4/5/6 n-grams.

*I split all the corpus sentences into 3/4/5/6 n-grams.

*Then I tried to find an approximate match (with FuzzySet) between all possible combinations of corpus n-grams and input n-grams (The combinations are required to grasp even cases where words have split or merged.)

It is quite clear to me that this method is very wasteful and probably also not the most accurate for my needs. I would love to understand how best to do it.

A: You can use corpus-based spell correction followed by fuzzyset. For spell correction, you can use a python implementation of symspell algorithm. Here you can find the list of repository implementing symspell. Use symspell with compounding configuration.

*

*Use a speller trained on the corpus to spell correct short sentences.

*Use fuzzyset/fuzzywuzzy to find a similarity score between spell
corrected sentence and each sentence in the corpus.

*Define a threshold by experiment, if the similarity is above the
threshold,call it a match


text:
Q: How to inherit custom javascript from parent to child pages? I have a function I wish to use in 10 different javascript files (each are used on a different webpage). I was hoping to avoid copying/pasting the function into every .js file.
The pages all have the same parent page.
Is there a way I can define this function once and call it from each page's .js file?
Thank you in advance.

A: Just define the function in its own separate JS file, and load that file alongside the page-specific files. The "WordPress way" would be to register the script containing the shared function(s) and then set it as a dependency of the other scripts:
wp_register_script( 'my-functions', get_theme_file_uri( 'js/functions.js' ) );

if ( is_page( 1 ) ) {
    wp_enqueue_script( 'my-page-1', get_theme_file_uri( 'js/page-1.js' ), [ 'my-functions' ] );
}

if ( is_page( 2 ) ) {
    wp_enqueue_script( 'my-page-2', get_theme_file_uri( 'js/page-2.js' ), [ 'my-functions' ] );
}

// etc.


text:
Q: Mapping mongodb in dropwizard? I am currently using hibernate in my project, and am using that to push data to SQL. However, that was just as a proof of concept, and in the long term, this project really needs to be running a NoSQL backend.
I've used mongoose with node, but this project is using Java & Dropwizard, is there anything available to me which will enable me to get ODM behavior with these technologies?
I have googled around, and found various github repos, but they seem the be dead project that I have found so far, I am looking for something with a community, and a bit of maturity.


text:
Q: Blender bpy: Retrieve object rotation as quaternion without modifying scene I am writing a blender exporter for my scene format.
When exporting, I need the rotation as quaternion.
The easiest way I found is to use the rotation_quaternion. But this member only guarantees to store the rotation, when the rotation_mode is set to 'QUATERNION'.
My temporary solution current looks like:
prevRotationMode = object.rotation_mode
object.rotation_mode = 'QUATERNION'
rotationAsQuaternion = object.rotation_quaternion
object.rotation_mode = prevRotationMode

This solution works, but I  am affraid this may introduce numerical errors when my exporter would be called often, as the rotation angles would be converted between quaternion representations and the original representation.
My second idea was to copy the object, and change the rotation-mode in the copy of the object and deleting it afterwards. But this still wouldn't be a clean solution, as the scene would be modified by the exporter script.
Is there an elegant way to get the rotation as quaternions without modifying the scene?

A: The mathutils module gives you some useful functions, some of which are already directly available from various properties.
rot_output = object.rotation_euler.to_quaternion()

That will allow you to get the quaternions without altering the file data.
I wouldn't be concerned about numerical errors, these use the same conversion steps that are used internally when you change rotation modes and you can change them back and forth all day without seeing any visual difference, changing the axis order of the euler rotation does make a difference though.