text:
Q: Test for parameter passed to NEST (elasticsearch) I am using NEST to do elasticsearch queries.
    public IReadOnlyCollection<IHit<Recommendation>> GetRecommendations(
        RecommenderQueryFields shoulds,
        RecommenderQueryFields musts,
        RecommenderQueryFields mustNots)
    {
        var boolQuery = new BoolQuery();
        boolQuery.Should = GetQueryContainers(shoulds);
        boolQuery.Must = GetQueryContainers(musts);
        boolQuery.MustNot = GetQueryContainers(mustNots);

        var response = _elasticClient.Search<Recommendation>(s => s
            .AllTypes().From(0).Size(10)
            .Query(outerQuery => boolQuery));

        return response.Hits;
    }

I have logic in the GetQueryContainers method which I want to test.
Is there some way to check what has been passed to the ElasticClient in the boolQuery object?
I have tried the following stuff already, using NUnit and NSubstitute.
    [Test]
    public void Test1()
    {
        // Arrange
        var searchResponse = Substitute.For<ISearchResponse<Recommendation>>();
        searchResponse.Hits.Returns(new List<IHit<Recommendation>>());
        var elasticClient = Substitute.For<IElasticClient>();

        var sut = new Recommender(elasticClient);

        // Act
        sut.GetRecommendations(null, null, null);

        // Assert
        elasticClient
            .Received(1)
            .Search(Arg.Is<Func<SearchDescriptor<Recommendation>, ISearchRequest>>(x => true));
    }

In the Arg.Is<[...]>(x => true) I would like to replace the true constant for some checks on boolQuery. But I do not know if it is possible or how it is done. Or is there a different way to do this?

A: TL;DR Use a derived QueryVisitor. See Edit2 below.
Found that the question has been answered already. It is not related to NEST, but to testing lambda expressions.
It is not possible: C# Moq Unit Testing with Lambda Expression or Func delegate
What can be done is testing the JSON request which will be sent to elasticsearch, but then you need the actual ElasticClient: ElasticSearch NEST 5.6.1 Query for unit test
What can be done is putting the logic in its own method/class. But then you write code simply for the sake of testing, which I'm not a fan of. Like:
public BoolQuery GetBoolQuery(RecommenderQueryFields shoulds, RecommenderQueryFields musts,
    RecommenderQueryFields mustNots)
{
    var boolQuery = new BoolQuery();
    boolQuery.Should = GetQueryContainers(shoulds);
    boolQuery.Must = GetQueryContainers(musts);
    boolQuery.MustNot = GetQueryContainers(mustNots);
    return boolQuery;
}

You are exposing a public method which you are not intending for use, only for testing.
But you can then assert on boolQuery like this:
[Test]
public void GetRecommendations_CallsElasticSearch()
{
    // Arrange
    var elasticClient = Substitute.For<IElasticClient>();
    var sut = new Recommender(elasticClient);

    // Act
    var boolQuery = sut.GetBoolQuery(new RecommenderQueryFields{BlackListedFor = new List<string>{"asdf"}}, null, null);

    // Assert
    Assert.AreEqual(1, boolQuery.Should.Count());
}

In boolQuery.Should is a list of QueryContainer which are not testable because it is generated with lambdas aswell. While better than nothing, it is still not a clean way to test NEST.
Edit
@Russ Cam in the comment has mentioned the IQueryContainer and QueryVisitor
What I've got:
[Test]
public void test()
{
    // Arrange
    var fieldValue = "asdf";
    var elasticClient = Substitute.For<IElasticClient>();
    var sut = new Recommender(elasticClient);

    // Act
    var boolQuery = sut.GetBoolQuery(new RecommenderQueryFields { BlackListedFor = new List<string> { fieldValue } }, null, null);

    // Assert
    IQueryContainer qc = boolQuery.Should.First(); // Cast to IQueryContainer
    Assert.AreEqual(fieldValue, qc.Match.Query); // Assert value

    // Get "field name"
    var queryVisitor = new QueryVisitor();
    var prettyVisitor = new DslPrettyPrintVisitor(new ConnectionSettings(new InMemoryConnection()));
    qc.Accept(queryVisitor);
    qc.Accept(prettyVisitor);
    Assert.AreEqual(0, queryVisitor.Depth);
    Assert.AreEqual(VisitorScope.Query, queryVisitor.Scope);
    Assert.AreEqual("query: match (field: blacklistedfor.keyword)\r\n", prettyVisitor.PrettyPrint);
}

The value of the field can be accessed via IQueryContainer.
I tried the QueryVisitor and the DslPrettyPrintVisitor. The first one doesn't provide any useful information. It has 0 depth and it is a Query? I already know that. With the second one I can assert some additional information, like the field name (blacklistedfor) and the suffix (keyword).
Not perfect to assert on the string representation, but better than nothing.
Edit2
@Russ Cam gave me a solution which I am really happy with. It uses a derived QueryVisitor:
public class MatchQueryVisitor : QueryVisitor
{
    public string Field { get; private set; }
    public string Value { get; private set; }

    public override void Visit(IMatchQuery query)
    {
        var inferrer = new Inferrer(new ConnectionSettings(new InMemoryConnection()));
        Field = inferrer.Field(query.Field);
        Value = query.Query;
    }
}

[Test]
public void test()
{
    // Arrange
    var fieldValue = "asdf";
    var elasticClient = Substitute.For<IElasticClient>();
    var sut = new Recommender(elasticClient);

    // Act
    var boolQuery = sut.GetBoolQuery(new RecommenderQueryFields { BlackListedFor = new List<string> { fieldValue } }, null,
        null);

    // Assert
    IQueryContainer qc = boolQuery.Should.First();
    var queryVisitor = new MatchQueryVisitor();
    qc.Accept(queryVisitor);
    Assert.AreEqual(fieldValue, queryVisitor.Value);
    Assert.AreEqual("blacklistedfor.keyword", queryVisitor.Field);
}

So in MatchQueryVisitor, it gets the Field and Value, which are then asserted in the test method.


text:
Q: How to check built-in formatter/beautifier version? and does it auto-update? Somebody from stackoverflow asked me to check if I have the latest js-beautify in my vscode. But I don't know how to check it. Can you please help?
I read from one of the threads in VS Code that it uses js-beautify as the formatter (it's the one doing the 'formatonsave' etc.). Please correct me if I'm wrong.
If it uses js-beautify, how do I know what version it is in? and does it auto-update to the latest version whenever there's a new one?
Thank you.
I already tried going through documentations and I also checked the preferences thoroughly, but I can't seem to find how to (manually) check for updates about plugins, especially the built-in ones like js-beautify.

A: The default setting for extensions.autoUpdate in VS Code enables auto-updating for all extensions. You can confirm this in your user settings or simply bring up the Command Palette (CTRL+SHIFT+P) and type 'auto update' to enable or disable it.
In the Command Palette you can also update extension mannually.
The current version of every installed extension is listed right next to its name in the extension panel or under the Changelog panel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple components binding with the same reactive form control update issue In some situations, we could need to have multiple form components binded to the same form control. And I'm confused by the angular way of handling this case:
When changing one of the components value, the form value is changed but not the other components values.
The workaround I did in this case is to patch the from with the form value, which is ugly:
this.form.patchValue(this.form.value);

Here is a stackblitz demo for my issue, I added the workaround for the input change not the select for better understanding.
Is there an elegant way to handle this case with angular reactive forms?

A: A nice reactive solution which would not require adding any (change) listeners, would be to create two separate name controls, and keep them in sync by subscribing to valueChanges stream.
component.ts
import { Component, NgModule, ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      nameText: '',
      nameSelect: '',
    })

    const text = this.form.get('nameText');
    const select = this.form.get('nameSelect');

    text.valueChanges.subscribe(v => select.setValue(v, { emitEvent: false }));
    select.valueChanges.subscribe(v => text.setValue(v, { emitEvent: false }));
  }

}

component.html
<form [formGroup]="form">
  When you change the input, the select changes :

  <input type="text" formControlName="nameText">

  When you change the select, the input does not change :

  <select formControlName="nameSelect">
    <option value="value1">value1</option>
    <option value="value2">value2</option>
  </select>
</form>

Live demo

A: I solved it by just using AbstractControl
valueChanges and setValue APIs. In this approach you don't have to use 2 separate form controls, you can have any number of components bound to the same reactive form control.
this.form.get('formControlName').valueChanges.subscribe(value => {
    this.form.get('formControlName').setValue(value, { onlySelf: true, emitEvent: false, emitModelToViewChange: true });
  }, error => {}, () => { });

The key here is the options param of setValue, this will prevent the recusive execution of valuesChanges until overflow.
{ onlySelf: true, emitEvent: false, emitModelToViewChange: true }

A: I looked for a generic solution: I'm using a JSON var "prevData" to remember the previous value and not loop indefinitely:
this.prevData = "";

this.form.valueChanges.subscribe(

  data => {
    let str = JSON.stringify(data);
    if (str != this.prevData){
      this.prevData = str;
      this.form.patchValue(data);
    }
  }
);


text:
Q: Implement a single iAd banner across entire multi page app using Swift Does anyone know how to implement a single iAd banner that sits at the top level of your app so that every view controller that is displayed contains the same instance of the single iAd banner?
I had an implementation a few years ago in Obj-C but cannot find an equivalent in Swift.

A: As the user above me said what you are looking for is a shared banner ad. You don't need to move the delegates to app delegate.swift, you just need to add the properties there.
https://developer.apple.com/library/ios/technotes/tn2286/_index.html
I made an ad helper for swift, why don't you check it out.
https://github.com/crashoverride777/Swift-iAds-and-AdMob-Helper


text:
Q: Setting auto dimension on core-image causes it not to render I have a core-image component in my page that I'm sizing to fit the width of the div it is within.

  <core-image class="sized gray" sizing="contain"
              preload fade src="Koala.jpg">
  </core-image>

