text:
Q: My file output is being duplicated. Every new println includes all the previous. (Code included)  Exactly what I'm doing,
    FileOutputStream out;
    PrintStream outputfile;
    try{
        out = new FileOutputStream("Project1.txt");
        outputfile = new PrintStream(out);
        int a[ ] = { 4, -3, 5, -2, -1, 2, 6, -2 };
        int maxSum;
        Formatter fmt = new Formatter();
        //Setup table column titles
        outputfile.println(fmt.format("%12s %12s %12s %12s %12s %12s%n", "Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))"));
        outputfile.println(fmt.format("%12s %12s %12s %12s %12s %12s%n%n", "_________", "_", "(ms)", "x100,000", "x10,000", "x10,000"));
        // Algorithm 1
        for( int n = 256; n <= 2049; n *= 2 ){
            int alg = 1;
            long timing;
            maxSum = maxSubSum1( a );
            timing = getTimingInfo( n, alg );
            double time = (((double)timing)/1000000.0);
            outputfile.println(fmt.format("%12s %12d %12f %12f %12f %12f%n", "Alg. 1", n, time, (time/(((long)n)*n*n))*100000.0, (time/(n*n))*10000, (time/((double)n*Math.log((double)n)))*10000));
        }
        }
        catch(Exception e)
        {
          System.err.println("Error in writing to file");
        }

Some output I am getting that I am referring to,

   Algorithm            n         time     time/n^3     time/n^2   time/(n*log(n))

   Algorithm            n         time     time/n^3     time/n^2   time/(n*log(n))
   _________            _         (ms)     x100,000      x10,000   x10,000

   Algorithm            n         time     time/n^3     time/n^2   time/(n*log(n))
   _________            _         (ms)     x100,000      x10,000   x10,000

   Alg. 1              256     4.335838     0.025844     0.661596  30.543418

A: Perhaps you are making it more complicated than it needs to be.
out.printf("%s%n", "A");
out.printf("%s%n", "B");

or
out.println("A");
out.println("B");

outputs
A
B

A: Use String.format() instead of fmt.format(). Or call Formatter's constructor with out and remove the outputfile.println() calls:
out = new FileOutputStream("Project1.txt");
Formatter fmt = new Formatter(out);
fmt.format("%12s %12s %12s %12s %12s %12s%n",
    "Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))");
fmt.format("%12s %12s %12s %12s %12s %12s%n%n",
    "_________", "_", "(ms)", "x100,000", "x10,000", "x10,000");

...
fmt.flush();
out.close();

A new Formatter() (created with noarg constructor) use an internal StringBuilder and appends every results of format() calls to it. Furthermore, every format() returns the formatter object itself (return this;). Then outputfile.println() calls the returned formatter's toString() method which returns the whole content of the internal StringBuilder. So, any subsequent calls of format() increases the StringBuilder's size and you print the whole buffer after every format() call.

A: When you construct a new Formatter, the destination of the formatted output is a StringBuilder. Therefore, every time you call outputfile.println(...), the current content of the StringBuilder is flushed to the output stream.
To fix this problem, all you need to do is this:

Formatter fmt = new Formatter(out);
fmt.format("%12s %12s %12s %12s %12s %12s%n", "Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))");

Notice that you will not need to use a PrintStream object any more.


text:
Q: How to create a mono-repo project structure with angular-cli (6.x) I'd like to use the angular-cli to generate a new workspace
The only way to do this at the moment is to run:
ng new asdf
cd asdf
ng g application whatever

but then all of the src/ files remain (and the original angular.json info for a project that is now inconsistently stored).  There's no way to create a new repo without the src folder... and when I do this using a custom schematic by essentially duplicating angular-cli's ng-new and removing https://github.com/angular/angular-cli/blob/6449a753641340d8fc19a752e1a1ced75f974efa/packages/schematics/angular/ng-new/index.ts#L61 schematic('application', applicationOptions),
Whenever I run it...
$ ng new asdf -c=my-schematic
$ cd asdf
$ ng g application whatever
    {"inlineStyle":false,"inlineTemplate":false,"routing":false,"prefix":"app","style":"css","skipTests":false,"skipPackageJson":false,"name":"whatever"}
CREATE projects/whatever-e2e/protractor.conf.js (752 bytes)
CREATE projects/whatever-e2e/src/app.e2e-spec.ts (304 bytes)
CREATE projects/whatever-e2e/src/app.po.ts (208 bytes)
CREATE projects/whatever-e2e/tsconfig.e2e.json (219 bytes)

Only the e2e files get put into projects/ and the angular.json file remains mostly empty:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {},
  "cli": {
    "defaultCollection": "my-schematic"
  }
}

I suspect this has to do with something silently failing in the application schematic or a path being off... but I wanted to check first if there was an easier / more preferred way.
$ ng --version

Angular CLI: 6.1.0-rc.0
Node: 10.1.0
OS: win32 x64
Angular: 6.0.7
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.7.0-rc.0
@angular-devkit/core         0.6.8
@angular-devkit/schematics   0.6.8
@angular/cdk                 6.3.1
@angular/cli                 6.1.0-rc.0
@angular/material            6.3.1
@schematics/angular          0.6.8
@schematics/update           0.7.0-rc.0
rxjs                         6.2.1
typescript                   2.7.2

Editing to note I'm familiar about 3rd-party libraries (e.g. Nrwl/Nx) but I'm trying to avoid those.  I also posted this issue to GitHub: https://github.com/angular/angular-cli/issues/11402

A: There currently isn't a way to do this the way I intend.
The hacky workaround is to run:
ng new <mono-repo name>
cd into it (cd <mono-repo name>)
generate the first app name (ng generate application <app-name>)
and then remove the original src / e2e folders (rm -rf src e2e) and the corresponding entry in angular.json.
From then on whenever libraries / applications are generated everything will be in the projects folder.

A: If you don't want your initial application to resides in /src, you can follow these 2 steps:
ng new my-workspace --create-application=false --defaults

*

*--create-application tells the Angular CLI not to generate an initial application.

*--defaults tells the Angular CLI not to prompt you about routing and CSS preprocessor

ng generate application my-app

With these two steps, you will end up with a file structure like this:
.
├── .git/
├── node_modules/
├── projects/
├── .editorconfig
├── .gitignore
├── README.md
├── angular.json
├── package.json
├── tsconfig.json
├── tslint.json
└── yarn.lock

And you will find your application and its corresponding e2e application in the projects folder:
projects/
├── my-app/
└── my-app-e2e/

A: I here is a guide how to do this using Nx and Angular CLI
here
The easiest is just to start with generating an empty Angular CLI project:
ng new --createApplication false

or if you use NX:
create-nx-workspace myworkspacedemo

From here you can generate apps in the app folder with:
ng g app myapp

And generate libs in the libs folder with:
ng g lib mylib

If you are using NX schematics this will also prompt you for a lot of extra configuration options such as generating lazy loaded modules, routing, use Jest etc...

A: Try ng g application {project-name} instead.
Result

And Angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "mono-repo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/mono-repo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "mono-repo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "mono-repo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "mono-repo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "mono-repo-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "mono-repo:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "project-alpha": {
      "root": "projects/project-alpha/",
      "sourceRoot": "projects/project-alpha/src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/project-alpha",
            "index": "projects/project-alpha/src/index.html",
            "main": "projects/project-alpha/src/main.ts",
            "polyfills": "projects/project-alpha/src/polyfills.ts",
            "tsConfig": "projects/project-alpha/tsconfig.app.json",
            "assets": [
              "projects/project-alpha/src/favicon.ico",
              "projects/project-alpha/src/assets"
            ],
            "styles": [
              "projects/project-alpha/src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "projects/project-alpha/src/environments/environment.ts",
                  "with": "projects/project-alpha/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "project-alpha:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "project-alpha:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "project-alpha:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/project-alpha/src/test.ts",
            "polyfills": "projects/project-alpha/src/polyfills.ts",
            "tsConfig": "projects/project-alpha/tsconfig.spec.json",
            "karmaConfig": "projects/project-alpha/karma.conf.js",
            "styles": [
              "projects/project-alpha/src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "projects/project-alpha/src/favicon.ico",
              "projects/project-alpha/src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/project-alpha/tsconfig.app.json",
              "projects/project-alpha/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "project-alpha-e2e": {
      "root": "projects/project-alpha-e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "projects/project-alpha-e2e/protractor.conf.js",
            "devServerTarget": "project-alpha:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "project-alpha:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "projects/project-alpha-e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "mono-repo"
}

A: Okay it's too easy to create a monorepo architecture
let's see

By doing this you specified an architecture without consisting any
  application.    this gives you code like this...

OOoh it seems you have created your architecture
  now come into your code editor and now create your application

Now time to check if everything works well or not.
  let's run with any random port where you want...

you can have multiple application in single architecture and they all would going to use the same node modules
  so in future once you update your any module, all your applications would be accessing the updated one    so no need to update them one by one

apart from you can run all your applications on different different ports and create the build as separately

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do append my API results into an unordered list? Ok so I am trying to get this Function:
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=starcraft&limit=30&&type=top&callback=?", function (data) {
  var temp = "";

  $.each(data.streams, function (index, item) {
      temp = temp + "
" + item.channel.display_name + "
";

    });
  $("#list ul ").html(temp);
});

to populate in a list inside the unorderd list here:

SC2

Thank you for your time!

A: The proper syntax for an unordered list is