Sizing this with absolute dimensions is fine, eg
.sized {
  width: 200px;
  height: 200px;
}

However, sizing with auto or 100% height will cause it not to render,
.sized {
  width: 200px;
  height: auto;
}

Removing the sizing="contain" fixes this issue somewhat however I'm using it's functionality.
What am I doing wrong, or what can I do to enable dynamic height based on width?

A: Setting width/height to auto/percentage does not cause it not to render. It causes it to have zero size.

*

*sizing= involves no magic behind, it simply sets the background-size property of the core-image's host.

*Once set, it forces core-image to render another template. That's why not specifying sizing seems to solve an issue.

*Custom elements have still the limited support even in modern browsers. That said, auto for width/height is working uhmmm... not always as expected (at least in my experience).
There is a possibility to set w/h to percentage value, though. To do so, one should explicitly set the size of the nesting container:
  <template>

      <core-image class="sized gray" sizing="contain"
                  preload fade src="Koala.jpg">
      </core-image>

  </template>

Live preview: http://plnkr.co/edit/7NhNwq6IgigBmiRhI58V?p=preview
Hope it helps.


text:
Q: Fractional Factorial Design with Highest Resolution In  the book Design and Analysis of Experiments by Douglas C. Montgomery , it is written that

We usually like to employ fractional designs that have the highest possible resolution consistent with the degree of fractionation required.

But the situation described here is a $2^{5-2}$ design of resolution $3$.

*

*Can't i also do $2^{5-1}$ design of resolution $5$ ?

If so , then my condition of minimum number of runs doesn't satisfy.
And if i don't do $2^{5-1}$ design of resolution $5$, then the condition of to employ fractional designs that have the highest possible resolution consistent with the degree of fractionation required doesn't satisfy.
Is that really  horns of a dilemma or i am doing wrong to understand.


text:
Q: Stripping variable names from VB.Net assemblies I'm trying to reduce as much as I can my VB.Net assembly side, and I just figured out that all variable names were kept unchanged in the actual assembly. Since I tend to use pretty long var names, it adds up and, by running dotfuscator on my assembly, I could shrink it by as much as 10%.
Thus I wonder: is there any way to tell Visual Studio to use shorter var names in the generated assembly? Are there any downsides to using dotfuscator (I'd rated avoid it though, since it'd need to be called after every compilation, therefore forcing me to update my build scripts...)?
Thanks a lot,
CFP.

A: You could buy a .NET Obsfucator that does compression:
http://www.xenocode.com/Obfuscator/

A: No.  It's actually not safe to change names without any guidance.  Renaming can break code, especially if you're using Reflection.
Visual Studio always goes for safety.  If you want to re-name your variables, you could add obfuscation to the build scripts to have them automatically redone each build.
That being said, once the assembly is compiled at runtime by the JIT, it won't matter.  The only advantages of obfuscating and using shorter names are a slightly smaller assembly, which may (slightly) improve your load times, but shouldn't matter much for runtime.


text:
Q: How to play/pause html5 video with spacebar How do you pause an html5 video with the spacebar using e.key? There's something off about the logic...

                    <video id=v-5417-tape preload="none">
                        <source type="video/mp4" src="videos/anthem-od47.mp4">
                        <source type="video/webm" src="videos/anthem-od47.webm">
                    </video>

JS
$( document ).on( 'keydown', function ( e ) {
            if ( e.keyCode === 32 ) {
                if (video.paused == true) {
                    // Play the video
                    video.play();
                }else{
                    if(video.play == true){
                    video.pause();
                    }
                }
            }
        });

A: Use e.preventDefault() to stop the scrolling of the web page to bottom.
var vid=document.getElementById('your_video_id_goes_here');

   document.body.onkeypress = function(e){
   if(e.which == 32){
 // stops default behaviour of space bar. Stop page scrolling down
    e.preventDefault();
    play_pause_video
  }
}

function play_pause_video() {
 if (vid.paused)
 {
  vid.play();
}
else
{
 vid.pause();
}
}

A: Here's the changes to your javascript:

$(window).keypress(function(e) {
  var video = document.getElementById("vid");
  if (e.which == 32) {
    if (video.paused)
      video.play();
    else
      video.pause();
  }
});

A:

var videoPlayer = document.getElementById('Video1')
$(window).keypress(function(e) {
  if (e.keyCode == 0 || e.keyCode == 32) {
 if (videoPlayer.paused == false) {
            videoPlayer.pause();
            videoPlayer.firstChild.nodeValue = 'Play';
        } else {
            videoPlayer.play();
            videoPlayer.firstChild.nodeValue = 'Pause';
        }

  }
});
<!DOCTYPE html>

Video

    <video id="Video1" autoplay="yes">
      <source src="videoName.mp4" type="video/mp4" />
    </video>

A: Here you go, this should work.
// Press spacebar to Play/Pause.
    var body = $( 'body' );

    body.keypress( function ( e ) {
        if ( e.which == 32 ) {
            // Stop the jerk.
            e.preventDefault();

            // If video is paused.
            if ( theVideo.get(0).paused == true ) {
                theVideo.get(0).play();
            } else {
                theVideo.get(0).pause();
            }
        }
    }); // End keypress().


text:
Q: Sqlite Browser NOT opening on Centos 6.5 When I try to open an .exe file in centOS (Release 6.5) by double clicking, it is not opening. I am creating an app which requires databases. I cannot check whether the data has gone in database or not because of this.I think may be some silly settings are blocking it. Any help appreciated.

A: You might try the Linux version of the software instead of the Windows version. The project website has the source, and I found a tutorial that should work for CentOS 6.5. Otherwise, to run a Windows executable on a non-Windows O/S, you might have success using WINE.
Or, there are other GUI database browsers like Valentia. You want the RPM package for use with CentOS.


text:
Q: How to install browser on Bluemix Pipeline Test Stage? I have a Node 8, Angular 6 application that I will be deploying with the Bluemix Pipeline. In the pipeline, I have set up Mocha tests for the back end and the front end. I now want to write e2e tests, but I can't figure out how to install a browser on the test stage, which runs Ubuntu 14. The closest I got was:
wget https://dl.google.com/linux/direct/google-chrome-
stable_current_amd64.deb
ar -x ./google-chrome*.deb
tar xf data.tar.xz
export CHROME_BIN=usr/bin/google-chrome-stable

But I got the following error:
15 06 2018 16:56:41.566:WARN [launcher]: Chrome have not captured in 60000 ms, killing.
15 06 2018 16:56:43.569:WARN [launcher]: Chrome was not killed in 2000 ms, sending SIGKILL.
15 06 2018 16:56:45.572:WARN [launcher]: Chrome was not killed by SIGKILL in 2000 ms, continuing.


text:
Q: how to remove dummy permission in Files and Folders on Security and Privacy? I've installed Adobe Creative Cloud and removed few days ago,
but it still remains 'com.adobe.acc.installer.v2' on Files and Folders permission.
How can I remove this?
I even cannot find this file on my mac.
Waiting for your intelligence.
Thank you.

A: Solution
1. Delete the following files :

*

*/Library/PrivilegedHelperTools/com.adobe.acc.installer.v2

*/Library/LaunchDaemons/com.adobe.acc.installer.v2.plist

or

*

*/System/Volumes/Data/Library/PrivilegedHelperTools/com.adobe.acc.installer.v2

*/System/Volumes/Data/Library/LaunchDaemons/com.adobe.acc.installer.v2.plist

2. Open Terminal and execute the bellow command :
sudo tccutil reset SystemPolicyDesktopFolder

3. Reboot
P.S. If com.adobe.acc.installer.v2 has access to other locations, the guide for using tccutil bellow :
sudo tccutil reset CATEGORY

CATEGORIES :

*

*Accessibility

*AddressBook

*AppleEvents

*Calendar

*Camera

*Microphone

*Photos

*Reminders

*ScreenCapture

*SystemPolicyAllFiles

*SystemPolicyDesktopFolder

*SystemPolicyDeveloperFiles

*SystemPolicyDocumentsFolder

*SystemPolicyDownloadsFolder

*SystemPolicyNetworkVolumes

*SystemPolicyRemovableVolumes

*SystemPolicySysAdminFiles

Best,
Elie


text:
Q: Restore Window Control in Gnome Shell So I tested elementary OS
I don't like it so I removed it
I switch back to gnome but left me with elementary os style windows control. which has close in left and maximize in right.
I decided to run this command
gsettings set  org.gnome.desktop.wm.preferences button-layout 'close,minimize,maximize:'

Now it ruins everything. So, I probably just explain it in screenshots:

A: Open Terminal and run the following command to switch back to elementary OS default (close button on the left and maximise button on the right)
gsettings set org.gnome.desktop.wm.preferences button-layout close:maximize

or the following command to Ubuntu default (minimise, maximise and close on the right)
gsettings set org.gnome.desktop.wm.preferences button-layout :minimize,maximize,close

However, it seems the issue is with the Arc-Darker GTK+ theme that you're using. Change it to another theme (e.g. Adwaita) to fix the problem.


text:
Q: override reformatting in forms by webmaster? I'm at a website, trying to complete an important form for work.  The webmaster created a form that reformats the phone number to add a "-", but the form does not accept submissions of phone numbers with dashes!  Is there a way to override the stupid site and skip the reformatting?

A: Yes! Just Use Ctrl+Shift+K in Firefox or Ctrl+Shift+I in Chrome.
Then at the topleft there is an arrow(firefox) or magnifier(chrome). Click on it and hover over the desired element (form field) then click on that. The Inspector should now shows you the code of form element like:
<input type="number(Or STH)" name="STH" value="STH" />

The value="" is the important part. double click on it and enter information between " and " . Then close the inspector and send the form using regular submit button.
Note: If there is not a value option you should add it by RightClicking on it and choose Edit as HTML then add value="" and other stuff ....
CHEERS! And Shame on that nooooooob webmaster ....


text:
Q: My rails 3 applicaiton has to have a subdomain to work, my rspec controller test are failing I am using lvh.me:3000 which redirects to localhost, and allows me to have wildcards like:
test.lvh.me:3000
In my application_controller, I make sure there is a subdomain in the url, and looking the subdomain in the database also.
If there is no subdomain, I redirect to an error page.
Because of this, my rspec controller tests are failing because the tests don't have a subdomain.
How can I make the get 'index' calls to use a subdomain that I know exists in the test db?

A: To get around this I do the following:
# spec/support/spec_helper_methods.rb
def require_subdomain
  @subdomain = # however you establish subdomains in you app
  controller.expects(:current_subdomain).returns(@subdomain)
  @request.host = "#{@subdomain}.test.host"
end

and then in my specs:
describe UsersController do

  describe "GET /users/new" do

    before do
      require_subdomain
    end

  end

end

Note - I'm using Mocha here, hence the expects() and returns() methods.
In my controller, I ask for current_subdomain() and raise a 404 if there isn't one


text:
Q: Prove that $IntCl(A)$ is regular open A set $A$ is said to be regular open if $IntCl(A)=A$
I am trying to prove that $IntCl(A)$ is regular open for any $A\subseteq X$
One of the inclusions is direct,
$Int(Cl(A))\subseteq Int(Cl(Int(Cl(A))))$
I have problems proving the inverse inclusion.

A: As Daniel Schepler marked, $Int(Cl(A))\subseteq Cl(A)$. This is due to the fact that $Int(A)\subseteq A\subseteq Cl(A)$. So, if we substitute $Cl(A)$ by $A$, $$Int(Cl(A))\subseteq Cl(A)\subseteq Cl(Cl(A))=Cl(A)$$ As a consequence,$$Int(Cl(Int(Cl(A))))\subseteq Int(Cl(Cl(A)))=Int(Cl(A)),$$ as you wanted to prove.

A: $$Int(Cl(A))=Int(Int(Cl(A)))\subseteq Int(Cl(Int(Cl(A))))\subseteq Int(Cl(Cl(A)))=Int(Cl(A))$$


text:
Q: rails contact management webapp design help maybe the rails pros here can help me with the software design of a contact management web app.
i want to create Groups, where I can add Contacts to. I thought I generate a Group scaffold and a Contact scaffold with
group:references

Then I the models to
Group: has_many :contacts
Contact: belongs_to :group

I also set the routes to
resources :groups do
  resources :contacts
end

The whole thing should then be accessible over the groups controller, the contact views get included as partials.
Is that the right way? Or would you do it another way?
Thanks + regards

A: If you want a contact to be in only one group at a time, that would be ok. To have a contact in more than one group at a time, I'd recommend a has_and_belongs_to_many association.
# group.rb
class Group < ActiveRecord::Base
  has_and_belongs_to_many :contacts
  …
end

# contact.rb
class Contact < ActiveRecord::Base
  has_and_belongs_to_many :groups
  …
end

You can also use the nested routes bidirectionally e.g.
# routes.rb
resources :groups do
  resources :contacts
end

resources :contacts do
  resources :groups
end

which would give you both /groups/15/contacts and /contacts/43/groups.


text:
Q: How to run Java code using Java code? Basically, I want to do two things:

*

*I want to know if there is any way that I can run Java code using Java code.

*If it is possible, how would I show the output on my screen? (be it regular output or error or exception)

I know this is possible because one of my seniors had done it, but I don't know how he did it. Maybe he used one of Java's built-in classes.
Note: user will write the code in some text file and then I will store that file content in some variable and then maybe run that code.

A: Yes, it is possible.
Step 1: Compile the Code
Use ProcessBuilder or Runtime to construct a Process in which the Java compiler compiles their code. (Note that this requires that a Java compiler be available on the system at runtime).
Step 2: Invoke their Code
There are two ways to invoke their code. You can again use a ProcessBuilder or Runtime object to construct a process in which you execute their Java code. You can use the Process's getInputStream and getOutputStream functions to read from and write to the other process. An alternative is that you can use Class and the various reflection APIs to load their code and execute it directly within Java.

A: You would have to some how invoke a compiler (such as Suns javac), parse its output in case of errors and load the resulting classes dynamically.
There is no API-classes in the Java runtime library that will parse, compile and run Java source code.

A: If you want an interpreter (so, no compiling required) for Java, take a look at BeanShell.
I like this one very much!

A: You can use a scripting language running on top of the JVM. Groovy is a very good idea and it has very similar syntax compared to Java.


text:
Q: About console error "Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)" in Jest I have problems about Jest.
This error happens when I execute "Table.test.js".
So I searched this error and found this post unit test raises error because of .getContext() is not implemented
And then I imported "jest-canvas-mock" and add "jest" in Package.json to the following in accordance with https://www.npmjs.com/package/jest-canvas-mock.
But It wasn't resolved.
Please tell me how to resolve.

Package.json
{
  "name": "react-frontend",
  "jest": {
    "setupFiles": [
      "jest-canvas-mock"
    ]
  },
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "material-table": "^1.69.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/react": "^11.2.2",
    "jest-canvas-mock": "^2.3.0",
    "jest-dom": "^4.0.0",
    "react-test-renderer": "^17.0.1"
  }
}

Table.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import { Table } from '../../Table';
import 'jest-canvas-mock';

describe('Table', () => {
    test('renders App component', () => {
        render(
);
    });
});

Table.js
import React from 'react';
import MaterialTable from 'material-table';
import CheckListService from '../services/CheckList';
import { useEffect } from 'react'
import { useState } from 'react';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import Box from '@material-ui/core/Box';
import { makeStyles } from '@material-ui/core';

const localizationJapanese = {
    error: "エラー",
    body: {
        emptyDataSourceMessage: "表示するレコードがありません。",
        filterRow: {
            filterPlaceHolder: "",
            filterTooltip: "フィルター",
        },
        editRow: {
            saveTooltip: "保存",
            cancelTooltip: "キャンセル",
            deleteText: "この行を削除しますか?",
        },
        addTooltip: "追加",
        deleteTooltip: "削除",
        editTooltip: "編集",
    },
    header: {
        actions: "アクション",
    },
    grouping: {
        groupedBy: "グループ化:",
        placeholder: "ヘッダーをドラッグ ...",
    },
    pagination: {
        firstTooltip: "最初のページ",
        firstAriaLabel: "最初のページ",
        previousTooltip: "前のページ",
        previousAriaLabel: "前のページ",
        nextTooltip: "次のページ",
        nextAriaLabel: "次のページ",
        labelDisplayedRows: "{from}-{to} 全{count}件",
        labelRowsPerPage: "ページあたりの行数:",
        lastTooltip: "最後のページ",
        lastAriaLabel: "最後のページ",
        labelRowsSelect: "行",
    },
    toolbar: {
        addRemoveColumns: "列の追加、削除",
        nRowsSelected: "{0} 行選択",
        showColumnsTitle: "列の表示",
        showColumnsAriaLabel: "列の表示",
        exportTitle: "出力",
        exportAriaLabel: "出力",
        exportCSVName: "CSV出力",
        exportPDFName: "PDF出力",
        searchTooltip: "検索",
        searchPlaceholder: "検索",
        searchAriaLabel: "検索",
        clearSearchAriaLabel: "クリア",
    },
};

function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {'Copyright © '}
            <Link color="inherit" href="https://material-ui.com/">
                株式会社ウィラム. All rights reserved.
        </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

const useStyles = makeStyles({
    root: {
        marginTop: '100px',
        marginBottom: '100px',

    }
});

export const Table = () => {
    const classes = useStyles();
    const [dataAll, setDataAll] = useState([]);
    useEffect(() => {
        CheckListService.getList().then((response) =>
            setDataAll(response.data)
        )
    }, [])

    const columns = [
        {
            title: 'リスト番号', field: 'listNo'
        },
        {
            title: '採用日', field: 'saiyouDate'
        },
        {
            title: 'バージョン', field: 'version'
        },
        {
            title: '種別', field: 'shubetu'
        },
        {
            title: 'ライセンス', field: 'licenseManage'
        },
        {
            title: '用途', field: 'youto'
        },
        {
            title: '備考', field: 'bikou'
        },
        {
            title: '承認者', field: 'authorizer'
        },
        {
            title: '承認日', field: 'approvalDate'
        },
        {
            title: 'URL', field: 'url'
        }
    ]
    return (

                    <MaterialTable
                        title="使用許可ソフトウェアリスト"
                        data={dataAll}
                        columns={columns}
                        style={{
                            marginTop: '50px',
                            whiteSpace: 'nowrap',
                        }}
                        options={{

                            headerStyle: {
                                backgroundColor: '#75A9FF',
                                color: '#FFF'
                            }

                        }}
                        localization={localizationJapanese}
                    />

            <Box pt={4}>
                <Copyright />
            </Box>

    )

}

PS:Is this correct?
This error show up in Console.

We detected setupFilesAfterEnv in your package.json.
Remove it from Jest configuration, and put the initialization code in >src/setupTests.js.
fThis file will be loaded automatically.
setupTest.js

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import 'jest-canvas-mock';

const localStorageMock = {
    getItem: jest.fn(),
    setItem: jest.fn(),
    removeItem: jest.fn(),
    clear: jest.fn(),
};
global.localStorage = localStorageMock;

Package.json
{
  "name": "react-frontend",
  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ]
  },
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "material-table": "^1.69.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/react": "^11.2.2",
    "jest-canvas-mock": "^2.3.0",
    "jest-dom": "^4.0.0",
    "react-test-renderer": "^17.0.1"
  }
}


text:
Q: Subversion large repos import/checkout My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there?

A: I agree on  the  "in-place import" procedure and also using a script for TTB-structure(upvoted both).
Just a small hint:
You should not import a huge (ten of thousands) number of files in a single commit, if you use http(s), as the time for displaying the version history scales by the number of added entries. The reason for this behaviour is that apache has to authenticate all added paths agains the svnaccess file(of course, only if you enabled path-based authorization). This can render your repository unusable, as all files will have to wait on a svn log for this big rev.
You should divide huge imports on directory levels