. Each element of your list will be wrapped in its own
.
What you are probably looking for is
var myList = $("#list ul");
$.each(data.streams, function (index, item) {
  var temp = $("
" + item.channel.display_name + "
");

  myList.add(temp);
});

The result you are looking for is

SC2


text:
Q: Spectrum of the operator $A(f,g)=(g,\Delta f-f)$ Let $\Omega$ be an open set in $\mathbb{R^n}$. We consider the product Hilbert space $H=H^1_0(\Omega)\times L^2(\Omega)$ with the norm
$$|(f,g)|^2=\int_\Omega (|\nabla f|^2+|f|^2+|g|^2 ) dx$$
We consider the operator $A:D(A)\to H$ defined  by
$$A\begin{pmatrix}
       f  \\
        g
       \end{pmatrix} =\begin{pmatrix}
       0 & I \\
        \Delta-I & 0
       \end{pmatrix}\begin{pmatrix}
       f  \\
        g
       \end{pmatrix}=\begin{pmatrix}
       g  \\
        \Delta f-f
       \end{pmatrix}$$
with domain
$$D(A)=\left\{ \begin{pmatrix}
       f  \\
        g
       \end{pmatrix}\in H, \ \ \ \Delta f\in L^2(\Omega) \ \ and \ \ \ g\in H^1_0(\Omega) \right\}$$
How can we find the spectrum of this operator in the case $\Omega$ is bounded and in the case $\Omega=\mathbb{R^n}$. If I am not wrong, we can see that $A$ is a skew adjoint operator.

A: Because nobody is answering, I thought I'd offer a start. Your equation for the resolvent of $A$ is
$$
              (\lambda I -A)\left(\begin{array}{c}f \\ g\end{array}\right)=
              \left(\begin{array}{cc}\lambda & -I \\
                                      I-\Delta & \lambda\end{array}\right)
              \left(\begin{array}{c}f \\ g\end{array}\right)
                            =\left(\begin{array}{c}h \\ k\end{array}\right).
$$
Equivalently,
$$
\begin{align}
   \lambda f - g = h  & \implies g=\lambda f - h\\
   (I-\Delta)f +\lambda g = k & \implies (I-\Delta)f+\lambda^{2}f=k+\lambda h
\end{align}
$$
Given $h$, $k$, this amounts to solving for $f$ such that
$$
            -\Delta f+(1+\lambda^{2})f = k+\lambda h,
$$
and then setting $g=\lambda f-h$. All of this comes down to knowing when
$-1-\lambda^{2}\in\sigma(-\Delta)$. So it seems that
$$
               \sigma(A) = \pm i\sqrt{\sigma(-\Delta)+1}.
$$
I'm being a little sloppy about the details.


text:
Q: App crashes if "play" button is not clicked Ok I'm making a simple quiz trivia app in which user listens to the audio and guess the song. The problem I'm facing is that if the user clicks the "next" button without listing to the audio the app crashes which it shouldn't. and if the user listen to the audio and press pause and then click the "next" button it again crashes. It works well only when the user is listening to the audio select the option and click "next" without clicking the pause button.
Here is the code
 private void setQuestionView()
{
    imagebutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(mp==null) {
                mp = MediaPlayer.create(Lylevel3.this, R.raw.q11);
                mp.start();
                imagebutton.setImageResource(R.drawable.pause);
            }
            else{
                mp.pause();
                mp = null;
                imagebutton.setImageResource(R.drawable.play);
            }
        }
    });

    if (qid == 1) {
        imagebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mp==null) {
                    mp = MediaPlayer.create(Lylevel3.this, R.raw.q12);
                    mp.start();
                    imagebutton.setImageResource(R.drawable.pause);
                }
                else{
                    mp.pause();
                    mp = null;
                    imagebutton.setImageResource(R.drawable.play);
                }

            }
        });
    }

There are 10 levels and each level has 5 questions.
Next button code
    setQuestionView();

    butNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.stop();
            mp = null;
            imagebutton.setImageResource(R.drawable.play);
            RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
            Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());

            if(answer.getText().equals(currentQ.getANSWER()))
            {
                score++;
                Log.d("score", "Your score" + score);
            }

            if(qid<5){
                currentQ=quesList.get(qid);
                setQuestionView();
            }else{
                Intent intent = new Intent(Lylevel3.this,                       ResultActivity.class);
                Bundle b = new Bundle();
                b.putInt("score", score); //Your score
                intent.putExtras(b); //Put your score to your next Intent
                startActivity(intent);
                finish();
            }
        }

A: Don't put below code inside a method/function
v1.setOnClickListener(new View.OnClickList)
{ ........
}

A: When the audio is paused mp will be null. So when you click on next button
mp.stop(); // this code will gives exception
so check before stopping, whether the instance is null or not:
if(mp != null)  {
mp.stop(); // and rest of your code
}


text:
Q: Prevent gradient overlay from scrolling I am trying to put a small gradient on the bottom of a scrolling div.  I've based my solution on the accepted answer to this SO thread.  The gradient shows up fine, but when I scroll the content in the div, the bottom of the gradient moves.  I need it to remain in place so that the content scrolls independently of the gradient.  I've tried several combinations of position: fixed, position: relative, and position: relatve to no avail.  What have I missed?
Relevant markup:

B123456789

FINAL

41975 LOUDOUN CENTER PL SE, LEESBURG, VA 20175

Relevant CSS:
.resultListContainer {
    border: 1px solid #000;
    height: 400px;
    width: 40em;
    overflow-y: scroll;
    font-size: 1em;
    position: relative;
}

.resultListContainer::before {
    background-image: linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -moz-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -ms-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -o-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -webkit-linear-gradient( top, rgba( 255, 255, 255, 0 ) 95%, rgba( 255, 255, 255, 1 ) 100% );
    content: "\00a0";
    height: 100%;
    position: absolute;
    width: 100%;
}

.result {
    margin-bottom: 0;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 5px;
    list-style-type: none;
}

The result:

A: Because your element is positioned absolute, it's position is absolute to the parent element so when you scroll it scrolls with your content. What you want is your ul to scroll. I have quickly rewritten yours, but below I've got a simplified and cleaned up version:

.resultListContainer {
    border: 1px solid #000;
    height: 400px;
    width: 40em;
    font-size: 1em;
    position: relative;
}

.resultListContainer::before {
    background-image: linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -moz-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -ms-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -o-linear-gradient( top, rgba( 255, 255, 255, 0 ) 0%, rgba( 255, 255, 255, 1 ) 100% );
    background-image: -webkit-linear-gradient( top, rgba( 255, 255, 255, 0 ) 95%, rgba( 255, 255, 255, 1 ) 100% );
    content: "\00a0";
    height: 100%;
    position: absolute;
    width: 100%;
  z-index: 2;
  pointer-events: none;
}

.result {
  position: absolute;
  left: 0;
  top: 0;
  margin: 0;
  box-sizing: border-box;
  z-index: 1;
    width: 100%;
    height: 100%;
    margin-bottom: 0;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 5px;
    list-style-type: none;
    overflow-y: scroll;
}

.result li {
  height: 100px;
  background: red;
}

B123456789

FINAL

41975 LOUDOUN CENTER PL SE, LEESBURG, VA 20175

B123456789

FINAL

41975 LOUDOUN CENTER PL SE, LEESBURG, VA 20175

B123456789

FINAL

41975 LOUDOUN CENTER PL SE, LEESBURG, VA 20175

Basically there are two things that are important: your outer box cannot be scrollable, you inner box can. All the fixed elements need to be outside your inner box (which is your ul in this case). Secondly, your :before cannot be 100% high, as it will absorb your mouse events, preventing scrolling. For all browsers except IE you can solve this by using pointer-events: none, but otherwise the safest way is to make your gradient a fixed height and your :before element the height of the gradient you want, resulting in a (in this case) 20px area that would not take your mouse events at the bottom.

html, body { height: 100%; } body { padding: 0; margin: 0; }
div {
  width: 400px;
  height: 400px;
  max-height: 100%;
  position: relative;
}

div:before, div ul {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
}

div:before {
  background: linear-gradient(0deg, rgba(255,255,255,1), rgba(255,255,255,0));
  background-size: 100% 100%;
  height: 20px;
  z-index: 2;
  /* IE does not support pointer events, so making this small in height is important
  as your scroll events will not be passed to the ul if it is covered by your :before */
  pointer-events: none;
  content: '';
  display: block;
}

div ul {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow-y: scroll;
  z-index: 1;
}

div li {
  width: 100%;
  height: 100px;
  background: #ececec;
}

div li:nth-child(2n){
  background: #cecece;
}

1

2

3

4

5

6

7

A: You need to wrap your container in another div that is positioned as relative.
Also, overlay will block your scroll bar, so instead of width: 100% I used: left:0; right: 16px; - now scroll is clickable.
Try my fiddle:
https://fiddle.jshell.net/8c6k4k6d/1/

A: replace
.resultListContainer::before

with
.resultListContainer .result:last-of-type::before


text:
Q: Archive old data in mongoengine I have a huge MongoDB database powered by mongoengine where the objects have a date. To make work easier, I want to archive old objects but keep them somewhere.
I've been reading the documentation and came across switch_db and switch_collection. However, I can't make either work.
For both cases, the documentation references two usage scenarios.

*

*As a QuerySet operation:
user = User.objects.get(id=user_id)
user.switch_collection('old-users')
user.save()

The problem with this is it only works for an individual object. It is not possible to batch archive multiple documents.

*As a context_manager:
with switch_collection(Group, 'group1') as Group:
Group(name="hello testdb!").save()  # Saves in group1 collection