A: I usually use "svn mkdir" to create the trunk/tags/branches directly on the server immediately after creating the repository. Then I can check out the empty trunk, move my initial files into that directory, add and commit them, and start working.

A: svn checkout --force lets you checkout a  workingcopy 'over' an existing path. It keeps your old files and adds files that are only in your repository.
For creating your repository: You can perform multiple mkdir commands to a repository in a single commit using the 'svnmucc' command that is available in most Subversion distributions (e.g. SlikSVN).
Type svnmucc without arguments for some help.

A: There is - it's called an "in-place import", and it's covered in the Subversion FAQ here:
http://subversion.tigris.org/faq.html#in-place-import
What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit.

A: If you've checked out a single folder, copied your files into it, run svn add and svn commit;  you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on.


text: Q: how refraction takes place at atomic level? when light beam is incidented at some angle on the surface of a medium some part of the light is reflected and some refracted. I want to know about refraction. As the photons interact with the atom and get reemitted in all the directions, how the photons know to a particular angle they should refract?


text:
Q: PHP Tournament Bracket System Happy new year to all!!
I'm trying to make starcraft 2 tournament web site for me and friends.
i stuck on tournament system.
I have a jquery script that makes a bracket but I couldn't figure out how can I implament it with my database and php:(
I would like to ask you some questions please.
I have this html and jquery script.
my mysql database is like this
tournamenttree

id - UserID - TournamentID - Round

1        - 1              - 1                 -  1
2        - 15            - 1                 -  1
3        - 17            -  1                - 1
4        - 25            - 1                  - 1

and
tournaments

id - tournamentname - createdtime - players - active

1        -Sunday Cup    -  time()          -       4   -     1

and Users table
 <?php
$link = mysql_connect( '', '', '' );
if ( !is_resource( $link ) ) die( 'MySQL Connect Error' );
if ( !mysql_select_db( 'db6968_game', $link ) ) die( 'MySQL DB Error' );
 mysql_query( "SET CHARACTER SET UTF8" );
mysql_query( "SET collation_connection = 'utf8_turkish_ci'" );

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <title>MyTournamentName</title>

blah blah blah

blah blah blah

I tried to do this
    <?php
 function getusername($id){
             $sql = mysql_query("SELECT * FROM users WHERE UserID = '".$id."'");
             $ROW = mysql_fetch_assoc($sql);
                 $data = $ROW['Username'];

             return $data;
         }
         ?>

             var matchInfo = {
             "rounds" : [
        { "name": "Round1", "matches" : [
        <?php

for ($i = 0; $i < $num_rounds; ++$i)
   {
    $matches = $teams * pow(.5, $i - 1) / 2;
    $ROW = mysql_fetch_array($sql);
    for ($j = 0; $j < $matches; ++$j)
    {

        echo '{ "id" : '.$j.', "p1" : "'.$ROW['UserID'].'", "p2" : "'.$ROW['UserID' + $j - 1].'" }';
        echo $coma = ',';
      }
      echo $coma= '';
   }?>

but it gives me this
 var matchInfo = {
             "rounds" : [
        { "name": "Round1", "matches" : [
        { "id" : 0, "p1" : "1", "p2" : "" },{ "id" : 1, "p1" : "1", "p2" : "2" },{ "id" : 2, "p1" : "1", "p2" : "1" },{ "id" : 3, "p1" : "1", "p2" : "1" },{ "id" : 0, "p1" : "15", "p2" : "" },{ "id" : 1, "p1" : "15", "p2" : "3" },{ "id" : 0, "p1" : "17", "p2" : "" },
          ]
        },

according to my database there are 4 teams but with my php script it gives me 7 matches. it should be only 2 matches. cos there are 4 teams.
i just cannot figure out this. is there anyone can give me an idea or help me please? thanks


text:
Q: How do I capture stylus event in Honeycomb? I've been trying to capture MotionEvents that are from the stylus and I want to filter out those events that non-stylus. However, every event that comes in is a pointer event SOURCE_TOUCHSCREEN (4098). How can catch the ones I want which are SOURCE_STYLUS (16386)? API 14 ICS is nice that I can check for the event's tool type but it's not available to me in Honeycomb API 11-13.
Thx,
-mL

A: To distinguish whether a MotionEvent is derived from a human thumb or a TPT's pen, Volker polls MotionEvent.getTouchMajor(). If a fatty finger touches the screen, the diameter of the ellipse will be > 0. If it's an anorexic digitizer pen, it will be 0.0f.


text:
Q: MongoDB database design for products and bundles I am trying to build an e-commerce website based on Node.js with a mongoDB database and I am encountering problems about some database design or some logic I am missing
To sum up, I have Product that contain price, name, description etc... and Bundle that contains an array of products (by reference). The main problem come when I have to order, I can't get Product AND Bundle together ...
So I have already a Product schema :
const productSchema = new mongoose.Schema({
  file: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  preparation: String,
  allergics: {
    type: Array,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  // More fields
});

module.exports = mongoose.model('Product', productSchema);

And a Bundle schema that contains ref to Product (A bundle contains multiple products) :
const bundleSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  itemsId: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: true,
  }],
  description: String,
  reduction: {
    type: Number,
    min: 0,
    default: 0,
    max: 100,
  },
});

module.exports = mongoose.model('Bundle', bundleSchema);

So when a user orders a bundle OR a single product, I use this schema :
const orderSchema = new mongoose.Schema({
  orderedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  articlesId: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Product',
    },
  ],
  itemsNumber: {
    type: Array,
    required: true,
  },
  amount: Number,
  orderedAt: Date,
  placeToShip: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Place',
  },
});

module.exports = mongoose.model('Order', orderSchema);

As you can see, I only reference to Product , but I want to reference to Product AND Bundle , I don't know if this is possible, or if this is the wrong way to design the database like that.
Sorry if the post is a bit long, but I am trying to be as clear as possible! Thanks a lot.

A: if you want to reference product or bundle(depending on user buys bundle or single product) in articleId, you can do it like this:
Dont give ref in the articleId field of your orderSchema, just specify its type as ObjectId.
const orderSchema = new mongoose.Schema({
  ...
  articlesId: [
    {
      type: mongoose.Schema.Types.ObjectId
    },
  ],
  ...
});

And, while populating tell it which model to populate from.
//In case user bought a product
Order.find({findQuery})
     .populate({path : '',model : 'Product'})
     .exec(function(err,result){...});

//In case user bought a Bundle
Order.find({findQuery})
     .populate({path : '',model : 'Bundle'})
     .exec(function(err,result){...});

But, you must have a way to find out user bought a single product or a bundle.
Hope that helps you!


text:
Q: making captcha image indetated in php how can i make the captcha image produced by this script indententer code hereed or italic or twisted like?
<?php
session_start();
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
$captchanumber = substr(str_shuffle($captchanumber), 0, 5);
$_SESSION["code"]=$captchanumber;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5,5,5,  $captchanumber, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

A: By loading in a custom font, you can skip all the "hard" parts by manipulating the font manually.
$font = imageloadfont('./myfont.gdf');
imagestring($im, $font, 5, 5, $captchanumber, $fg);

You can download custom fonts at various websites, such as;

*

*https://www.acidfonts.com

*http://www.dafont.com/
But make sure you check their licensing terms.


text:
Q: How to migrate a Maven based web application POM to use Gradle? Yes, yes, I know! There are hundreds of Maven-to-Gradle related questions here on SO, but none of them, AFAICT addresses the inherent difficulties (of a constantly moving target [Gradle!]) of porting a very simple Maven POM to use Gradle for compilation.
In this particular case, we have an app the original developers are relying on using the GWT plugin for Eclipse, but that many other developers would like to use something more modern and less bloated, i.e. Gradle. All sources simply brush this off to, "you can simply convert pom.xml in Gradle", as is stated in the Gradle documentation, unfortunately this is simply not working for most practical purposes.
The project under consideration is circuitJS1 which was ported to use Maven here. The resulting pom.xml reads:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lushprojects.circuitjs1</groupId>
    <artifactId>circuitjs</artifactId>
    <version>2.1.15</version>
    <packaging>gwt-app</packaging>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.google.gwt</groupId>
                <artifactId>gwt</artifactId>
                <version>2.8.2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- generating dependency report is slow; disable it -->
        <dependency.locations.enabled>false</dependency.locations.enabled>
    </properties>
    <dependencies>

        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-dev</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId> <!-- artifact with sources is easier to handle during development -->
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!-- declaring only in order to skip during site deployment -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.7</version>
                <executions>
                    <execution>
                        <id>deploy</id>
                        <phase>deploy</phase>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <skip>true</skip>
                    <siteDirectory>site</siteDirectory>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.9</version>
                <configuration><!-- we don't need those reports; disabling speeds up
                        build -->
                    <dependencyDetailsEnabled>false</dependencyDetailsEnabled>
                    <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
                </configuration>
            </plugin>

            <!-- gwt compiler -->
            <plugin>
                <groupId>net.ltgt.gwt.maven</groupId>
                <artifactId>gwt-maven-plugin</artifactId>
                <version>1.0-rc-9</version>
                <extensions>true</extensions>
                <configuration>
                    <moduleName>com.lushprojects.circuitjs1.circuitjs1</moduleName>
                    <!-- this is the best setting for a laptop with 2 cores and HT -->
                    <localWorkers>0.5C</localWorkers>
                    <warName>circuitjs</warName>
                    <optimize>9</optimize>
                    <compilerArgs>
                        <compilerArg>-style</compilerArg>
                        <compilerArg>PRETTY</compilerArg>
                    </compilerArgs>
                    <codeServerPort>8888</codeServerPort>
                </configuration>
            </plugin>

            <!-- copy a few things around before packaging the website -->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/site</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>war</directory>
                                </resource>
                                <resource>
                                    <directory>${project.build.directory}/${project.name}-${project.version}/circuitjs1</directory>
                                    <targetPath>circuitjs1</targetPath>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Cloning that repository and simply doing: mvn install will give you a working (circuit simulation) website, that you can open with your browser, under the file location:
file:///C:/path/to/circuitjs1/target/site/circuitjs.html
However, using gradle init --type pom to convert to Gradle, yield a build.gradle like this:
/* This file was generated by the Gradle 'init' task. */
plugins {
    id 'java'
    id 'maven-publish'
}
repositories {
    mavenLocal()
    maven {
        url = 'http://repo.maven.apache.org/maven2'
    }
}
dependencies {
    compile 'com.google.gwt:gwt-user:2.8.2'
    compile 'com.google.gwt:gwt-dev:2.8.2'
}
task sourcesJar(type: Jar) {
    classifier = 'sources'
    from(sourceSets.main.allJava)
}

group = 'com.lushprojects.circuitjs1'
version = '2.1.15'
sourceCompatibility = '1.8'

publishing {
    publications {
        maven(MavenPublication) {
            from(components.java)
            artifact(sourcesJar)
        }
    }
}
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

Unfortunately, using that with gradle build, doesn't seem to yield anything that can be ran in the browser. It does generate ./build/ directory but which contents are not of any use at all.
build
├── classes
│   └── java
│       └── main
│           └── com
├── generated
│   └── sources
│       └── annotationProcessor
│           └── java
├── libs
│   └── circuitjs-2.1.15.jar
└── tmp
    ├── compileJava
    └── jar
        └── MANIFEST.MF

I have also tried to beat this file into shape by adding things like:
//id 'com.gradle.build-scan' version '2.2.1'
id 'java'
id 'maven'
//id 'gwt-maven'
id 'maven-publish'
id 'war'
//id 'org.metahelicase.site-builder' version '1.1'
//id 'org.jbake.site' version '5.0.0'
//id 'gradle.site' version '0.6'
//id 'com.stehno.gradle.webpreview' version '0.3.0'

But to no avail...

*

*How can I make this build.gradle script work correctly to produce the web files necessary to run the application locally in my browser?

*Are there any up-to-date tools available that can do this for you?

A: The problem was that because the Maven build file (pom.xml) had so many plugins in it, that I was thinking they were needed also in Gradle. That is a big mistake because Gradle's build.gradle file only need minimal plugin info. The rest is downloaded and used automagically.
In my case it only needed the Gradle version of GWT, the gwt-gradle-plugin plugin.
The corrected and hugely simplified build.gradle becomes:
// This must be before plugins!
buildscript {
    repositories {
      mavenCentral()
    }
    dependencies {
        classpath "org.wisepersist:gwt-gradle-plugin:1.0.8"
    }
}

plugins {
    id 'java'
}

repositories {
    mavenLocal()
    maven {
        url = 'https://plugins.gradle.org/m2/'
        url = 'http://repo.maven.apache.org/maven2'
    }
}

dependencies {
    implementation 'com.google.gwt:gwt-user:2.8.2'
    implementation 'com.google.gwt:gwt-dev:2.8.2'
}

apply plugin: 'gwt-compiler'
...

Now you can just run:
gradle compileGwt --console verbose --info
and all files will be built in the ./build directory.


text: Q: Matlab VPA slowness I am writing a program to decrypt RSA-encrypted messages by factorising the prime number and I want to test it on some long primes so I need to use Variable Precision Arithmetic, but for some reason even when I use small numbers it is significantly slower when I use VPA with a small number of digits. What is going on?


text:
Q: Application is not shown in Recent Apps list when opened via PendingIntent My app offers a widget. User can add the widget to the home screen of his Android OS. When the user taps the widget my app gets opened.
The issue is: when run so, the app is not shown in the Recent Apps list.
How can I make my app to shown in the Recent Apps list regardless of how it was opened?
Here is the intent used to open the app:
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_contents, pendingIntent);

Here is the declaration of the activity in the app's manifest:
<activity
    android:name=".MainActivity"
    android:label="@string/title_activity_browse_playlist"
    android:screenOrientation="portrait"
    android:configChanges="orientation|keyboardHidden"
    android:launchMode="singleTop">
</activity>


text:
Q: Android DataBindingClasses are not updating immediately Problem:
I'm working on a project having dataBinding integrated now whenever I create a new layout or add a view to an existing one it just not appear in binding object and I even try rebuilding and cleaning the project but it doesn't work and I have to just restart the project or rename the layout file one or two times to update the BindingClass. It is so annoying and consuming my important time.
Code
build.grade
dataBinding {
    enabled = true
}

layout_file
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <RelativeLayout
        android:id="@+id/lyt_parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <View android:id="@+id/old_view_1" .../>
        <View android:id="@+id/old_view_2" .../>

        <!-- New View -->
        <View android:id="@+id/new_view" .../>
    </RelativeLayout>
</layout>

Activity/Fragment/Place where layout is used
LayoutFileBinding binding = DataBindingUtil.setContentView(this, R.layout.layout_file);
binding.newView
// here I get error cannot resolve (newView) until i restart project or rename layout file

A: Data binding and platform support is still not so mature, I am using data binding from a long time, all the issues related to IDE are resolved but your problem happens most of the times with me too.
The most quick fix for me is

*

*File > Close Project

*Open from recent
This takes almost 5 second. and generates all newly added fields and layouts binding classes.
It is faster than Rebuild or Restart AS.


text:
Q: How can i position my Add Minus in form to stay same position in my input? I got some questions related to positioning I don't want to use a fixed position as my browser is dynamic, how can I move my + - to the right position of the contact: input (Position here)
I try many as it seems only ways is a position to be fixed is there another way to do it?
Here the image

  Contact:

    <input id="validationNumber" name="phonenumber" type="text" class="form-control" pattern="\b\d{8}\b" required>

    <input type="hidden" value="1" id="total_chq">

      Enter a correct PhoneNumber!

A:

.flex{display: flex;}

  Contact:

    <input id="validationNumber" name="phonenumber" type="text" class="form-control" pattern="\b\d{8}\b" required>

    +
    -

    <input type="hidden" value="1" id="total_chq">

      Enter a correct PhoneNumber!


text:
Q: Zero charge density, yet non-zero current density? I am reading about retarded potentials in Griffiths' Introduction to Electrodynamics, and came across the particular case of wires. Griffiths takes wires to be electrically neutral, therefore the retarded scalar potential is zero, which has an integrand proportional to charge density, which he has taken to be zero.
The retarded vector potential depends on the current density in the wire, which is non-zero. However, I recall that the current density $\textbf{J} = \rho \textbf{v}$.
Hence, my question is, how can we have a non-zero current density, but a zero charge density? Are the $\rho$'s different? The current density being constant in say the z direction, and zero charge density does not violate conservation of charge, but how do we reconcile this fact with the relationship between $\rho$ and $\textbf{J}$?
Is the charge density, found for instance in the Maxwell equation $\nabla \cdot \textbf{E} = \frac{\rho}{\epsilon_0}$ an 'overall' charge density which takes every charge into account, while the $\rho$ found in the expression for $\textbf{J}$ a 'mobile' charge density?