Using this I can't even make the query, getting the following error:
ValidationError (Document:None) (Field is required...

I've tried searching for a way to archive data with mongoengine, but none of the options seem to work. Do you have a suggestion?

A: If you have access to the MongoDB instance itself, why not just run a query directly against that, instead of jumping thru the hoops of MongoEngine?
you can rename your current users collection to users-old using this command:
http://docs.mongodb.org/manual/reference/command/renameCollection/
and then run a simple script to copy the newer values over to a new users collection


text:
Q: Handle multiple child component in React I've tried to look everywhere and couldn't find anything related to my use case, probably I'm looking for the wrong terms.
I have a situation where I have a bar with 3 icons, I'm looking for set one icon "active" by changing the class of it.
The icon is a custom component which have the following code
export default class Icon extends Component {

    state =  {
        selected : false,
    }

    setSelected = () => {
        this.setState({
            selected : true
        })
    }

    setUnselected = () => {
        this.setState({
            selected : false
        })
    }

    render() {
        var classStatus = '';
        if(this.state.selected)
            classStatus = "selected-icon"
        else
            classStatus = "icon"
        return
<FontAwesomeIcon icon={this.props.icon} />

    }
}

In my parent component I have the following code
export default class MainPage extends Component {

    handleClick(element) {
        console.log(element);
        alert("Hello!");
    }

    render() {
        return (

                    File
                    Modifica
                    Selezione

                            <Icon icon={faFileCode} onClick={() => this.handleClick(this)} />
                            <Icon icon={faCodeBranch} onClick={() => this.handleClick(this)} />
                            <Icon icon={faMagnifyingGlass} onClick={() => this.handleClick(this)} />

                    Files

                    Footer

        );
    }
}

What I'm trying to achieve is that when one of the Icon child component get clicked it will set the selected state to true manage by the parent component, in the same time while one of them is true I would like that the parent would set to false the other twos.
I've tried to use the useRef function but it doesn't look as a best practise.
Which is the correct way to do it? Sending also this to the handleClick function it just return the MainPage class instead of the child. Any suggestion at least where I should watch?
Thanks in advance

A: I suggest not storing the state in the icon, since it doesn't know what else you're using it for. Simply have the icon component take it's 'selected' status from props. e.g.
export default class Icon extends Component {
  render() {
    var classStatus = '';
    if(this.props.selected)
      classStatus = "selected-icon"
    else
      classStatus = "icon"

     return (

.
        <FontAwesomeIcon icon={this.props.icon} />

     );
    }
};

Then you can just manage the state in the parent where it should be:
export default class MainPage extends Component {
  constructor(props) {
    super(props);
    this.state = { selectedOption : '' };
  }

  handleSelectOption(newValue) {
    this.setState({ selectedOption: newValue });
  }

  isSelected(value) {
    return value === this.state.selectedOption;
  }

  render() {
    return (

      { /* etc... */ }

            <Icon
               icon={faFileCode}
               onClick={() => this.handleSelectOption("File")}
               selected={isSelected("File")}
            />
            <Icon
               icon={faCodeBranch}
               onClick={() => this.handleSelectOption("Modifica")}
               selected={isSelected("Modifica")}
            />
            { /* etc... */ }

      { /* etc... */ }

    );
  }
};

A: You should define a constructor in your class component:
        constructor(props) {
          super(props);
          this.state = { selected : false };

        }

You also have to call a function which modify the state when you click on the Icon. onClick={this.props.onClick} doesn't change the state


text:
Q: How can I display negative error bars in a logarithmic plot using pgfplots? I have error bars representing 95% confidence intervals in a logarithmic plot. Some of the error bars extend to negative numbers for which the logarithm is undefined, so pgfplots simply drops the bar completely. Is there a way to make it plot e.g. a dashed line that extends all the way down to the axis instead?
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{semilogyaxis}
\addplot [error bars/.cd, y dir=both, y explicit] coordinates {
    (1, 10) +- (0, 1)
    (2, 10) +- (0, 10)
    (3, 10) +- (0, 1)
};
\end{semilogyaxis}
\end{tikzpicture}
\end{document}

A: Unfortunately pgfplots drops the out-of-range coordinates automatically before it calls the drawing scheme (/pgfplots/error bars/draw error bar/). There is (almost) no chance that pgfplots will reconsider drawing that part of errorbar.
Nevertheless, you can still emphasise the errorbar by making a second plot with an exaggerated mark. Consider the following:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}

\begin{document}

\begin{tikzpicture}
\begin{semilogyaxis}
\addplot [error bars/.cd, y dir=both, y explicit] coordinates {
    (1, 9) +- (0, 1)   % good point
    (2, 11) += (0, 10) % bad point
    (3, 10) +- (0, 1)  % good poiny
    (4, 12) -= (0,3)   % bad point
};
\addplot [only marks,mark=.,error bars/.cd, y dir=both, y explicit relative,error mark=triangle*, error mark options={rotate=-90,scale=4}] coordinates {
    % good point has nothing to do
    (2, 11) -= (0,.5) % bad point
    % good point has nothing to do
    (4, 12) += (0,.5) % bad point
};
\end{semilogyaxis}
\end{tikzpicture}
\end{document}


text:
Q: Identify and extract number from text files I am trying to extract data from a text file. The data in the file is somewhat random and has a numbers followed by a code.
(Example 1.25CROW, 4.25CRD, 10.25CR) I only want to extract the number associated with the #.##CR index. So if find 4.25CR
I need to parse only the 4.25 and add the totals of all these numbers. I have been able to identify the lines that contain the
###.##CR as shown below. What I am now trying to do is parse the number associated with CR and put each occurrence in a list
to add together, identify, etc. I have looked string.operands and re.match but I can't come up with a solution. Help would be most
 appreciated.
open("some.txt").read()
#txt ='CR'

count = 0
for line in open("some.txt"):

    if 'CRD' in line:
        pass
    elif 'CROW' in line:
        pass
    elif 'CR' in line:
        print line
        count = count + 1
        print
print "Total # Count "
print count

A: You could convert those to numbers by doing something like
float( line.replace( 'CR', '' ) )

A: Try this:
with open("some.txt") as f:
    for line in f:
        # break line to words
        for word in line.strip().split()
            if word.endswith("CR"):
                try:
                    print "word %s-> %f" % (word, float(word[:-2]))
                except:
                    print "word %s has no number" % word

A: Yep you are on the write track. You need to modify your last elif block as
elif 'CR' in line:
    print line
    count = count + 1
    value = float(line.split('CR')[0])
    listOfCRs.append(value)

Have a list before the if clause defined as
listOfCRs = []

Finally print the sum outside the loop as in
print sum(listOfCRs)

Few points

*

*Use with open('some.txt') as f: to open the file as it will explicitly close your file.


text:
Q: advanced filter for omitting parameters value I want to omit value of selected parameters in analytics reports.
For example in urls there is domain/param1=1234 and I want to see in reports domain/param1.
I can achieve this goal by using advanced filter but I don't have idea about regexp which should be used.


text:
Q: Serving python CGI script with Apache2 I'm trying to call a Python script from a webpage, and apache2 is not actioning the script.  The files are:
test.py
#!/usr/bin/env python
print "Content-type: text/html\n\n"
print "
Hello World
"

index.html
<form action="./test.py" method="POST">
    <input type="text" size="70" name="data" value="">

    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
</form>

I've enabled a2enmod cgi and edited apache settings as follows:
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
...
<directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
    AddHandler cgi-script .py
    Require all granted
</directory>
</VirtualHost>

Webpage files ownerships are:
# ls -lh /var/www/html/
total 16K
-rw-r--r-- 1 root root  342 May 30 13:34 index.html
-rwxr-xr-x 1 root root   88 May 30 14:11 test.py

Running apachectl -M brings up a list with line cgid_module (shared).
When I bring up the page I can see the form, but when I click 'Submit' the browser either prompts to download test.py (FF) or views it (Chrome).  Any idea what I'm getting wrong here?

A: As discussed in the comments. This directory configuration looks like a plain copy from an example, and your Web root is probably somewhere else.
<VirtualHost *:80>
    <directory "/var/www/htdocs">
        AllowOverride None Options
        +ExecCGI -MultiViews
        +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
        AddHandler cgi-script .py
        Require all granted
    </directory>
</VirtualHost>

For instance where directory is changed. That's the default path usually, if yours is /var/www/html change accordingly.
I've gotten shit for this earlier but this question might also be better off on serverfault considering this is strictly related to how apache should be configured.


text:
Q: LINQ Method Syntax to INCLUDE 4 Levels Deep I have been searching without success (or not knowing how to search for this properly) so I come to you.
Check out these test classes:
public class A {
    int Id;
    ICollection<B> Bs;
}
public class B {
    int Id;
    int AId;
    ICollection<C> Cs;
}
public class C {
    int Id;
    int BId;
    ICollection<D> D;
}
public class D {
    int Id;
    int CId;
    bool Show;
}

What I'm trying to do is use eager loading to get all these classes in 1 call (making sure the DB only gets called once).
Below is the actual TSQL I want to convert to LINQ Method syntax (I think that the correct lingo) and not LINQ Query syntax.
SELECT *
FROM A
LEFT JOIN B ON B.AId = A.Id
LEFT JOIN C ON C.BId = B.Id
LEFT JOIN D ON D.CId = C.Id
WHERE A.Id = 1