A: If the positive and negative charges are moving at different velocities, then their contributions to the current density will be different, even if their charge densities are equal and opposite.
For example, in a normal wire, we can usually model the electrons as moving and the positive charges as stationary (though this is material-dependent and in particular doesn't hold for semiconductors). The charge density of positive charges is $\rho$ and the charge density of electrons is $-\rho$, so the total charge density is $\rho-\rho=0$. But the electrons are moving at velocity $-\vec{v}$ (where $\vec{v}$ points in the direction of the electric field) and the protons are effectively stationary, so the total current density is $\rho\vec{0}-\rho(-\vec{v})=\rho\vec{v}$, which is nonzero. You can add the current densities like this because Maxwell's equations are linear, and therefore obey the principle of superposition.
For another example, suppose we somehow had a wire made out of electrons and positrons of equal charge density (neglecting annihilation or any of the more interesting physics that this would imply). When an electric field is applied to this wire, the positrons will move in the direction of the electric field and the electrons will move in the opposite direction. Since the electron and positron charge have the same absolute value, the magnitude of the force on each species will be the same, and they will move at the same speed. Once again, the charge density is zero, since the positrons have charge density $\rho$ and the electrons have charge density $-\rho$. For the current density, we define $\vec{v}$ to be pointing in the same direction as the electric field; then the positrons have charge density $\rho$ and are moving with velocity $\vec{v}$, and the electrons have charge density $-\rho$ and are moving with velocity $-\vec{v}$, so the total current density is $\rho\vec{v}-\rho(-\vec{v})=2\rho\vec{v}$. So even when the charge carriers move at the same speed, the current density can still be nonzero if their velocity vectors are pointing in different directions.

A: From a microscopic perspective $J=\rho v$ holds, but from a macroscopic perspective it can fail.
Consider two microscopic charge distributions, one with charge density and no velocity and the other with the opposite charge density and some velocity. The current of the first is 0, but the current of the second is non zero.
Maxwell's equations are linear, so to get the overall picture we can simply add the contributions from both charge distributions to get a macroscopic 0 charge density and nonzero current density.

A:
Is the charge density, found for instance in the Maxwell >equation ∇⋅E=ρ/ϵ0 an 'overall' charge density which takes >every charge into account, while the ρ found in the >expression for J a 'mobile' charge density?

In short, yes.
In the Gauss's law formula, we count all charges. The electric field  divergence will be zero only if the net change is zero.
In the current density formula, we count all charges that will move with a non-zero average velocity, when an electric field is applied, and thus will contribute to the electric current.


text:
Q: how do you unenqueue a single item from sidekiq Is there an a way to remove a single item (like this) from the enqueued "stack" of sidekiq:
irb(main):017:0> Sidekiq::Queue.all.first.first.methods
=> [:[], :delete, :args, :value, :klass, :item, :parse, :queue, :created_at, :jid, :latency, :display_class, :display_args, :enqueued_at, :to_json, :`, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :to_yaml, :to_yaml_properties, :blank?, :present?, :presence, :psych_to_yaml, :as_json, :acts_like?, :to_param, :to_query, :deep_dup, :duplicable?, :in?, :presence_in, :instance_values, :instance_variable_names, :with_options, :html_safe?, :is_haml?, :pretty_print, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :require_dependency, :unloadable, :require_or_load, :load_dependency, :try, :try!, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :kind_of?, :instance_variables, :tap, :method, :public_method, :singleton_method, :class_eval, :is_a?, :extend, :pretty_inspect, :define_singleton_method, :to_enum, :enum_for, :awesome_inspect, :awesome_print, :<=>, :===, :suppress_warnings, :=~, :!~, :eql?, :respond_to?, :freeze, :inspect, :display, :object_id, :send, :gem, :to_s, :ai, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :trust, :untrusted?, :frozen?, :!, :==, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

A: Found it
Sidekiq::Queue.all.first.first.delete


text:
Q: JavaScript regular expressions matching any alpha character with accents I'm trying to match any alpha character and any accented vowel - I'm using this regular expression

[a-zA-Z\ÁÉÍÓÚáéíóú]+$

But unfortunately it only matches the last word in any string I provide for example:

If I add the ^ symbol to the start of the expression it only selects the first C
To clarify I am hoping to select multiple words but omit the whitespace that is found between them.  Is this possible?
Any advice most welcome.
L

A: Maybe?
    \s*([a-zA-Z]*[ÁÉÍÓÚáéíóú][a-zA-Z]*)\s*

Regex with global option.
Screen in [http://gskinner.com/RegExr/]: http://coment.me/sTNE5RD

A: So, from your comments, I understand that you simply want a global replacement for any of these [a-zA-ZÁÉÍÓÚáéíóú] characters. Try this:
"Cúl do chinn".replace(/[a-zA-ZÁÉÍÓÚáéíóú]/g, "-");

More info on the /g modifier on MDN (search for "global match" string in the document).


text:
Q: Naive height of zero The naive height function of a rational number $x=\cfrac{m}{n}$ (in lowest terms) is defined as
$$H(x) = H\left(\frac{m}{n}\right) = \max\{|m|, |n|\} $$
However, $0$ can be denoted by $\frac{0}{1}, \frac{0}{2}, ...$
Then what's the value of $H(0)$?
Is it 1, or undefined?

A: It seems silly to post this as an "answer", but the OP asked me to do so.
The apparent ambiguity is resolved by noting that $0/2$ is not in lowest terms. In fact $\text{gcd}(0,2)=2$, while $\text{gcd}(0,1)=1$; so the height of $0$ is $1$.


text:
Q: $watch only firing on reload I have a page that has 3 sections. I'm using ui-router, and I'm using an abstract view to get the vehicle object.
In the second view, I need to compute a field based on the vehicle object, I'm using a $scope.$watch.
The problem that I have is that when the state changes to 'dashboard.home.vehicle_wizard.proof' the watch method is called once, but the vehicle is undefined, and it doesn't get hit a second time. If I reload the page tho, it gets hit.
any idea ?
  .state 'dashboard.home.vehicle_wizard',
      url: "vehicle"
      templateUrl: 'views/vehicle-wizard.html'
      controller: 'VehicleWizardCtrl'
      abstract: true

  .state 'dashboard.home.vehicle_wizard.info',
      url: "/info"
      templateUrl: 'views/vehicle-info.html'
      controller: 'VehicleInfoCtrl'

  .state 'dashboard.home.vehicle_wizard.proof',
      url: "/proof"
      templateUrl: 'views/vehicle-proof.html'
      controller: 'VehicleProofCtrl'

VehicleWizardCtrl :
angular.module 'App'
.controller 'VehicleWizardCtrl', ($scope, $state, vehicle) ->

    vehicle.get().then (result) ->
      if result
        $scope.vehicle = result[result.length - 1]

VehicleInfoCtrl:
$scope.submit = ->
  return if !$scope.form.$valid
  $scope.loading = true
  $scope.vehicle.status = "confirmed"
  $scope.vehicle.update()
  .then (vehicle) ->
    $scope.loading = false
    $scope.vehicle = vehicle
    $state.go "dashboard.home.vehicle_wizard.proof", $scope.vehicle
  , (resp, headers) ->
    $scope.loading = false
    _.each resp.data, (errors, key) ->
      if $scope.form[key]
        $scope.server_errors[key] = errors[0]
        $scope.form[key].$error["server"] = errors[0]
        $scope.form[key].$setValidity('server', false)

VehicleProofCtrl :
$scope.$watch('vehicle', (newValue, oldValue)->
  if ($scope.vehicle)
    $scope.vehicle.age = parseInt(moment($scope.vehicle.regDate, "YYYY-MM-DD").fromNow(true).match(/\d+/g))
)

A: use $watchCollection insted of $watch
$watchCollection watches the properties of an object and fires whenever any of the properties change (for array items and object maps, this implies watching the properties). If a change is detected, the listener callback is fired.
for further info read doc

A: You need to do a deepwatch for objects and that can be done by passing true as the 3rd parameter:
$scope.$watch('vehicle', (newValue, oldValue)->
  if ($scope.vehicle)
    $scope.vehicle.age = parseInt(moment($scope.vehicle.regDate, "YYYY-MM-DD").fromNow(true).match(/\d+/g))
, true)


text:
Q: Get name columns above table from database I've written code that will dynamically generate a table based on the result set of a query. Each field in each row gets placed in its own cell. How can I add the column names as headers over the appropriate column?
My code:
$db = new mysqli("...", "...", "", "...");
$query = "SELECT * from customer ";
if ($result = $db->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {
        printf("%s\n", $finfo->name);
    }
    $result->close();
}

$db = new mysqli('...', '...', '...', '...');
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * from ...";
if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
echo "
";
while($row = $result->fetch_assoc()){
echo "

                " . $row['COLUMN1'] . "
                " . $row['COLUMN2'] . "
               " . $row['COLUMN3'] . "
                " . $row['COLUMN4'] . "
               " . $row['COLUMN5'] . "
               " . $row['COLUMN6'] . "

";
}
echo "
";

?>

------------ picture problem solved-------------

A: You should only need to open 1 DB connection. You can use the fetch_field on the query you ran without iterating over the rows of the resultset. All the whitespace i'm adding is optional.
    $db = new mysqli("...", "...", "", "...");

    if($db->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
    }

    $sql = "SELECT * from ...";
    if(!$result = $db->query($sql)){
        die('There was an error running the query [' . $db->error . ']');
    }

    echo "

";
    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {
        echo "
        " . $finfo->name . "	";
    }
    echo "

";
    while($row = $result->fetch_assoc()){
    echo "

            " . $row['COLUMN1'] . "
            " . $row['COLUMN2'] . "
            " . $row['COLUMN3'] . "
            " . $row['COLUMN4'] . "

";
    }
    echo "

";


text:
Q: Big Query and Google Adwords (Ads): Country label I'm trying to find the corresponding label for the column CountryCriteriaId, the column is coming from p_GeoStats_*.
The schema description says that I can find the label in LocationCriterionService but as far I understand that's a Google Adwords API function rather a table in Big Query.
Do you know where can I find the labels inside the Adwords schema?

A: The labels are not inside BigQuery, they are located in what's called GeoTargets in the Adwords API.
Adwords provide a CSV with all the IDs in the following link


text:
Q: Print DevExpress Datagrid in custom format I want to print the data grid in the following format

Username
  Address
  City
  PinCode

Eg :

JohnSmith
  25,NewStreet
  New York
  75896

These are my datagrid columns columns
UserName, Address, City, PinCode
I am using SQL Server Compact Edition as my backend and DevExpress Product gridcontrol as my datagrid

A: Marina told me that she answered this question in the support center.  So, I will just post a link here for the community:
Print datagrid in custom format

A: Use DevExpress.VerticalGrig.VGridControl and you can get the requirements you want to view your data vertically.
Get your data from the Database as a datatable and set the datasource property value to the datatable.
For the VgridView you just have to add the rows and name or bound the rows with DataFieldName.


text:
Q: How to find group differences with irregularly measured, nested, and missing data? Background: I have a dataset, which consists of waterlevel measurements over time at different locations. However, the locations are irregularly measured in different years. Therefore my data consists of more gaps than actual data.
Additionally, some of my data is nested. That means that some of my measurements can be grouped under another measurement, while others are not.
How can I best test whether there is a difference between the waterlevels of various locations given these features of the data?

A: This is definitely a job for multilevel models (aka hierarchical models, mixed models and other terms). It's a big field, but the essential idea is to deal with non-independent data, which you have, certainly in terms of time and possibly place as well.
There are tools for this in SAS (PROC MIXED, NLMIXED or GLIMMIX, you probably want MIXED) and R (a couple of packages, such as nlme).


text:
Q: A kind of static variable in PHP I would want to display a certain message on a php page at a let's say 15 displayed pages. So it displays the message once and after 15 again and so on. I should need a varaible that keeps it's value between pages reload.
Can I do that with PHP?
thanks.

A: Store the value in session:

Session support in PHP consists of a
  way to preserve certain data across
  subsequent accesses. This enables you
  to build more customized applications
  and increase the appeal of your web
  site.

A: Alternatively to Andrew's answer:
If you want them to appear every 15 page views(not during a session) you have two options:

*

*storing a counter in a database or file(both options will give you a bad performance)

*using a statistical approach: generate a random number and by the chance of 1/15 display the message

A: If you only want the value shown to one user, then the session is the way to go. If for more than one user, you'll need store the message on the server side in a file, database, etc. That said, it's not clear from your question what you're trying to achieve.

A: for such a simple piece of data as a counter, you could use a cookie or session. Though session(without using query strings) requires cookies anyway..
If you must do this without cookies or this needs to be global to all users, then you can store it in a database or file.
if appropriate though, you could possibly get by with putting the counter in query string and taking it on to all the links to these 15 pages.

A: if you use something like memcached, you can store any value into it. it will work like very global and very static variable


text:
Q: Setting warning / critical thresholds in plugin-conf.d file I can set warning / critical thresholds in munin.conf (for a plugin that I've written) like this:
load_per_core.load_per_core.warning 0.2 # Low value to trigger warnings
load_per_core.load_per_core.critical 1

This works as expected, I see email notices and the right stuff on the graphs.
But I want to move these config items into a separate file so that I can more easily manage them across servers with Puppet. However when I move these two lines into a new file plugin-conf.d/zz-load_per_core like this:
[load_per_core]
env.load_per_core.warning 0.3 # Low value to trigger warnings
env.load_per_core.critical 1

...it doesn't work. No emails, nothing on the graphs.
I've guessed at the format of the lines starting env.load_per_core so maybe that's what's wrong?

A: tldr; Munin configuration key/value pairs are environment variables that are injected into a specific plugin's execution environment at runtime. They must be accessed from within the plugin's code like any other system environment variable.
Munin Plugin Execution
Each munin plugin is a standalone executable file. At runtime, Munin creates a separate environment for each plugin into which it injects variables that the plugin can reference. There are two groups of environment variables: munin core and plugin specific.
Tip: Use munin-run -d load_per_core to see what environment variables are being injected into your plugin's environment.
How to Define Environment Variables
Plugin specific environment variables are declared per plugin using the syntax:
#/etc/munin/plugin-conf.d/zz-name_of_your_plugin
[name_of_your_plugin]
env.identifier value

Which in your case would be:
#/etc/munin/plugin-conf.d/zz-load_per_core
[load_per_core]
env.load_per_core.warning 0.2

This creates an environment variable with identifier load_per_core.warning that has a value of 0.2 and injects it into the execution environment of the plugin named load_per_core.
Important: Restart munin-node for your changes to take effect:
sudo service munin-node restart

Where to Define Environment Variables
Plugin variables are defined in the directory /etc/munin/plagin-conf.d.
Munin creates a default config file at this location called munin-node its not recommended to edit this file because munin can overwrite it.
Instead, create a new file for each plugin. Which in your case could be /etc/munin/plugin-conf.d/zz-load_per_core. There are two things to think about when naming your plugin configuration file:

*

*The name is arbitrary in that it doesn't have to relate to your plugin name, it can be anything, but...

*Configuration files in this directory are evaluated in alphabetical order and definitions can overwrite each other. So enforce precedence for your configuration file by prefixing the name with zz to ensure it is evaluated after munin-node.

How to Access Environment Variables
Configuration environment variables can be accessed by your plugin's code like any other environment variable. The syntax for this depends on the language used by your plugin. for instance if your plugin was written in bash you could write:
#!/usr/bin/bash
#this would access and print the load_per_core.warning environment var
#i.e 0.2
echo $load_per_core.warning

or in Python:
#!/usr/bin/env python
import os
print os.environ.get('load_per_core.warning')

or in Perl, using the standard Munin library:
#!/usr/bin/perl
use Munin::Plugin;
print_thresholds('load_per_core');


text:
Q: How to read a file from remote system using java? I have a file copied in one computer and I need to access the file from other computer.
I am not sure, which protocol or which technology to use for this?
Please provide me any hints for this..
Update:
I am using Ubuntu Linux system.
I used the code :
File f = new File("//192.168.1.157/home/renjith/picture.jpg");// 192.168.1.157 is the ip of the computer, where I have the picture file
Image image = ImageIO.read(f);

But it is giving an exception:
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1275)

I have shared renjith folder also.

A: HTTP is an option.  However, if these are Windows machines on the same LAN, it would be easier to expose the directory on the remote machine via a file share and access the file through a regular file path.  Similarly, if these are Unix-like machines, you could use regular file paths if you're using NFS.  FTP's yet another option.

A: if the remote computer is in the same network and on a shared folder to the computer where your java code is running then try this piece of code for accessing it
File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");

here Comp-1 is the DNS name of the machine containing the file in the network!!!

A: You might try:
URL url = new URL("file://192.168.1.157/home/renjith/picture.jpg");
Image image = ImageIO.read(url);

A: You could try to mount that path first, and then load it. Do a :
subst x: \\192.168.1.157

and then:
File f = new File("x:\\home\\renjith\\picture.jpg");
Image image = ImageIO.read(f)

It should work.

A: There are any number of ways to access files on remote machines, but they virtually all depend on the remote machine having been set up to provide the file in some way first.  If you with to access files via java, the easiest method would probably be to set up an HTTP server on the remote machine (this can be done pretty easily using Apache HTTP server on a variety of platforms) and then using Apache Commons HTTPClient on the client side java app.  Further discussion of how to install these or configure them is generally beyond the scope of Stack Overflow and would at least require a more specific question

A: Share the directory and access the file thruogh java code
try this one:
File f = new File("//10.22.33.122/images")

File[] files = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        // Specify the extentions of files to be included.
        return name.endsWith(".bmp") || name.endsWith(".gif");
    }
});

// get names of the files
String[] fileNamesArray = null;
for (int indx = 0; indx < files.length(); indx++) {
    fileNamesArray[indx] = files[indx].getName();
}

return fileNamesArray;

A: Map your IP to  network drive and try   let us say the drive letter is X,
then code changes to File f = new File("x:\\home\\renjith\\picture.jpg");
Infact your file is already loaded in object f , try priting the value of the path f.getAbsolutePath() to console  and see.. Actual error is with ImageIO

A: You can read from remote and write to remote using jcifs-1.3.15.jar jar in java but first you need to share location from remote system then it's possible.
try{
            String strLine="";
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("WORKGROUP", "username", "passwd"); // Authentication info here, domain can be null
    //        try (InputStream is = new SmbFile("smb://DESKTOP-0xxxx/usr/local/cache/abc.txt", auth).getInputStream()) {
            try (InputStream is = new SmbFile("smb://xx.xx.xx.xxx/dina_share/abc.txt", auth).getInputStream()) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((strLine = br.readLine()) != null) {
                System.out.println(strLine);
            }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String smbURL="smb://xx.xx.xx.xxx/dina_share/abcOther.txt";
            SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL,auth));
            byte bytes[]="Wellcome to you".getBytes();
            fos.write(bytes);
        }catch(Exception e){
            e.printStackTrace();
        }


text:
Q: Iterating over arrays simultaneously using jq I'm describing the output I'd like to have using jq
Here my json file
{
  "partitions": [
    {
      "replicas": [
        0,
        1,
        2
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "replicas": [
        2,
        0,
        1
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
[...]

I would like, for every object in partitions[] to replace the value of the i th string in log_dirs[] by its concatenation with the i th number in replicas[] in order to have something like this
{
  "partitions": [
    {
      "replicas": [
        0,
        1,
        2
      ],
      "log_dirs": [
        "any0",
        "any1",
        "any2"
      ]
    },
    {
      "replicas": [
        2,
        0,
        1
      ],
      "log_dirs": [
        "any2",
        "any0",
        "any1"
      ]
    },
[...]

A: Use a reduce loop with a range
.partitions[] |= reduce range(0; ( .replicas | length ) ) as $r
  ( . ; .log_dirs[$r] += ( .replicas[$r] | tostring ) )

The reduce expression works by iterating over the entire log_dirs array upto the length of replicas list and modifying each entry .log_dirs[$r] (here r runs from 0 - length of replicas) by appending the corresponding value at replicas[$r]. Since replicas contains numerics, it needs to be converted to string for the append operation.
jqplay - demo

A: I'm not quite happy with this, but it does work:
jq '.partitions[] |= . + (
  . as $p | {
    log_dirs: [
      range(.replicas | length) |
      "\($p.log_dirs[.])\($p.replicas[.])"
    ]
  }
)' in.json


text:
Q: You could tell by his eyes that he was plastered to the hairline Here's from The Long Goodbye by Raymond Chandler (1953)

The first time I laid eyes on Terry Lennox he was drunk in a Rolls-Royce Silver Wraith
  outside the terrace of The Dancers. The parking lot attendant had brought the car out
  and he was still holding the door open because Terry Lennox's left foot was still
  dangling outside, as if he had forgotten he had one. He had a young-looking face
  but his hair was bone white. You could tell by his eyes that he was plastered to the hairline,
  but otherwise he looked like any other nice young guy in a dinner jacket
  who had been spending too much money in a joint that exists for that purpose and for no other.

I wonder what exactly "You could tell by his eyes that he was plastered to the hairline,
but otherwise he looked like any other nice young guy in a dinner jacket
who had been spending too much money in a joint that exists for that purpose and for no other."
means. What do "by his eyes", "plastered to the hairline", "that purpose", etc. mean?
Thanks.

A: "Plastered" is a synonym for drunk.
"Plastered to the hairline" may be hyperbole concerning the volume of alcohol consumed, as measured from toe to head. It may also connote an unmoving facial expression due to the stupor of intoxication.
The man's eyes were likely unresponsive and or bloodshot due to a large amount of alcohol in his system.
"for that purpose" references the business of selling alcohol. The word "joint" in this sentence is a synonym for a tavern, and the purpose is to sell drinks.


text:
Q: How to clear javascript objects retrieved from JQuery.HTML() I have an application that having the below requirement:
The pages of the application always contains page header, main content (center), and page footer. As per user requirement, the page header & footer should remain static, whenever user navigate from one page to other, the app should only refresh the main content (center) but NOT the header & footer.
The application was initially setup by other ex-colleagues, it is not using Single Page Application, and yet we do not prefer to use iframe to achieve the above mentioned requirement. The approach we use is: use the JQuery to fetch the page from server, and then render the page into a dedicated html div, via command $(div).html();
However, now we noticed there are some potential issue with the approach that we are using. The pages retrieved from the JQuery, most of them contains javascript objects (variables, functions), which are global by default. Without refreshing / reloading the entire page, the javacript objects will remain there, which may cause unexpected behavior, more over the javascript objects will be accumulated in the page which shall impact the performance.
I have tried the JQuery.empty() method however it only clear the DOM elements but not those javascript objects.
Here is how we render the main content into the center div:
function switchPage(pageUrl) {
    $.ajax({
        url: context + pageUrl,
        cache: false,
        success: function(result) {
            $("#main-content-panel").html(result);
    }
   });
}

Please advise there is a way to clear those javascript objects effectively with minimal effort? Or if these JQuery approach is a wrong option in the first place, what could be a better approach with minimal effort of changes (as we have already built many pages, and hence we wish to minimize the changes).
TQ.

A: That's quite dirty, but quick resolve you can try:
If you have global JavaScript alredy loaded, only thing you have to do is cut out all javascript from incoming result by removing all "script" tags. If you need to preserve some scripts with eg. new variables, functions to replace etc. you can mark them with eg. "live-script" class:
function switchPage(pageUrl) {
    $.ajax({
        url: context + pageUrl,
        cache: false,
        success: function(result) {
          var $result = $(result).find("script:not(.live-script)").remove();
            $("#main-content-panel").html($result);
    }
   });
}


text:
Q: If loop, error in macro Hi I am trying to make a macro for imagej.
Now I have as input a vector Array1y about 300 elements. If I would like to subdivide the vector in subvectors, how can i do? If for example I want 100 subvectors, so a step of 30, I was thinking to something like that
w=30;
step= Array1y.length/w
for (i=0; i<Array1y.length; i+=(w+1))
{
for (j=w; j<Array1y.length ; j+=w)
a(i)= Array.slice(Array1y,i,w)
Array.print a(i)
}
}

what's wrong?
Can it work if I have no 300 elements but less, let's say 268 and I want as well a step of 30 (so I have the last subvector that is not made by 30 elements?)

A: I'm not sure what you're trying to do, or if it is actually java, but here's what I think you asked for :
public static void main(String[] args) {
    int[] vector = new int[268];
    IntStream.range(0, vector.length).forEach(i -> vector[i] = i); // to fill the vector
    int subvectorSize = 30;
    int[][] subvectors = new int[vector.length/subvectorSize+1][subvectorSize];  // array of arrays
    for(int i=0; i< vector.length; i++){  // iterate over vector
        int x = i/subvectorSize; // get quotient (xth subvector)
        int y = i%subvectorSize; // get reminder (index y of subvector)
        subvectors[x][y] = vector[i];
    }
    System.out.println(Arrays.deepToString(subvectors));
}

That outputs :

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89], [90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119], [120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149], [150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179], [180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209], [210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239], [240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 0, 0]]


text:
Q: Better way to execute join query in Laravel Currently I have two tables; Users and Employees
All users are employees but not all employees are users,
I have a models Users and Employee, the personal details of a user are pulled his respective employee record.
Now I wanted to display all users and I can do it using User::all();
but also I wanted to have their personal details too.
currently I'm doing a DB:: call to join table in a function on my Users Model.
is there a better approach to this?

A: You can do it the Laravel way - eager load the relationship
$users = User::with('employee')->get();

This assumes that you have your relationships defined, at least on User side.
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Employee;

class User extends Authenticatable
{
    // ...

    public function employee()
    {
        return $this->hasOne(Employee::class, 'employee_no');
    }
}

FYI the Laravel way doesn't necessarily mean the fastest or the best way. It's usually syntactically more expensive/terse and convenient though.
Eager loading a relationship requires an additional query. In your case two queries will be executed under the hood and then employee property will be materialized for each User model in a collection.
So your way with a join and one roundtrip to the database might be more performant at the end of the day.

A: You should establish a relation. In this case your users can relate to your employees as such
public function employee()
{
    return $this->hasOne(Employee::class);
}

With Eloquent, you can just define methods in your User model to access the relation and be done with it.
public function role
{
    return $this->employee->role;
}

However, when fetching users, you want to ensure you "eager load" your employee relation so that you're not individually fetching employees when using these methods. When you fetch your users:
User::with('employee')->all()

If you will always require the employee record you can eager load by default:
class User extends Authenticatable
{
    protected $with = ['employee'];
}

A: Sounds like you need to use an Eloquent One to One Relationship
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function employee()
    {
        return $this->hasOne('App\Employee');
    }
}


text:
Q: Return raw objects from Action methods and convert them to JsonResult before rendering The website that I'm working on is heavily depending on ajax/json and knockout.js.
I would like to have a lot of my Controllers return view-tailored 'json objects', without wrapping them in a JsonResult when returning the method.
This would mean I could easily composite multiple calls into one parent object, but still be able to call the Actions separately too.
Simplified example:
public object Main(int groupId)
{
    var viewModel = new
    {
        Persons    = Employees(groupId),
        Messages   = AllMessages()
    };

    return viewModel;
}

public object Employees(int groupId)
{
    return DatabaseContext.Employees.Where(e => e.GroupId == groupId).ToList();
}

public object AllMessages()
{
    return DatabaseContext.Messages.ToList();
}

I was hoping I could capture the returned object in OnActionExecuted and at that point wrap the whole result up in a final JsonResult.
The result is already converted to a string and captured in a ContentResult though.
Any ideas? :) Thanks,

A: A good approach on this is to create helper methods for your entity calls. Or if you have those methods already somewhere, they can actually serve as the helper methods. In that manner you can return a list of strongly-typed Messages and Employees as well as returning your desired parent object. You can then have individual controller methods that returns  json objects. In addition, you can extend the parent viewmodel to return additional fields.
The Parent ViewModel
public class ParentModel {
    public Employee Persons {get;set;}
    public Message Messages {get;set;}
}

The Helper Methods
The beauty of using helper methods similar to what is defined here is that you can apply a few more logic to your query, and more, and you don't have to change anything in your controller methods.
public ParentModel GetMain(int groupId)
{
    var viewModel = new ParentModel
    {
        Persons    = Employees(groupId),
        Messages   = AllMessages()
    };

    return viewModel;
}

public IEnumerable<Employee> Employees(int groupId)
{
    return DatabaseContext.Employees.Where(e => e.GroupId == groupId).ToList();
}

public IEnumerable<Message> AllMessages()
{
    return DatabaseContext.Messages.ToList();
}

The Controller Methods
public ActionResult GetParent(int groupId){
    return Json(helperinstance.GetMain());
}
public ActionResult GetEmployees(int groupId){
    return Json(helperinstance.Employees());
}
public ActionResult GetMessages(int groupId){
    return Json(helperinstance.AllMessages());
}

A: Thanks for the answer. I'm not going for the solution of von v. because I like to keep the boilerplate as small as possible.
In the end I am trying out the following approach. It seems to work pretty well for now, but I still have to test it in real production.
If anyone has some (security) concerns with this, I'm happy to hear them in the comments.
// BaseController
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var returnType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;

    // is the returnType not deriving from ActionResult? Automatically wrap it in a JsonResult
    if ( !typeof(ActionResult).IsAssignableFrom(returnType) )
    {
        var result = filterContext.ActionDescriptor.Execute(filterContext, filterContext.ActionParameters);

        filterContext.Result = Json( result );
    }
}


text:
Q: Is it possible to recreate the .meteor directory? When I tried to run my Meteor app from its directory with the "meteor" command, I got, "You're not in a Meteor project directory."
When I looked, I saw that the .meteor folder got deleted; I guess I somehow inadvertently did that.
Is there a way to add back a corrupted or deleted .Meteor folder?

A: No, but there shouldn't be anything in there that cannot be recreated easily.
I'd meteor create DoinItAgain in a new directory, then copy all your source files into the new project.
Then it's time to play 'Whack a Mole' with the errors that come up, due to packages that will need to be re-added to the project.


text:
Q: Using Selenium Webdriver how to retrive date text With selenium webdriver I need to get the text from a div tag which has a date in it how to go with that
here is the HTML tag showing the div tag.

Last update

Jul 12, 2017

I stored created a webelement for the above and tried using
WebElement lastUpdate = driver.findElement(By.xpath("//*[ . = 'Last update' and //div[contains(@class, 'fieldlabel-content')]]/following-sibling::div[@class='fieldlabel-content']"));

lastUpadte.getText();

The output was --
So I another option which is this
Date expiryDate = null;
    DateFormat formatter = new SimpleDateFormat("MMM DD, YYYY");
    String dateString = lastUpdate.getText();
     try {
       expiryDate = formatter.parse(dateString);
    }
     catch (ParseException e) {
     e.printStackTrace();
    }

Still it didn't work. I am sure I am not doing it properly so please help me in fixing this issue.

A: Try this below code to get the date
String date = driver.findElement(By.xpath("//div[@class='gridlayout-content']//div[@class='fieldlabel-content']")).getText();
System.out.println(date);

OR

you can do this way.
WebElement date = driver.findElement(By.xpath("//div[@class='gridlayout-content']//div[@class='fieldlabel-content']"));
String s = date.getText();
System.out.println(s);

A: I think the problem is your XPath is incorrect. You have a couple choices to fix the XPath expression.
First: Find the date element based on sibling text value 'Last update'.
WebElement lastUpdate = driver.findElement(By.xpath("//*[div='Last update']/*[@class='fieldlabel-content']");

Second: Find the date element by go into the sibling by text 'Last update' and then up to the parent and find the date.
WebElement lastUpdate = driver.findElement(By.xpath("//*[text()='Last update']/../*[@class='fieldlabel-content']");

You can get the date text by:
lastUpdate.getAttribute("innerText");

Finally, you need to change the date format to "MMM dd, yyyy".
DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");