Here's what I've gotten so far
var x = db.A
        .Include(a => a.B)
        .Include(a => a.Bs.Select(b => b.C)
        // How do I get D?
        .FirstOrDefault(a => a.Id == 1);

While I don't think it's important, I'd like to point out, just in case, that in the end, I need to do some things to A, and at a later point, I will need to get all the D's that have Show == true.

A: Your sample model is a little inconsistent, you use different names for your model classes and your LINQ query e.g. B vs Bs. That aside, I believe you can achieve what you want by nesting another Select() in your inner query.
e.g.
var x = db.A
    .Include(a => a.Bs.Select(b => b.Cs.Select(c => c.Ds))
    .FirstOrDefault(a => a.Id == 1);


text:
Q: What does label function do in R? I am doing clustering in r.
There is a question in my exercise: Randomly assign a cluster label to each observation
I have made a combined matrix for x1 and x2. In the solution the next thing given is the code below.
labels = sample(2, nrow(x), replace = T)
labels

What is this line doing?


text:
Q: django about ajaxSend... where exactly to i put it? where do i put the ajaxSend code i found here:
https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax
I mean, i have a base htm file that has a  section, which looks a bit like this:
<script>
    $(function() {
        $("#loginThing").click(function(){
            ... and then i define buttons to be pressed etc etc
    });
</script>

so what? do i put the code above the ${function(){}); call (but in the script tags)? do i put it in the function call? do i have to change it - the way it is called, perhaps - in any way shape or form?
i stuck it above the $(function()) call (but in the script tag), but its not like my ajax calls are behaving any differently. In fact, i don't have the foggiest notion how to test if this is doing anything. I'm not using any test code (i know, terrible. but this is a learning progress. also, i don't like test code). Is there some way i can "manually" test this? Like, using nothing but firefox?

A:
where do i put the ajaxSend code

It just needs to be outside of your present function definition.
<script>
    $(function() {
        $("#loginThing").click(function(){
            // ... and then i define buttons to be pressed etc etc
    });

    $(document).ajaxSend(function(event, xhr, settings) {
        // ... Rest of function goes here
    });
</script>

Is there some way i can "manually" test this? Like, using nothing but firefox?

I can't tell you how to test it in Firefox as I don't use it. However, Chrome has a built in interface that's great for this.
Open your page in Chrome and hit Command-Option-I (on a mac, Windows is likely similar). Go to the Network tab. In the left most column you should see the url of your POST request. Click on it. It will give you all the details you'll need to explore, Cookies (look for csrftoken to make sure Django's csrf cookie is present in the page), request and response headers, etc.

its not like my ajax calls are behaving any differently. In fact, i don't have the foggiest notion how to test if this is doing anything.

They should be, you just can't "see" it. Use the Chrome tools as explained above to view the communications with the server. To confirm that it "is doing anything":

*

*Remove the javascript code you just added from the Django site

*Perform an AJAX POST to a csrf protected form

*Note that the POST fails


text:
Q: Debugging WordPress Looking for advice on debugging sql queries. I find that plugins and themes are causing heavy queries and slowing performance. Any easy ways for doing this? Tools? Shortcuts?
Thanks!
Daniel

A: The basic technique of logging queries is that if SAVEQUERIES constant is defined to be true (it's not by default for performance reasons) then $wpdb->queries will keep the log of queries performed.
There isn't anything on top of this that WordPress natively does. There are plenty of plugins around which work either by interpreting this data, or implementing additional data collection. Latter can get pretty intricate to implement and only done in more elaborate debug plugins.


text:
Q: LibGDX Android create internal files on installation I need several files to be in the internal directory of my Android app on installation.
I could theoretically just copy them from the assets folder but that is not really convenient.
The files would be to store settings and progression.
How could I create these files?

A: As mentioned in the comments, during installation, the device does nothing but simply copy the app itself. If you want to do anything else, that's the job of your application.
Use local storage for this purpose (will be deleted on uninstall, on the desktop target, this is the same as internal.)
You could either:

*

*check whether the files exist, and copy them if they do not

This is the more reliable choice, as in the (rare?) case that the files are deleted, they will be replaced.
@Override
public void create() {
    ...
    for (String file : filesToCopy) {
        final FileHandle handle = Gdx.files.local(file);
        if (!handle.exists()) {
            // copy to handle
        }
    }
}

*store whether or not the app has already been launched at least once, and if the key does not exist, copy the files

You can use Preferences for this:
@Override
public void create() {
    ...
    final Preferences prefs = Gdx.app.getPreferences("prefs");
    if (prefs.getBoolean("newInstall", false)) {
        for (String file : filesToCopy) {
            final FileHandle handle = Gdx.files.local(file);
            // copy to handle
        }
    }
    prefs.putBoolean("newInstall", true);
    prefs.flush();
}


text:
Q: jquery selector for container and all child elements except specified I have a webform that consists of a search box and a table that is populated from the search. What I have happening is if you click anywhere on the table, your focus goes back to the search box to allow for rapid interaction.
I want to prevent this behavior on a few elements like the selects contained in the table. I would like to do so by adding a class so I can later change what ignores the focus change.
I think the issue is that my selector is looking for an element with the boxx class and without the noboxx class, but the child elements don't have the boxx class themselves but I can't seem to construct the selector I need.

$('.boxx > *:not(.noboxx)').on('click', function (e) {
    $('#searchtext').focus().select();
});

    <input type='text' id='searchtext' />

        Important text
        <button type="button">clicker</button>

          <select class='noboxx'><option>1</option><option>2</option></select>

A: It has to do with event propagation I believe.
Try this instead. It appears to me that this does what you are looking for.

$('#theOuter').on('click', '.boxx .noboxx', function (e) {
    e.stopPropagation();
});
$('#theOuter').on('click', '.boxx *:not(.noboxx)', function (e) {
    e.stopPropagation();
    $('#searchtext').focus().select();
});

        <input type='text' id='searchtext' />

                Important text
                <button type="button">clicker</button>

                    <select class='noboxx'>
                        <option>1</option>
                        <option>2</option>
                    </select>

                    stuff

                    more stuff


text:
Q: Display the next row of a List in a JTable I will try to explain as thorough as possible what I am trying to do, since I am very new at UIs.
I have a String List, let's call it user_decide, which contains different number of elements.
For example
1st Row [192, 495, 393, 399]
2nd Row [384, 493, 945, 559, 485]

These number represent the index of some arrays, for example
Name[192] = "John", Name[495] = "Mary"
Surname[192] = "Pap", Surname[495] = "Black"

I am trying to make a UI which will have a previous and a next button, as well as a JTable.
The first time, my UI will show
1st Column 2nd Column 3rd Column 4th Column 5th Column
Name       John       Mary       etc..
Surname    Pap        Black

and when I press Next, it will display the next line:
1st Column 2nd Column    3rd Column    4th Column    5th Column 6th Column
Name       Name[384]     Name[493]     Name[945]     etc...
Surname    Surname[384]  Surname[493]  Surname[945]

What I have done so far, is a frame with lots of JTables.
JPanel panel = new JPanel();
int cols = 0;
Iterator<String> iterator = user_decide.iterator();
while (iterator.hasNext())
    {
        String con = iterator.next();
        con = con.replaceAll("\\s", "").replaceAll("\\[", "").replaceAll("\\]", "");
        String conv [] = con.split("\\,");
        // It can be used for the "for-statement"
        cols = conv.length;

        List<String> column = new ArrayList<String>();
        // Giving the name of the columns
        for(int i = 0; i < cols + 1; i ++)
        {
            if (i == 0) column.add("");
            else column.add("Column #" + i);
        }
        // Setting the jtable with a specific number of columns
        String[] column_names = column.toArray(new String[column.size()]);
        tableModel = new DefaultTableModel( 17, cols);
        tableModel.setColumnIdentifiers(column_names);
            JTable table = new JTable(tableModel);
            // HERE I AM GOING TO PLACE MY DATA AFTERWARDS
            SetData(table, "Name",0,0);
            SetData(table, "Surname",1,0);

                panel.add(new JScrollPane(table,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
                }
    JFrame frame = new JFrame("Results");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(200, 200, 600, 400);
    frame.add(new JScrollPane(panel,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));

    frame.add(panel, BorderLayout.CENTER);
    frame.setVisible(true);
}

public void SetData(JTable table, Object obj, int row_index, int col_index){
      table.getModel().setValueAt(obj,row_index,col_index);
      }

and I had this next button when I was doing trying to do it with a table which would store all the data in a row.
JPanel navigation = new JPanel(
new FlowLayout(FlowLayout.CENTER));
JButton next = new JButton("NEXT");
next.addActionListener( new ActionListener(){
        public void actionPerformed(ActionEvent ae) {
        int height = table.getRowHeight()*(rows-1);
        JScrollBar bar = scrollPane.getVerticalScrollBar();
        bar.setValue( bar.getValue()+height );
        }
} );

I would appreciate any help.
Thank you a lot for reading this.

A: public class SwitchTableModel extends AbstractTableModel {
    private final String [] name = new String [] {"Alice", "Bob", "John", "Mary"};
    private final String [] surname = new String [] {"Green", "Red", "Brown", "Grey"};

    private final int [][] data = new int [][] {
        new int [] {1, 3, 2},
        new int [] {0, 2, 1, 3},
        new int [] {0, 3},
        new int [] {0, 1, 2, 3}
    };

    private int position = 0;

    @Override
    public int getRowCount() {
        return 2;
    }

    @Override
    public int getColumnCount() {
        return data [position].length + 1;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (rowIndex)
        {
        case 0:
            return columnIndex == 0 ? "Name" : name [data [position][columnIndex - 1]];
        case 1:
            return columnIndex == 0 ? "Surname" : surname [data [position][columnIndex - 1]];
        default:
            throw new Error ();
        }
    }

    public void previous ()
    {
        position -= 1;
        if (position < 0) position = data.length - 1;

        fireTableStructureChanged();
    }

    public void next ()
    {
        position += 1;
        if (position >= data.length) position = 0;

        fireTableStructureChanged();
    }

    public static void main(String[] args) {
        final SwitchTableModel model = new SwitchTableModel();

        Box toolbar = Box.createHorizontalBox();
        toolbar.add (new JButton (new AbstractAction("Previous") {
            @Override
            public void actionPerformed(ActionEvent e) {
                model.previous ();
            }
        }));
        toolbar.add (Box.createHorizontalGlue());
        toolbar.add (new JButton (new AbstractAction("Next") {

            @Override
            public void actionPerformed(ActionEvent e) {
                model.next ();
            }
        }));

        JTable table = new JTable(model);

        JFrame frame = new JFrame ();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add (toolbar, BorderLayout.NORTH);
        frame.getContentPane().add (
            new JScrollPane(
                table,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),
            BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}


text:
Q: Shiny & Plotly reactive amount rows in subplots based on length of CheckBoxGroupButtons (ERROR: (list) object cannot be coerced to type 'double') Any help would be greatly appreciated I've been struggling with this for a while. Reprex below.
I'm trying to make plotly::subplot(nrows = ?) with shiny checkbox inputs.
The inputs are datasets so they all have different Y-values but will be plotted along the same X-axis, hence the shareX = TRUE.
I am able to plot the traces if I specify nrow = 3 and all the boxes are checked but I want it to be conditional on the number of inputs selected. Only two inputs selected? Plot two rows. Only one input selected? Don't even use subplot. That's why I included nrows = length(input$choices). And that works when all three are checked!
But it is not working when I split it up into "if else" statements to specify whether I want the subplot or not, AND its not working when I check n < 3 inputs.
Instead I've gotten the error: (list) object cannot be coerced to type 'double'
I believe the error is coming from how the conditional statement is interpreting the length(input$choices) and or how subplot is interpreting the list of traces to plot.
library(shiny)
library(plotly)
library(dplyr)
library(tidyverse)

ui <- fluidPage(

    sidebarLayout(
        sidebarPanel(
            checkboxGroupInput("choices",
                        "Inputs:",
                        choices = c("Three", "Four", "Five"))
        ),

        mainPanel(
           plotlyOutput("distPlot")
        )
    )
)

server <- function(input, output) {
    gear5 <- reactive({
        req("Five" %in% input$choices)
    mtcars %>% filter(gear == 5)})

    gear4 <- reactive({
        req("Four" %in% input$choices)
        mtcars %>% filter(gear == 4)})

    gear3 <- reactive({
        req("Three" %in% input$choices)
        mtcars %>% filter(gear == 3)})

    output$distPlot <- renderPlotly({
        if (length(input$choices) > 1) {
        fig <- plot_ly() %>% add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines") %>%
                add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$wt, type = "scatter", mode = "lines") %>%
                add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$qsec, type = "scatter", mode = "lines")

        subplot(fig, shareX = TRUE, nrows = length(input$choices))

        }
        else if (length(input$choices) == 1) {
            plot_ly() %>% add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines") %>%
                add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$wt, type = "scatter", mode = "lines") %>%
                add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$qsec, type = "scatter", mode = "lines")
        }

    })
}

shinyApp(ui = ui, server = server)

AND here is code for the plot that is successful at making the desired figure but it doesn't react to inputs selected or the amount of inputs selected.
E.g. this is the included picture of the graph with all three inputs selected.1 <- Desired output
 output$distPlot <- renderPlotly({
        fig1 <- plot_ly() %>% add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines")
        fig2 <- plot_ly() %>% add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$wt, type = "scatter", mode = "lines")
        fig3 <- plot_ly() %>% add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$qsec, type = "scatter", mode = "lines")

        subplot(fig1, fig2, nrows = 2, shareX = TRUE)

    })

A: Once you specify which ones you want to plot, it works.  This is one way to meet your needs.
Try this:
server <- function(input, output) {
  gear5 <- reactive({
    if ("Five" %in% req(input$choices)) mtcars %>% filter(gear == 5)
    else return(NULL)
    })

  gear4 <- reactive({
    if ("Four" %in% req(input$choices))
    mtcars %>% filter(gear == 4)})

  gear3 <- reactive({
    if ("Three" %in% req(input$choices))
    mtcars %>% filter(gear == 3)})

  output$distPlot <- renderPlotly({
    req(input$choices)
    if (!is.null(gear3())) {
      fig3 <- plot_ly() %>%
        add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines")
    }
    if (!is.null(gear4())) {
      fig4 <- plot_ly() %>%
        add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$disp, type = "scatter", mode = "lines")
    }
    if (!is.null(gear5())) {
      fig5 <- plot_ly() %>%
        add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$disp, type = "scatter", mode = "lines")
    }

    if (length(input$choices) > 1) {
      # fig <- plot_ly() %>%
      #   add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines") %>%
      #   add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$wt, type = "scatter", mode = "lines") %>%
      #   add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$qsec, type = "scatter", mode = "lines")

      if (length(input$choices)==3){
        myplots <- list(fig3, fig4, fig5)
      }else{
        if (is.null(gear3())) myplots <- list(fig4, fig5)
        else if (is.null(gear4())) myplots <- list(fig3, fig5)
        else if (is.null(gear5())) myplots <- list(fig3, fig4)
      }

      fig <- subplot(myplots, shareX = TRUE, nrows = length(input$choices))

    }
    else if (length(input$choices) == 1) {
      fig <- plot_ly() %>%
        add_trace(data = gear3(), x = gear3()$mpg, y = gear3()$disp, type = "scatter", mode = "lines") %>%
        add_trace(data = gear4(), x = gear4()$mpg, y = gear4()$wt, type = "scatter", mode = "lines") %>%
        add_trace(data = gear5(), x = gear5()$mpg, y = gear5()$qsec, type = "scatter", mode = "lines")
    }
    fig

  })
}

A: YBS posted a great answer but I wanted to add in if people had 4 inputs instead of 3. If that's so you have to use && in your conditional statements.
Here's an example from my case that I've been working on.
if ( is.null(gitDataEDA()) && is.null(gitDataHRV()) ) myplots <- list(fig3, fig4) ## temp bvp
else if ( is.null(gitDataBVP()) && is.null(gitDataTEMP()) ) myplots <- list(fig1, fig2) # eda hrv
else if ( is.null(gitDataHRV()) && is.null(gitDataTEMP()) ) myplots <- list(fig1, fig4) #eda bvp
else if ( is.null(gitDataBVP()) && is.null(gitDataHRV()) ) myplots <- list(fig1, fig3) #temp eda
else if ( is.null(gitDataTEMP()) && is.null(gitDataEDA()) ) myplots <- list(fig2, fig4) #hrv bvp
else if ( is.null(gitDataBVP()) && is.null(gitDataEDA()) ) myplots <- list(fig3, fig2) #temp hrv


text:
Q: Cobalt - What are the latest feature added in the upstream Cobalt (14.119169)? We have successfully ported Cobalt broswer for raspi-2 platform.
We have also replaced existing FFMPEG & OpenMax and ported GStreamer based audio/video decoding functionalities.
Verified the default YouTube TV app and it works very well.
As of now we are using Cobalt 13.111497. We would like to upgrade to latest upstream Cobalt. It will be helpful if we know the added features with latest.
Please do suggest if we should refer to any other sources about latest updates in Cobalt if this forum is not the right place.


text:
Q: From variable to text I have this
@mutation
@name

What I am trying to do is to make @mutation look for the name of a product(name.products) and then have @name take the name of the product in @mutation as text. So what I am trying to do is to get the name of a product in products table and use it to name a view later on.
ALTER PROCEDURE [dbo].[exec_view]
AS
BEGIN

DECLARE @mutation NVARCHAR(255);
DECLARE @name NVARCHAR(255) ;

SET @mutation = N'SELECT
name
FROM INSERTED

' ;

SET @test = N'@mutatation varchar' ;

EXECUTE sp_executesql @name = @mutation ;

EXEC (
'
CREATE VIEW @name
AS SELECT *
FROM view_for_future_mutation
');

END

A: declare @name sysname;

set @name = (select quotename(name) from inserted);

exec (N'create view ' + @name + N' as select * from view_for_future_mutation');


text:
Q: Let $a\in X$ be a local max point for the function $f:X\to\Bbb{R}$. If $f$ has a right derivative at $a$, then $f'_+(a)\leq0$. Let $a\in X$ be a local max point for the function $f:X\to\Bbb{R}$. If $f$ has a right derivative at $a$, then $f'_+(a)\leq0$.
Dem: If $f'_+\gt0$, then exists some $\delta$ such that $a<x<a+\delta\Rightarrow f(a)<f(x)$ then $a$ would not be a local maximum point.
This is a review from a question i found. I understand the geometric concepts behind, but i didn't get the algebric concepts, i.e. why he used $a<x<a+\delta\Rightarrow f(a)<f(x)$ if we are talking about derivative?

A: Let $a\in X\subset\Bbb{R}$ be a local max point for the function $f:X\to\Bbb{R}$. Then there exists some $\delta$ such that for $a<x<a+\delta$ we have $f(a)\geq f(x)$. If $f$ has right derivative at $a$, according to derivate definition
$$f'_+(a)=\lim_{x\to a+}\frac{f(x)-f(a)}{x-a}\leq0$$


text:
Q: Manually adding a UDID to Xcode 10? Is there any way to add a UDID manually (one determined via iTunes) to the Apple Developer Portal and the Team Provisioning Profiles? I added the UDID to the Portal, and to all the manual Profiles, but I can't seem to get Xcode to update my app's Team Provisioning Profile to reflect the new UDID.
It seems to have worked in the past when connecting a device to Xcode and letting it set up that device, but I can't do that in this instance (the device is with a team member in another state).


text:
Q: Templates and std::pair list-initialization This is a follow-up to this question.
Why does this compile:
#include <iostream>
class Test {
    public:
        Test(std::pair<char *, int>) {
            std::cout << "normal constructor 2!" << std::endl;
        }
};

int main() {
    Test t6({"Test", 42});
    return 0;
}

But this does not:
#include <iostream>
class Test {
    public:
        Test(std::pair<char *, int>) {
            std::cout << "normal constructor 2!" << std::endl;
        }
        template<typename ... Tn>
        Test(Tn ... args) {
            std::cout << "template constructor!" << std::endl;
        }
};

int main() {
    Test t6({"Test", 42});
    return 0;
}

Error message:

error: call to constructor of 'Test' is ambiguous

As I understood in the previous question, the non-template constructor is preferred, if it exactly matches. So I guess {"Test", 42} does not match with std::pair?
If so, what would be the correct way? I know there is std::make_pair, but I want it as short as possible, because I can have several of those pairs and typing std::make_pair everytime would be unfavorable, because it bloats things. So what is the shortest way possible?

A: Since you're already using c++11, switch to brace initialization and your code will compile under gcc (4.7.2 at least) and do what you want:
...
int main() {
    Test t6{{"Test", 42}};
    return 0;
}

$ g++ t.cpp -std=c++11
t.cpp: In function 'int main()':
t.cpp:14:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

$ a.out
normal constructor 2!


text:
Q: How To Permanently Add Source IP to Route Table Entry in CentOS 5.11 I have a multi-homed CentOS 5.11 server in which I have manually changed the default route entry so that packets are sourced from a particular IP (45.32.6.197).  How can I make this change permanent across reboots?
The command I used to change the default route is:
# ip route change default via 104.238.132.1 src 45.32.6.197

and the resulting routing table looks as such:
# ip route list
45.32.6.0/23 dev eth0  proto kernel  scope link  src 45.32.6.197
104.238.132.0/23 dev eth0  proto kernel  scope link  src 104.238.133.199
169.254.0.0/16 dev eth0  scope link
default via 104.238.132.1 dev eth0  src 45.32.6.197

Thanks!


text:
Q: leafletjs setOpacity method transition? Im trying to find a way to switch between map layers with transition.
Currently Im using the setOpacity method to switch between map layers which has helped to avoid the flickering that addLayer and removeLayer methods create. However I would like to be able to add some transition to ease the switch.
Was wondering if there is a way to do this? Thank you!
Update: I found a way to do so by adding a CSS class.
map2010.getContainer().className += `mapTransition`
map2022.getContainer().className += `mapTransition`

.mapTransition{
transition: opacity 0.7s ease;
}

Got the answer from here: https://gis.stackexchange.com/questions/195271/how-to-add-custom-css-class-to-leaflet-tilelayer


text:
Q: Contar quantos campos estão em branco em uma linha do MYSQL Eu tenho uma tabela de cadastro com 53 colunas (endereço, telefone, etc).
Eu queria montar uma consulta que me trouxesse quantas dessas colunas estão vazias ou NULL, como posso fazer isso?

A: Não sei se entendi muito bem, mas, acredito que se você contar os registros usando a cláusula COUNT(*) e onde as colunas são nulas IS NULL e vazias ='', você consiga encontrar o esperado. Por exemplo:
SELECT COUNT(*) FROM tabela WHERE (coluna1 IS NULL or coluna1 = '')
AND (coluna2 IS NULL or coluna2 = '')
AND (coluna3 IS NULL or coluna3 = '') ... -- AND a quantidade de colunas que você desejar adiocionar na sua query.

Espero ter ajudado!

A: Baseando no que entendi (quantos campos de cada usuário não foram preenchidos), fiz o seguinte código (dá uma olhada nesse fiddle funcional):
create table tabela_colunas (id int, coluna varchar(100));
CREATE TABLE tabela_contador (id_na_tabela int(10), total int(1));

SET @id_tabela:=1, @total:=(SELECT COUNT(*) FROM tabela_colunas);

insert into tabela_contador (id_na_tabela, total)
select id, 0 as total from tabela;

WHILE @id_tabela <= @total DO

    set @sql := concat('update tabela_contador tc join tabela t on tc.id_na_tabela = t.id set tc.total = tc.total + 1 where ', (select coluna from tabela_colunas where id = @id_tabela), ' is null or ', (select coluna from tabela_colunas where id = @id_tabela), ' = \'\'');

    PREPARE myquery FROM @sql;
    EXECUTE myquery;

    SET @id_tabela = @id_tabela + 1;
END WHILE;

select * from tabela_contador;

Segui a seguinte lógica:

*

*criei uma tabela temporárias para armazenar os nomes das colunas;

*criei outra tabela temporárias para armazenar os totais de cada ocorrência da tabela original;

*para cada das colunas, é somado um ao total (quando id é o mesmo e o campo não tem valor);

*por fim, consulta da tabela de dado.


text:
Q: MERN stack app randomly broke after 6 months in production and throws the following error: "TypeError: r.filter is not a function" I wrote a full stack critical application using the MERN stack for a client and it has been running smoothly for over 6 months now. Today, my client notified me that upon logging into the app, the Dashboard view flashes on the screen and then disappears throwing this error: TypeError: r.filter is not a function.
The Dashboard view makes an AJAX call to the back-end and fetches a number of tickets from the database that are then stored in Redux and then categorized and displayed on the browser. There are several array methods used in this component, for example:
  const awaiting = tickets.filter(
    ticket =>
      (ticket.status === 'Return to Provider' ||
        ticket.status === 'Require survey') &&
      !ticket.closed
  );

  const unassigned = tickets.filter(
    ticket => ticket.status === 'Unassigned'
  );

  const pending = tickets.filter(ticket => ticket.status === 'Issued');

  const active = tickets.filter(
    ticket =>
      ticket.status === 'On field' ||
      ticket.status === 'Provisioning required by client'
  );

  const complete = tickets.filter(
    ticket =>
      (ticket.status === 'Complete' ||
        ticket.status === 'Complete to activate at a later date') &&
      !ticket.closed
  );

The error is thrown at the first .filter method. If I comment that out, the error is thrown at the next and so on. The same error is being thrown wherever there is an array method used and this is the exact error message:
TypeError: r.filter is not a function
at t.value (Dashboard.js:99)
at Mi (react-dom.production.min.js:3785)
at Pi (react-dom.production.min.js:3776)
at ji (react-dom.production.min.js:3960)
at Ba (react-dom.production.min.js:5514)
at $a (react-dom.production.min.js:5536)
at Mu (react-dom.production.min.js:5958)
at Cu (react-dom.production.min.js:5925)
at ku (react-dom.production.min.js:5860)
at Xa (react-dom.production.min.js:5787)

When I try to access another view on the app where an array method is used to render a list of tickets specifically, I get the same error. But, I am able to access any other view that does not render a list of tickets, there are no errors thrown.
NOTE: This ONLY occurs when I connect to the production database, which has over 2000 tickets (over 30MB of data), regardless of whether I am connecting from my localhost environment or from production environment.
However, when I connect the same code base to my test database (which has 34 tickets), there are no errors thrown and everything runs smoothly.
This is literally the only difference I can identify that is producing this error and crashing the entire app (the number of tickets that the array methods are operating on).
As I said before, the production app was running smoothly for the last 6 months. What would cause such a random app-breaking error like this?

A: There could be a number of reasons why filter() might not work in your situation.
Can you specify the network response you are getting ? That would be a good way to start debugging.
There are 2 main failure points at play here:

*

*Response is coming wrong from backend or not coming at all (server side fault, which seems like the probable cause because your app suddenly broke)

*There is something wrong with your client side code
Response from backend can break because of any number of reasons. You can check for:

*

*SSL Certificate expiry

*Environment Variable mis-function issue

*Response being very large (as you said 30MB, in which case you can use and should definitely use pagination)


text:
Q: Pulse generator with single op amp and diode I want to design pulse generator with specific period and duty cycle. I found a pulse generator with single op amp and diode. I couldn't find information about how to calculate period and duty cycle. If you have any suggestion about pulse generator design with single op amp (not comparator or 555 timer). You can find my schematic in figure below.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. The basic relaxation oscillator.
How it works:

*

*OUT is initially low, C1 is discharging and the threshold voltage, Vt, is at 1/3 supply. (R1 and R2 form a half-supply voltage divider but R3 is in parallel with R2 pulling it down to V1/3.)

*When Vc drops below V1/3 the op-amp output switches high, Vt changes to 2/3 V1 and C1 starts charging.

*The half-cycle time could be roughly approximated by \$ \tau = R4 \cdot C1 = 10k \cdot 1µ = 10 \ \mathrm{ms} \$ if the capacitor was charging from 0 to 63%. As it is actually charging from 33% to 66% the time will be somewhat shorter - about 7 ms on the simulation below.

Figure 2. The waveforms obtained from Figure 1.
The simplest way to control the duty cycle is to control the charge and discharge times independently with diodes as shown in Figure 3.

simulate this circuit
Figure 3. Duty-cycle control with diodes.

Figure 4. Resultant simulation.

simulate this circuit
Figure 5. By adding a potentiometer the duty cycle can be adjusted while maintaining the frequency reasonably stable.

simulate this circuit
Figure 6. You can also leave out one of the diodes. In this case discharging C1 is done through R5 only while charging is done through R5 and R4.

There's a useful calculator at Must Calculate that will work out the time constants for you. For the timing of my Figure 1 it worked out 6.93 ms.
You can play with the CircuitLab simulations by "editing" my question and editing the schematic. Just don't save them on your way out!
Note that I haven't included the voltage drop of the diodes in my calculations. It will affect the results a bit but the simulator should pick that up for you.


text:
Q: Как перенести laravel на хостинг? Имеется сайт на локальном хосте написанный на laravel.
Как его перенести на хост, помимо того, что его нужно залить в корень сайта?

A: Ты не уточнил какой хостинг.
Если шаред, то возможно придется переименовать папку pulbic_html в public или сделать симлинк.
Если VPS, то проблем быть не должно, конечно если он настроен.

A: Интересный вопрос, но мало уточнений нюансов, проект просто в локальной папке и заливать планируете по ftp? Если да, то требования к хостингу указаны в документации, нужно будет выставить атрибуты папок и файлов storage и bootstrap на 775, если умеете конфигурировать сервер и дать права на выполнение правильному пользователю, иначе 777. Ну и вопрос с public и public_html, но тут уже вам ответили.

A: Делаю все с помощью Git:
1 Захожу в папку public_html
2 Делаю git clone
3 Тут будет папка с проектом. По этому нужно создать .htaccess c редиректом в папку public проекта. Например:
<IfModule mod_rewrite.c>
 RewriteEngine On
RewriteRule ^(.*)$
Project/public/$1 [L]
</IfModule>

4 Копирую .env файл и делаю вписываю настройки БД и т.д...
5 composer i && composer update
6 php artisan key:generate
7 php artisan migrate
Все :)


text:
Q: Will PostgreSQL engine optimize this query? I have two queries like this:
SELECT ... FROM ... WHERE (status IN (1,2,3) OR status IN (3,4,5)) AND ... AND status IN (2,3)

and this one:
SELECT ... FROM ... WHERE ... AND status IN (2,3)

These queries are executed in almost same time that makes me think that SQL engine optimizes first query and makes somthing like in second example.
Am I right or wrong? Is there any profit to optimize first query manually to the second one, or I can rely on SQL engine?

A: PostgreSQL probably does the right thing here as long as the items in your IN() clauses are constants.
To verify that, you can run both queries prefixed with EXPLAIN ANALYZE and examine the execution plans. Completely understanding execution plans takes some work. But PostgreSQL probably reduces all those IN() clauses to a single lookup predicate.


text:
Q: SELECT statement doesn't return the expected results Hello there good people of Stackoverflow.
I have a issue with my Sql, since I'm new to it I'm quite sure that its a matter of Syntax or bad/misunderstod logic.
here is the relevant frondend:
<asp:DropDownList ID="DropDownList_Brand" runat="server">
  <asp:ListItem>Brændeovn</asp:ListItem>
  <asp:ListItem>Brændespande</asp:ListItem>
  <asp:ListItem>Pejsesæt</asp:ListItem>
  <asp:ListItem>Optænding</asp:ListItem>
  <asp:ListItem>Vedligeholdelse</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox_Sog_Adv" runat="server"></asp:TextBox>
<asp:Button ID="Button_Sog_Adv" runat="server" Text="SØG" OnClick="Button_Sog_Click_Adv" />

And here is the backend:
protected void Button_Sog_Click_Adv(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    var Pr_Navn = TextBox_Sog_Adv.Text;
    var Pr_Type = DropDownList_Brand.Text;
    cmd.CommandText = "SELECT * FROM Table_Products WHERE products_name LIKE '%" + Pr_Navn + "%' OR products_brand LIKE '%" + Pr_Navn + "%' AND products_type='" + Pr_Type + "'";

    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    Repeater_Sog_Adv.DataSource = dt;
    Repeater_Sog_Adv.DataBind();
}

Now I'm quite sure its the AND thats the problem, I'm lead to belive that AND is like OR but it must be True. (Might be Wrong)
Yet the main focus here is this line:
cmd.CommandText = "SELECT * FROM Table_Products WHERE products_name LIKE '%" + Pr_Navn + "%' OR products_brand LIKE '%" + Pr_Navn + "%' AND products_type='" + Pr_Type + "'";

Any help is much appreciated.

A: You probably miss some parenthesis
WHERE (products_name LIKE '%" + Pr_Navn + "%' OR products_brand LIKE '%" + Pr_Navn + "%') AND products_type='" + Pr_Type + "'";

You may take a look at operator precedence in sql (sql server here) to understand how mixed OR/AND are treated, and forget it immediatly to remember you should rather use parenthesis.
Now, your should take care of sql injection, and use parameterized queries.


text:
Q: Centering content in tables Hi guys I am new to LaTeX, I have a very large table with data in it which moves past the page. I have managed to fix it and adjust it according to the page but I lost the centering option for the data can you please tell me how to center the data while maintaining the specification I have provided for the length the columns I have attached the code I am using so you can understand me better
\begin{tabular}{ | p{5cm} | p{2cm} | p{2cm} | p{2cm} |}
I tried adding c to the code like | c p{5cm} | but it still wouldn't center the data inserted in the table. Thank you

A: (1) Always post minimal examples that can be copied and compiled as is. This is a sniplet. MWEs makes it a lot easier to help
\usepackage{array}

 \begin{tabular}{ |
  >{\centering\arraybackslash} p{5cm}
   | >{\centering\arraybackslash}p{2cm}
   | >{\centering\arraybackslash}p{2cm}
   | >{\centering\arraybackslash}p{2cm} |}

array enables up to get the >{...} construction, so we insert \centering into each cell. But this messes with \\ so it nolonger means new row, \arraybackslash brings back the original table definition
And do consider if those lines are really necessary (they often make the tale much less readable)

A: Use the array package and define a new column type C which uses the p type and centers it.
It would be possible to write this directly in the tabular column definition, but the \newcolumntype is cleaner, especially if there are more than on columns to change.
\documentclass{article}

\usepackage{array}

\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\begin{document}
\begin{tabular}{|C{5cm}|*{3}{C{2cm}|}}
\hline
a & b & c & d \tabularnewline
\hline
\end{tabular}
\end{document}


text:
Q: GUI construction error I'm still fairly new to Java, and am not sure why I am getting an error when I compile (no errors show prior to that). The error is:
Exception in thread "main" java.lang.NullPointerException
at Lab10.<init>(Lab10.java:21)
at Lab10.main(Lab10.java:55)

I was assuming that is indicating that the array is null? I tried moving it before the constructor, and it came out with errors in whatever I did. There were hundreds of errors before I initialized it with just a space before I actually used the user input as the array. All I am trying to make is a simple GUI where if you click on the button "Add Course" it will prompt you to type in a course, and that will add to the JList. I would appreciate any input! Thank you!
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Lab10 extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    int count = 0;
    String subject;
    private JList list;
    private JButton button;
    private JButton button2;
    Scanner input = new Scanner(System.in);
    String [] Courses;

    @SuppressWarnings("unchecked")
    public Lab10() {
        JPanel p1 = new JPanel();
        for (int j = 0 ; j < 100 ; j++) {
            Courses[j] = " ";
        }
        p1.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
        button = new JButton("Add Course");
        button2 = new JButton("Close");
        button.addActionListener(this);
        button2.addActionListener(this);
        add(button);
        add(button2);

        setLayout(new BorderLayout(10, 10));
        list = new JList(Courses);
        add(list, BorderLayout.CENTER);
        add(p1, BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Add Course")) {
            System.out.println("Enter your new subject: ");
            subject = input.next();
            count++;
            for (int i = 0 ; i <= count ; i++) {
                if (Courses[i].equals(" ")) {
                    Courses[i] = subject;
                }
            }
        }
        else if (e.getActionCommand().equals("Close")) {
            System.exit(0);
        }
    }

    public static void main(String [] args) {
        Lab10 frame = new Lab10();
        frame.setTitle("Java");
        frame.setSize(500, 600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

A: Add this to the top of your constructor:
this.Courses = new String[100];

Even better, you should actually move that 100, and the 100 in your for loop condition, to something like:
private static final int ARRAY_SIZE = 100;

Then change the other instances of 100 to ARRAY_SIZE.
Also, note that the NullPointerException isn't happening when you compile; it's happening when you run the program.

A: Basically, you've declared an array called Courses but you've never initialised it...
String[] Courses;

@SuppressWarnings("unchecked")
public Lab10() {
    JPanel p1 = new JPanel();
    for(int j = 0; j < 100; j++){
        Courses[j] = " ";
    }

Make sure you allocate the required number of elements to the array before you try and use it, for example...
String[] Courses;

@SuppressWarnings("unchecked")
public Lab10() {
    JPanel p1 = new JPanel();
    Courses = new String[100];
    for(int j = 0; j < Courses.length; j++){
        Courses[j] = " ";
    }

You may also wish to take a read through Code Conventions for the Java Programming Language, as it will make you code eaiser for others to read


text:
Q: ListAdapter sharing Can same adapter be safely shared among different ListViews or GridViews ?
And if so, can two different view be returned from getView() based on who is asking for that view ?

A:
Can same adapter be safely shared among different ListViews or GridViews ?

Yes. But why would you want to display the same information twice (once in a ListView and again in a GridView)?

And if so, can two different view be returned from getView() based on who is asking for that view ?

Yes... You could override getView() and return different Views from getItemViewType() based on getView()'s parameter ViewGroup parent. But if the Views are so different why not use to different adapters?


text:
Q: Fastest way of deseriallizing JSON C# I have list of JSON strings which may contain 1000-2000 records per string. The list count may be around 100,000. I tried to use JSON.net (JsonConvert.DeserializeObject), System.Web.Helpers.Json.Decode and JavascriptSerializer.Deserialize (i followed this post and used DynamicJsonConverter). In a performance comparison, JavascriptSerializer.Deserialize works quite better than others but still it does not meet my requirements. I need to know that what could be the most efficient way of de-serializing JSON into object/dynamic. Or if someone would like to share performance benchmark of de-serializing JSON would be very helpful.
Thanks!

A: JSON.NET is always performant.
Old, but relevant:
http://james.newtonking.com/archive/2010/01/01/net-serialization-performance-comparison


text:
Q: Solve $x^2\equiv a$ mod $\prod P_i^{e_i}$ Suppose we have the solutions to  $x^2\equiv a$ mod $P_i^{e_i}$. How do we find solutions to $x^2\equiv a$ mod $\prod P_i^{e_i}$. For example, I know $x^2\equiv  1$ mod $3$ has solution $\pm 1$ mod $3$ and  $x^2\equiv  1$ mod $5$ has solution $\pm 1$ mod $5$. Can we construct all the solutions to  $x^2\equiv  1$ mod $15$ from them? Can we use Chinese remainder theorem?

A: Yes, you can. You have to start from a Bézout's relation between $3$ and $5$:
$$2\cdot 3-1\cdot 5=1$$
Now if you have solutions $a$ mod. 3 and $b$ mod. $5$, we deduce  solutions mod. $15$:
$$x\equiv b\cdot 2\cdot 3-a\cdot 1\cdot 5=6b-5a\mod15.$$


text:
Q: Error in executing Open-NLP Ruby Gem The ruby code we were trying to execute based on https://github.com/louismullie/open-nlp/blob/master/README.md:
#gem inclusion

require 'open-nlp'

# Set an alternative path to look for the JAR files.
# Default is gem's bin folder.
OpenNLP.jar_path = '/home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/bin/'

# Set an alternative path to look for the model files.
# Default is gem's bin folder.
OpenNLP.model_path = '/home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/bin/'

# Pass some alternative arguments to the Java VM.
# Default is ['-Xms512M', '-Xmx1024M'].
OpenNLP.jvm_args = ['-Xms512M', '-Xmx1024M']

# Redirect VM output to log.txt
OpenNLP.log_file = 'log.txt'

# Set default models for a language.
OpenNLP.use :language

#Maximum entropy tokenizer, chunker and POS tagger
OpenNLP.load

chunker   = OpenNLP::ChunkerME.new
tokenizer = OpenNLP::TokenizerME.new
tagger    = OpenNLP::POSTaggerME.new

sent   = "The death of the poet was kept from his poems."

tokens = tokenizer.tokenize(sent).to_a
# => %w[The death of the poet was kept from his poems .]

tags   = tagger.tag(tokens).to_a
# => %w[DT NN IN DT NN VBD VBN IN PRP$ NNS .]

chunks = chunker.chunk(tokens, tags).to_a
# => %w[B-NP I-NP B-PP B-NP I-NP B-VP I-VP B-PP B-NP I-NP O]

And that is the output:
/home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/lib/open-nlp/bindings.rb:125:in `+': no implicit conversion of nil into String (TypeError)
    from /home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/lib/open-nlp/bindings.rb:125:in `load_model'
    from /home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/lib/open-nlp/bindings.rb:110:in `get_model'
    from /home/USER/.rvm/gems/ruby-2.1.2/gems/open-nlp-0.1.5/lib/open-nlp/base.rb:13:in `initialize'
    from opennlp_example.rb:26:in `new'
    from opennlp_example.rb:26:in `<main>'

As it is just the example (Simple tokenizer example is running fine)... we hope someone knows more about that

A: Looking at the code it seems that OpenNLP::Config::DefaultModels[name][OpenNLP.language] is nil:

  def self.load_model(name, file = nil)
    if self.models[name] && file ==
      self.model_files[name]
      return self.models[name]
    end
    models = OpenNLP::Config::DefaultModels[name]
    file ||= models[self.language] # <- this is the problematic line
    path = self.model_path + file
    stream = FileInputStream.new(path)

I suspect that checking OpenNLP.language would yield :language, from the line:
# Set default models for a language.
OpenNLP.use :language

As the implementation for use is:

  def self.use(language)
    self.language = language
  end

Bottom line - try removing OpenNLP.use :language from your code, or changing it to OpenNLP.use :english


text:
Q: AngularJS: ui-select bind data back to the select I am using Angular js 1.3.4 version and using ui-select.
I am binding complex multilevel JSON array of objects to this ui-select which works fine. So the user can select any options in this select. When the user saves other data and this select data I am saving this info in the database. All this works fine.
What I am having issues is how to bind back data to this. It might not be the issue  of ui-select only as I am not able to bind back the data to the textbox as well.
So below is the json(after some modification) which I get from my db:
{
   "input1":{
      "set1":{
         "source":"uat1",
         "value":"value1"
      },
      "set2":{
         "source":"uat",
         "value":"value2",
         "options":[
            {
               "name":"option1"
            },
            {
               "name":"option2"
            }
         ]
      }
   },
   "input2":{
      "set3":{
         "source":"uat1",
         "value":"value3"
      },
      "set4":{
         "source":"uat",
         "value":"value4",
         "options":[
            {
               "name":"option3"
            },
            {
               "name":"option4"
            }
         ]
      }
   }
}

Below is my directive where I try to bind back the data:

    {{name}}
    <ui-select name="{{inputName + $index}}" ng-model="set.value" theme="bootstrap" ng-if="set.source == 'uat'">
        <ui-select-match placeholder="Set">{{set.value.name}}</ui-select-match>
        <ui-select-choices repeat="ds in set.options | filter: $select.search track by $index">

        </ui-select-choices>
    </ui-select>
    <input type="text" ng-if="set.source == 'uat1'" name="{{inputName + $index}}" ng-model="set.value" />

The result of above is that for my ui-select I can see the options which means it is binded correctly with my incoming json data.
The issue is the value displayed. I cannot see anything select in my ui-select and my textbox is also empty.
Since the model of each of above is ng-model = 'set.value' I am passing this in my json. So I thought this would work but it does not.
I believe I am missing something in my Json. Can anyone point out whats missing here so that I can see the value field in my json to the corresponding control.
Thanks.

A: In AngularJS ui-select, the ui-select-match directive is used to show which value is selected and should display in the textbox. You are displaying the wrong data here (set.value.name). You need to instead display the selected value using $select.selected.name.
<ui-select-match placeholder="Set">{{$select.selected.name}}</ui-select-match>

Your ui-select-choices are objects so if you want to set a default value from the controller, your value needs to be an object that exists in the options. So you can set a default value to the ui-select by assigning the right value to your ng-model set.value.
"value": {
    "name":"option1"
}


text:
Q: Postfix Header_Checks Reject Legitimate Mail (CnetOS 7 + Postfix 2.10.1) I use Postfix to block terms in headers and bodies.  In few cases, it blocks legitimate mails because the term used is present in a long string (probably an id or reference or a coded string).
For example:
/AQHV/ REJECT  SPAM RULE #5
Emails containing the following text in their headers are rejected.  Because the characters "AQHV" are in the one of the headers:-
Thread-Index: AQHVSEXnJ2u6futfzU6u85aNv7EgTg
I have tried to add a space before + after the term AQHV, like so:-
/ AQHV/ REJECT  SPAM RULE #5
/AQHV / REJECT  SPAM RULE #6
This error occurs:
postmap: warning: /etc/postfix/header_checks.db: duplicate entry: "/"
How can I tell Postfix to treat the term "AQHV" as a separate word only, and not as part of a string?
Thanks in advance!
tripleee:  apologies for the comments - still struggling with these forums.
I have decided to uninstall Postfix and reinstall it again. It might solve this problem.  I will accept your answer.  Many thanks.

A: Try /\bAHQV\b/. Here \b is a regex word boundary marker.

A: Make sure you include this in main.cf:
header_checks = pcre:/etc/postfix/header_checks

Run these commands, assuming header_checks is in /etc/postfix/.
postmap /etc/postfix/header_checks
postfix reload

To deal with spaces in regex/pcre, you can comment them out. For example, if you wanted to reject any email with a space in the header, you could put this in header_checks:
/\ / REJECT NO SPACES ALLOWED!!!!

So, if you wanted to just block an email with a line in the header that contained AHQV, but just the string AHQV, not AHQV as a substring in a larger string, then this is the regex you need:
/\ AHQV\ / REJECT NO AHQV PLS

I hope this helps!!


text:
Q: VueJS + TinyMCE: TinyMCE is only displayed once Please try the code snippet.
I have many components in Vue Router, every component has its own TinyMCE editor to edit content. However, TinyMCE is only displayed for the first loaded router. There is an error in the console: Permission denied to access property "document" which only occurs when I use TinyMCE and Vue together, I don't know if it is the reason of my problem.
I appriciate if anyone has a solution!
I have another version of this problem at jsfillde: http://jsfiddle.net/tranduyhung/NF2jz/5105/ . I don't get the error Permission denied to access property "document" at jsfiddle.

var Foo = Vue.extend({
    template: '#foo',
   ready: function() {
      // This doesn't help
      //tinyMCE.remove()

      tinyMCE.init({selector: "#tinymcefoo"})

      // This is not working
      //tinyMCE.execCommand('mceAddControl', false, '#tinymcefoo');
      //tinyMCE.execCommand('mceAddEditor', false, '#tinymcefoo');
    }
})

var Bar = Vue.extend({
    template: '#bar',
   ready: function() {
      // This doesn't help
      //tinyMCE.remove()

      tinyMCE.init({selector: "#tinymcebar"})

      // This is not working
      //tinyMCE.execCommand('mceAddControl', false, '#tinymcefoo');
      //tinyMCE.execCommand('mceAddEditor', false, '#tinymcefoo');
    }
})

var App = Vue.extend({})
var router = new VueRouter()

router.map({
    '/foo': {
        component: Foo
    },
    '/bar': {
        component: Bar
    }
})

router.redirect({
  '*': '/foo'
})

router.start(App, '#app')

Menu: Working | Not working

  <router-view></router-view>

A: Intialize tinyMCE just once, you can make it at the start of your application
tinceMCE.init({
  mode: 'none'
});

Use the ready and beforeDestroy events of Vue to reload the editor at every initialization
var Foo = Vue.extend({
  // ...
  ready: function() {
    tinyMCE.execCommand('mceAddEditor', true, 'tinymcebar'); // id without '#'
  },
  beforeDestroy: function() {
    tinyMCE.execCommand('mceRemoveEditor', true, 'tinymcebar');
  }
}

link to updated jsfiddle

A: Yes I found a solution like this:
// load tinymce placeholder plugin from from local static file
tinymce.PluginManager.load('placeholder', '/static/js/tinymce/plugins/tinymce-placeholder.plugin.js');

Here is the full source of my TinyMceComponent:
https://github.com/Doogiemuc/liquido-vue-frontend/blob/master/src/components/TinyMceComponent.vue

A: Try giving your textareas the same class and choose that class as selector:
<textarea id="tinymcefoo" class="my_editor"></textarea>
<textarea id="tinymcebar" class="my_editor"></textarea>

On ready use
tinyMCE.init({selector: ".my_editor"});


text:
Q: Infimium between two sets with a bijection People, I need some help about a thing: I am studying analysis and, between my thoughts about supremum and infimum, I started to ask myself the following:

Let A, B $\neq \emptyset$ and $f:A\rightarrow B$ be a bijection. Assume that there A and B are bounded below. Show that $f(\inf(A))=\inf(B)$.

Is that sentence true? Why? I did not found a way to prove it, since I can not assume that $f$ takes the infimium from one set to the another, once $\inf(A) \notin A$, in general.

A: Here's a contradiction: $A = B = [0, 1]$, and $f(x) = 1 - x$. Then $f(\inf A) = f(0) = 1 \neq \inf(B)$.

A: I am interpreting "inferiorly limited" as "bounded below" since I haven't seen that terminology before; and this does not seem true at all.
Suppose $A = \{1,2,3\}, B=\{4,5,6\}$, then $\text{inf}(A) = min(A)= 1$, $\text{inf}(B)=min(B)=4$.
And we have the bijection $f: A\rightarrow B, f(x)=x+3$.
Giving us a contradiction.


text:
Q: Sticking stream data to specific working We are trying to replace Apache Storm with Apache Spark streaming.
In storm; we partitioned stream based on "Customer ID" so that msgs with a range of "customer IDs" will be routed to same bolt (worker).
We do this because each worker will cache customer details (from DB).
So we split into 4 partitions and each bolt (worker) will have 1/4 of the entire range.
I did see comparison Spark and Storm; and this being limitation on Spark.
I am hoping we have a solution to this in Spark Streaming

A: When using Kafka, one way to address this problem is to partition your data at the producer side. As you probably have seen, Kafka messages have a key, and you may use that key to partition the data among partitions.
Using the Kafka receiver, you create one receiver per partition. Upon start of the Streaming  job, the receivers will be distributed over several executors.
This means that every executor (JVM) will be receiving data for only the partitions it's got assigned. This results on the same id going to the same executor for the lifetime of the receiver, and enables effective local caching as intended in the question.