问:
How to fetch json file in MEAN?
I am new in MEAN.I have json content inside database.Need to fetch the content and want to show at the front

Here is the json collection which I have taken from terminal

```<code>athira@athira-Inspiron-3558:~$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use ehsjson
switched to db ehsjson
> db.ehsjson.find()
{ "_id" : ObjectId("58ddfc8758749dac677fe0af"), "glossary" : { "title" : "example glossary", "GlossDiv" : { "title" : "S", "GlossList" : { "GlossEntry" : { "ID" : "SGML", "SortAs" : "SGML", "GlossTerm" : "Standard Generalized Markup Language", "Acronym" : "SGML", "Abbrev" : "ISO 8879:1986", "GlossDef" : { "para" : "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso" : [  "GML",  "XML" ] }, "GlossSee" : "markup" } } } } }
>
</code>```

Here is my code I have tried to fetch the data

```<code>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ehsjson');
var Employee = mongoose.model('Employee', mongoose.Schema({

glossary: {
    title: String,
    GlossDiv: {
        title: String,
        GlossList: {
            GlossEntry: {
                ID: String,
                SortAs: String,
                GlossTerm: String,
                Acronym: String,
                Abbrev: String,
                GlossDef: {
                    para: String,
                    GlossSeeAlso: Array
                },
                GlossSee: String
            }
        }
    }
}

}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));

app.get('/api/employee', function(req, res){
    Employee.find(function(err, ehsjson)
    {
        console.log(ehsjson);
        if(err)
        {
            res.send(err);
            console.log("error"+err);
        }
        res.jsonp(ehsjson);
    });
     //res.jsonp(Employee.ehsjson());
});
</code>```

But its returning null object.

Please help to find out the mistakes

Thank you

答:
You are trying to map the JSON content with the Employee object. But the JSON content has different data so it won't be matched with Employee object. That's why you are getting null.

Insert the content like this and try it. It will work.

db.employee.find()
  { "_id" : ObjectId("58deb49ddf74cfbde91cf804"), "name" : "test", "dept" : "dept", "area" : "area", "status" : "status", "contact" : "contact", "salary" : "122" }

Title: How to fetch json file in MEAN?

Body:
I am new in MEAN.I have json content inside database.Need to fetch the content and want to show at the front

Here is the json collection which I have taken from terminal

athira@athira-Inspiron-3558:~$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use ehsjson
switched to db ehsjson
> db.ehsjson.find()
{ "_id" : ObjectId("58ddfc8758749dac677fe0af"), "glossary" : { "title" : "example glossary", "GlossDiv" : { "title" : "S", "GlossList" : { "GlossEntry" : { "ID" : "SGML", "SortAs" : "SGML", "GlossTerm" : "Standard Generalized Markup Language", "Acronym" : "SGML", "Abbrev" : "ISO 8879:1986", "GlossDef" : { "para" : "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso" : [  "GML",  "XML" ] }, "GlossSee" : "markup" } } } } }
>

Here is my code I have tried to fetch the data

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ehsjson');
var Employee = mongoose.model('Employee', mongoose.Schema({

glossary: {
    title: String,
    GlossDiv: {
        title: String,
        GlossList: {
            GlossEntry: {
                ID: String,
                SortAs: String,
                GlossTerm: String,
                Acronym: String,
                Abbrev: String,
                GlossDef: {
                    para: String,
                    GlossSeeAlso: Array
                },
                GlossSee: String
            }
        }
    }
}

}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));

app.get('/api/employee', function(req, res){
    Employee.find(function(err, ehsjson)
    {
        console.log(ehsjson);
        if(err)
        {
            res.send(err);
            console.log("error"+err);
        }
        res.jsonp(ehsjson);
    });
     //res.jsonp(Employee.ehsjson());
});

But its returning null object.

Please help to find out the mistakes

Thank you


来源: stackexchange

问:
Java User Input array is only capturing 3 integers instead of five
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.</p>

```<code>import java.util.Scanner;

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}
</code>```

答:
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.

Here I fix your code.

```<code>import java.util.Scanner;

public class ArrayReverse {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in); // scanner for input
    final int NUM_VALS = 5;  // number on int user able to enter
    int[] userNum = new int[NUM_VALS]; // user integers storage
    int j = 0;
    int i = 0;
   //for 5 inputs you need loop
   for(;i<NUM_VALS;i++){
    System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int
   }

    for (j = 0; j < NUM_VALS; j++) {
        System.out.print("You entered: ");
        System.out.println(userNum[j]);
        //++j; //no need to increment as you already did in for loop
    }
    System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
    for (j = NUM_VALS - 1; j >= 0; j--) {
        System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
    }

}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.

import java.util.Scanner;

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}

Body:
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.

Here I fix your code.

import java.util.Scanner;

public class ArrayReverse {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in); // scanner for input
    final int NUM_VALS = 5;  // number on int user able to enter
    int[] userNum = new int[NUM_VALS]; // user integers storage
    int j = 0;
    int i = 0;
   //for 5 inputs you need loop
   for(;i<NUM_VALS;i++){
    System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int
   }

    for (j = 0; j < NUM_VALS; j++) {
        System.out.print("You entered: ");
        System.out.println(userNum[j]);
        //++j; //no need to increment as you already did in for loop
    }
    System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
    for (j = NUM_VALS - 1; j >= 0; j--) {
        System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
    }

}
}


问:
Javascript Set ES6
Is there a way to insert an item as first element of Set in javascript like it is done in arrays in the example below ?</p>

```<code>arr['a','b','c']
arr.unshift ('d')
//Result
arr['d','a','b','c']
</code>```

答:
There is no direct way, or a method to unshift a set element.

You could use the spread syntax ... for the old set and generate a new set.

var mySet = new Set(['a', 'b', 'c']);

mySet = new Set(['d', ...mySet]);

console.log([...mySet]);```

Title: Javascript Set ES6

Body:
Is there a way to insert an item as first element of Set in javascript like it is done in arrays in the example below ?

arr['a','b','c']
arr.unshift ('d')
//Result
arr['d','a','b','c']


问:
4x 25% boxes in one line
I started learning CSS3 and got a problem, i want to create 4 black boxes(divs), and put them on in one line, 3 of them work properly, but 4th is moving to new line, what am i doing wrong?

My guess would be that its because of the 10px margin, but i dont know how to do it properly.

* {
    margin: 0px;
    padding: 0px; }

body {
    font-family: Roboto, sans-serif;
    box-sizing: border-box; }

#wrapper {
    width: 1000px;
    margin-left: auto;
    margin-right: auto; }

#block1 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block2 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block3 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block4 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="wrapper">
        <div id="block1"></div>
        <div id="block2"></div>
        <div id="block3"></div>
        <div id="block4"></div>
    </div> </body></code>```

答:
body {
      font-family: Roboto, sans-serif; box-sizing: border-box;
    }

    #wrapper {
      width: 1000px;
      margin: 0 auto;
    }

    #block1 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block2 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block3 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block4 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="block1">
    Stuff1
  </div>
  <div id="block2">
    Stuff2
  </div>
  <div id="block3">
    Stuff3
  </div>
  <div id="block4">
    Stuff4
  </div>

</div></code>```

Title: 4x 25% boxes in one line

Body:
body {
      font-family: Roboto, sans-serif; box-sizing: border-box;
    }

    #wrapper {
      width: 1000px;
      margin: 0 auto;
    }

    #block1 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block2 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block3 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px; }

    #block4 {
      width: calc(25% - 10px);
      height: 100px;
      background-color: black;
      float: left;
      margin-right: 10px;
    }

<div id="wrapper">
  <div id="block1">
    Stuff1
  </div>
  <div id="block2">
    Stuff2
  </div>
  <div id="block3">
    Stuff3
  </div>
  <div id="block4">
    Stuff4
  </div>

</div>


问:
Javascript - reduce to an object
Execute below code in chrome console - for the google page.

```<code>[].slice.call(document.querySelectorAll("input"))
                       .map(el => el.name?el.name:el.id)
</code>```

I see this output.

I wanted to reduce this list to an object.

```<code>         .reduce((acc,el) => acc[el] = el.toUpperCase(), {});
</code>```

I expected something like below...

```<code>            {
                "sclient":"SCLIENT",
                "site":"SITE",
                ...
            }
</code>```

But it returns only the last element.

What is wrong with this reduce function?

答:
You're returning acc[el] = el.toUpperCase(), which will return the value for el.toUpperCase(). In other words, you're returning a new string every iteration. You need to return your accumulator (acc):

```<code>.reduce((acc,el) => {
   acc[el] = el.toUpperCase();
   return acc;
}, {});
</code>```

Let me know if you have any issues.

Title: Javascript - reduce to an object

Body:
Execute below code in chrome console - for the google page.

[].slice.call(document.querySelectorAll("input"))
                       .map(el => el.name?el.name:el.id)

I see this output.

I wanted to reduce this list to an object.

         .reduce((acc,el) => acc[el] = el.toUpperCase(), {});

I expected something like below...

            {
                "sclient":"SCLIENT",
                "site":"SITE",
                ...
            }

But it returns only the last element.

What is wrong with this reduce function?

Body:
You're returning acc[el] = el.toUpperCase(), which will return the value for el.toUpperCase(). In other words, you're returning a new string every iteration. You need to return your accumulator (acc):

.reduce((acc,el) => {
   acc[el] = el.toUpperCase();
   return acc;
}, {});

Let me know if you have any issues.


问:
CSS Fold items up & down animation
I have a list of items:

Which, I would like to collapse with an animation effect, to just display one item:

As you can see, currently it collapses to one item, but the entire component does not collapse.

I am currently just setting the the items opacity to zero:

css

```<code>.slide-fade-hide {
  transition: all 1.2s ease-out;
  opacity: 0;
  //height: 2em;
}

.slide-fade-show {
  transition: all 1.2s ease-in;
  opacity: 1;
  //height: 2em;
}
</code>```

html

```<code><ion-list>
  <ion-row>
    <ion-col>
      <div id="search">
        <ion-searchbar class="ion-searchtext" id="ion-searchtext" [(ngModel)]="searchQueryText" (ionFocus)="focusSearch($event)" (change)="onChangeText($event)"
          (ionClear)="onCancelText($event)" (ionInput)="onInputText($event)" placeholder="{{jobType === 0 ? favourite ? 'Market Favourites' : 'Market' : favourite ? 'Postings Favourites' : 'Postings'}}"
          debounce="1"></ion-searchbar>
      </div>
      <!--<div id="pinButton"><button ion-button (click)="presentPopover()" color="primary"><ion-icon name="funnel"></ion-icon></button></div>-->
    </ion-col>
  </ion-row>

  <!--<div *ngIf="showExtraSearch === true">-->
  <div id="extra-filter-items" class="slide-fade-hide">
    <ion-row>
      <ion-col>
        <div id="location-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryLocation" (ionClear)="onCancelLocation($event)" (ionInput)="onInputLocation($event)"
            (click)="presentFilterMap()" placeholder="Location" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="categories-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQuerySectors" (ionClear)="onCancelSectors($event)" (ionInput)="onInputSectors($event)"
            (click)="presentFilterCategories()" placeholder="Sectors" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="rating-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryRating" (ionClear)="onCancelRating($event)" (ionInput)="onInputRating($event)"
            (click)="presentFilterRating()" placeholder="Star Rating" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="time-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryTime" (ionClear)="onCancelTime($event)" (ionInput)="onInputTime($event)"
            (click)="presentFilterTime()" placeholder="Last Online" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
  </div>
</ion-list>
</code>```

javascript

```<code>  showExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-show";
    }
  }

  hideExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-hide";
    }
  }
</code>```

Problem

The items are still present, they just are transparent.

So if I click on them, they still respond.

Also, they are still taking up space, so that the rest of the dom is still beneath it.

Question

How do I allow the items to toggle from 1 item to 5 items with an animation effect as if they are sliding up & down? Also, so they also free up the space beneath them when they are up.

I did look at this example (see "Slide down & Fade"), but as you can see above, this does not achieve what I need.

Thanks

p.s. I am using Ionic2, so don't want to use any other Javascript frameworks like JQuery (just plain javascript and css).

答:
You need to transition with height attribute in your css

$(function(){

$("li").click(function(){
$(this).addClass("vanish");

})
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vanish {
  height:0;
  transition: 1s all linear;
  opacity:0;
}

li {
  height:2em;
  opacity:1;
  background:green;
}</code>```

Click me to collapse

Click me to collapse

Click me to collapse

```

Title: CSS Fold items up & down animation

Body:
I have a list of items:

Which, I would like to collapse with an animation effect, to just display one item:

As you can see, currently it collapses to one item, but the entire component does not collapse.

I am currently just setting the the items opacity to zero:

css

.slide-fade-hide {
  transition: all 1.2s ease-out;
  opacity: 0;
  //height: 2em;
}

.slide-fade-show {
  transition: all 1.2s ease-in;
  opacity: 1;
  //height: 2em;
}

html

<ion-list>
  <ion-row>
    <ion-col>

        <ion-searchbar class="ion-searchtext" id="ion-searchtext" [(ngModel)]="searchQueryText" (ionFocus)="focusSearch($event)" (change)="onChangeText($event)"
          (ionClear)="onCancelText($event)" (ionInput)="onInputText($event)" placeholder="{{jobType === 0 ? favourite ? 'Market Favourites' : 'Market' : favourite ? 'Postings Favourites' : 'Postings'}}"
          debounce="1"></ion-searchbar>

    </ion-col>
  </ion-row>

    <ion-row>
      <ion-col>

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryLocation" (ionClear)="onCancelLocation($event)" (ionInput)="onInputLocation($event)"
            (click)="presentFilterMap()" placeholder="Location" debounce="1"></ion-searchbar>

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQuerySectors" (ionClear)="onCancelSectors($event)" (ionInput)="onInputSectors($event)"
            (click)="presentFilterCategories()" placeholder="Sectors" debounce="1"></ion-searchbar>

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryRating" (ionClear)="onCancelRating($event)" (ionInput)="onInputRating($event)"
            (click)="presentFilterRating()" placeholder="Star Rating" debounce="1"></ion-searchbar>

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryTime" (ionClear)="onCancelTime($event)" (ionInput)="onInputTime($event)"
            (click)="presentFilterTime()" placeholder="Last Online" debounce="1"></ion-searchbar>

      </ion-col>
    </ion-row>

</ion-list>

javascript

  showExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-show";
    }
  }

  hideExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-hide";
    }
  }

Problem

The items are still present, they just are transparent.

So if I click on them, they still respond.

Also, they are still taking up space, so that the rest of the dom is still beneath it.

Question

How do I allow the items to toggle from 1 item to 5 items with an animation effect as if they are sliding up & down? Also, so they also free up the space beneath them when they are up.

I did look at this example (see "Slide down & Fade"), but as you can see above, this does not achieve what I need.

Thanks

p.s. I am using Ionic2, so don't want to use any other Javascript frameworks like JQuery (just plain javascript and css).

Body:
You need to transition with height attribute in your css

$(function(){

$("li").click(function(){
$(this).addClass("vanish");

})
});

.vanish {
  height:0;
  transition: 1s all linear;
  opacity:0;
}

li {
  height:2em;
  opacity:1;
  background:green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul>
<li>Click me to collapse</li>
<li>Click me to collapse</li>
<li>Click me to collapse</li>
</ul>
</div>


问:
Resources for creating a Windows Phone 7 application in VS 2010

Possible Duplicate:

  Getting Started with Windows Phone 7

I am new to creating Windows Phone apps.

I want to develop my application in Visual Studio 2010 and also I would like some materials (like e-books) for developing for the Windows Phone 7.

Does anyone know of a website for that?

答:
http://create.msdn.com/en-US/

http://wp7dev.wikispaces.com/

are two great resources

ContentLicense: CC BY-SA 2.5


问:
Large project files in Heroku on Django
I have some large files that I need to store in my project. Their sum total size is 157 MB. When my application starts, I have an AppConfig which runs. It reads the files into memory and they stay there for the lifetime of the application. By the way, these files aren't static/media assets like images; they're numpy arrays for some server-side logic.

So I want a solution which accomplishes the following:

Keeps my files out of source control / the Heroku slug

Does not require me to read from some cloud service S3/Google frequently

Has my files readily available during the stage where AppConfigs are initialized.

Here is one solution that I thought of: Store the files in S3/Google, and download them from the server when AppConfig is initialized. The downside of this is that it would make restarting my server really slow because downloading 157 MB is pretty time-consuming, and it might cost a bit too.

Is there a better way?

答:
You would have hard time finding ideal solution for heroku (without paying to someone)

These are some of thoughts:

Keep datasets in database ( rows are not free on Heroku )

Keep datasets in memcached/redis ( these instances are pretty expensive on heroku )

OR

Host your site on cheap VPS :)

Title: Large project files in Heroku on Django


问:
Compiling and running in different containers
I have a project which compiles to a binary file, and running that binary file exposes some REST APIs.

To compile the project I need docker image A which has the compiler and and all the libraries required to produce the executable. To run the executable (ie. host the service) I can get away with a much smaller image B (just basic linux distro, no need for the compiler).

How does one use docker is such a situation?

答:
```<code>mkdir local_dir
docker run -dv $PWD/local_dir:/mnt BUILD_CONTAINER
</code>```

compile code and save it to /mnt in the container.  It'll be written to local_dir on your host filesystem and persist after the container is destroyed.

You Should now write a Dockerfile and add a step to copy in the new binary, then build.  But for example's sake...

```<code>docker run -dv $PWD/local_dir:/mnt PROD_CONTAINER
</code>```

Your bin, and everything else in local_dir, will reside in the container at /mnt/

Body:
mkdir local_dir
docker run -dv $PWD/local_dir:/mnt BUILD_CONTAINER

compile code and save it to /mnt in the container.  It'll be written to local_dir on your host filesystem and persist after the container is destroyed.

You Should now write a Dockerfile and add a step to copy in the new binary, then build.  But for example's sake...

docker run -dv $PWD/local_dir:/mnt PROD_CONTAINER

Your bin, and everything else in local_dir, will reside in the container at /mnt/


问:
Query sqlite every 10s vs using timeout vs node-cron
I have an sqlite flavor DB which contains one table, its has about 10k items with 5 columns. In one of the columns I have a 'timer' basically a number I have given and the purpose of it is to decrease it as time (ideally every second) goes by till it reaches zero. When it reaches zero I want to perform an action.

Thought process

1st: I can update my db for every item needed (probably for the 2k out of the 10k) every 10s (setInternal) -as to not stress it- and check whether any items reached zero. I am reluctant about this way as I feel it might not be so efficient.

2nd: Since I am on nodejs I can use timeouts. Read once my DB get all the wanted users, and for every one of them create a setTimeout method. After a minute or so update the DB, nested-setInternal Since each of the setTimeout take about 35bytes of the nodejs heap its not a bad method. -Right now I think this is the wat to go.

3rd: I found out this https://github.com/kelektiv/node-cron github, which basically is a task scheduler. After looking at its code for a bit I dont think its bad but I really dont think I have to use an external package here.

Note: Whatever of the above methods where I to use in case the process crashed they would be resetted (loses completely the point) without updating my DB periodically so I guess I cant avoid that.

Question: What should I do to efficiently update a timer in my DB every few seconds-(so all the time my process is alive)- without draining my resources?

Sorry to those that read the whole thing and feel they lost their time.

答:
Don't store the remaining time in the database. Instead store the absolute timestamp of the action.

Then you can simply ask for any actions that need to be handled:

SELECT *
FROM actions
WHERE timestamp > (last handled timestamp)
  AND timestamp <= (current timestamp);
```

<p>(If the <code>timestamp</code> column is indexed, this query is very efficient.)</p>

<p>You can also get the time until the next event, to program a timeout:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT timestamp
FROM actions
WHERE timestamp > (last handled timestamp)
ORDER BY timestamp ASC
LIMIT 1;
</code>```

Body:
Don't store the remaining time in the database. Instead store the absolute timestamp of the action.

Then you can simply ask for any actions that need to be handled:

SELECT *
FROM actions
WHERE timestamp > (last handled timestamp)
  AND timestamp <= (current timestamp);

(If the timestamp column is indexed, this query is very efficient.)

You can also get the time until the next event, to program a timeout:

SELECT timestamp
FROM actions
WHERE timestamp > (last handled timestamp)
ORDER BY timestamp ASC
LIMIT 1;


问:
How do I echo strings on the same line as a previous echo?
How do I echo "I have 1 number" using two echo commands in a batch file?

```<code>echo "I have "
...
... do stuff
...
echo "1 number"
</code>```

creates two lines:

```<code>I have
1 number
</code>```

how do I suppress the cr/lf on the first echo?  to create:

```<code>I have 1 number
</code>```

答:
this appears to do it:

```<code><nul set /p=I have
echo 1 number
</code>```

note that this example is too simplistic- in a more general case the second part is not just an echo but the result of some calculation or manipulation, for example cd:

```<code><nul set /p=set currentdir=>a.bat
cd>>a.bat
</code>```

I can't see that this functionality is possible with the PART1 answer given above.

Body:
How do I echo "I have 1 number" using two echo commands in a batch file?

echo "I have "
...
... do stuff
...
echo "1 number"

creates two lines:

I have
1 number

how do I suppress the cr/lf on the first echo?  to create:

I have 1 number

Body:
this appears to do it:

<nul set /p=I have
echo 1 number

note that this example is too simplistic- in a more general case the second part is not just an echo but the result of some calculation or manipulation, for example cd:

<nul set /p=set currentdir=>a.bat
cd>>a.bat

I can't see that this functionality is possible with the PART1 answer given above.


问:
protobuf MessageToJson removes fields with value 0
I'm writing a Python script that receives protobufs, converts them to json objects, and pushes them to another service. I use json.loads(MessageToJson(protobuf)) to convert the protobuf to a python dictionary object. Later I convert it back to json with json.dumps(dictionary).

I have a proto with an optional enumerated field such as:

```<code>enum C_TYPE
{
    AB = 0;
    BC = 1;
    CD = 2;
}
</code>```

When I receive a proto with a field designated as BC everything works as I expect it. When I receive a proto with a field designated AB that field gets ignored -- it does not turn up in the python dictionary or subsequent json dump. A workaround I have found is to use json.loads(MessageToJson(protobuf, including_default_value_fields=True)) but that will create default values for all missing fields, not just the ones that have a 0 enumeration. It implies that the field with enumeration 0 is missing - but it's not!

What is the correct way to retrieve the value of the enumeration field when it is set to 0?

答:
There is no correct way, I'm defining my protobufs incorrectly. For enumerated fields, the first value is the default value. This means if a protobuf comes through without a set value, it is set to the default value and, when converted to json, ignored (unless you want to keep all default values.)

Thus, it is recommended use throw-away names for the default value to be able to properly distinguish when it has been set. i.e. I should define my protobuf as:

```<code>enum C_TYPE
{
    NONE = 0;
    AB = 1;
    BC = 2;
    CD = 3;
}
</code>```

From Protobuf Documentation on Optional Fields And Default Values:

For enums, the default value is the first value listed in the enum's
  type definition. This means care must be taken when adding a value to
  the beginning of an enum value list.

Additionally from an issue on golang/protobuf:

This is working as intended. proto3 zero-values are omitted in the
  JSON format too. The zero-value should be a "throwaway" value: it's
  also what you will see if the sender of a serialized message sets the
  field to an invalid or unrecognized value.

Body:
I'm writing a Python script that receives protobufs, converts them to json objects, and pushes them to another service. I use json.loads(MessageToJson(protobuf)) to convert the protobuf to a python dictionary object. Later I convert it back to json with json.dumps(dictionary).

I have a proto with an optional enumerated field such as:

enum C_TYPE
{
    AB = 0;
    BC = 1;
    CD = 2;
}

When I receive a proto with a field designated as BC everything works as I expect it. When I receive a proto with a field designated AB that field gets ignored -- it does not turn up in the python dictionary or subsequent json dump. A workaround I have found is to use json.loads(MessageToJson(protobuf, including_default_value_fields=True)) but that will create default values for all missing fields, not just the ones that have a 0 enumeration. It implies that the field with enumeration 0 is missing - but it's not!

What is the correct way to retrieve the value of the enumeration field when it is set to 0?

Body:
There is no correct way, I'm defining my protobufs incorrectly. For enumerated fields, the first value is the default value. This means if a protobuf comes through without a set value, it is set to the default value and, when converted to json, ignored (unless you want to keep all default values.)

Thus, it is recommended use throw-away names for the default value to be able to properly distinguish when it has been set. i.e. I should define my protobuf as:

enum C_TYPE
{
    NONE = 0;
    AB = 1;
    BC = 2;
    CD = 3;
}

From Protobuf Documentation on Optional Fields And Default Values:

For enums, the default value is the first value listed in the enum's
  type definition. This means care must be taken when adding a value to
  the beginning of an enum value list.

Additionally from an issue on golang/protobuf:

This is working as intended. proto3 zero-values are omitted in the
  JSON format too. The zero-value should be a "throwaway" value: it's
  also what you will see if the sender of a serialized message sets the
  field to an invalid or unrecognized value.


问:
unindent does not match any outer indentation level in my maths game
I'm creating a maths quiz to help get my self started with Python since I'm very new to the language and it comes up with a unindent does not match any outer indentation level error message? Could someone inform me on what this means and where my mistake lies.

Here is my code:

```<code>import random

questions = 0
correct = 0

print ("Welcome to the maths challenge")
print ("Out of these 10 questions how many can you get right?")

while True :
questions += 1
numberA = random.randint(0,12)
question = "What is {0}**2".format(numberA)

print(question)

response = input("Your Answer : ")

answer = numberA**2

if(int(response) == answer) :
    print("Correct!")

else :
    print("Wrong!")

 if(questions == 10) :
     print("You got {0}/{1} questions correct.").format(correct, questions)

 if correct == ("5>")
     print ("Better luck next time")

 if correct == ("5<")
     print ("You got a great score Well done!")
     break
</code>```

答:
It looks like the area that is generating the error may start from:

```<code> if(questions == 10) :
</code>```

At least from what you have put in your question. With python, space and indentation dictate most of the language syntax, rather than opening and closing blocks. So it is very important that you pay attention to exactly how many spaces or tabs you use before a block, in order to keep indentation consistent.

Some IDEs will help immensely with this task, such as PyCharm. Other text editors like Notepad++ would allow you to search through your text and replace tab characters with spaces, though that may be a little bit above and beyond what you asked.

Body:
I'm creating a maths quiz to help get my self started with Python since I'm very new to the language and it comes up with a unindent does not match any outer indentation level error message? Could someone inform me on what this means and where my mistake lies.

Here is my code:

import random

questions = 0
correct = 0

print ("Welcome to the maths challenge")
print ("Out of these 10 questions how many can you get right?")

while True :
questions += 1
numberA = random.randint(0,12)
question = "What is {0}**2".format(numberA)

print(question)

response = input("Your Answer : ")

answer = numberA**2

if(int(response) == answer) :
    print("Correct!")

else :
    print("Wrong!")

 if(questions == 10) :
     print("You got {0}/{1} questions correct.").format(correct, questions)

 if correct == ("5>")
     print ("Better luck next time")

 if correct == ("5<")
     print ("You got a great score Well done!")
     break

Body:
It looks like the area that is generating the error may start from:

 if(questions == 10) :

At least from what you have put in your question. With python, space and indentation dictate most of the language syntax, rather than opening and closing blocks. So it is very important that you pay attention to exactly how many spaces or tabs you use before a block, in order to keep indentation consistent.

Some IDEs will help immensely with this task, such as PyCharm. Other text editors like Notepad++ would allow you to search through your text and replace tab characters with spaces, though that may be a little bit above and beyond what you asked.


问:
Migrating C++ project to Java, protecting implementation details
I have a quite complex project to migrate from C++ (Linux) to Java
Currently, the C++ version is being distributed as a shared library (.so) followed by top-level interface header class. The implementation details are fully hidden from the final user.

This question is not about porting the C++ code to Java, but rather about creating similar distribution package.

Let's assume I have a very simple 'public' class in C++, topapi.h:

```<code>class TopApi
{
public:
  void do( const string& v );
}
</code>```

The actual implementation is hidden from the API user. The actual project may contain another 100 files/classes do() will call.

The distribution will contain 2 files: topapi.so and topapi.h

Users will #include "topapi.h" in their code, and link their applications with topapi.so.

The questions are:
1. How can I achieve a similar effect in Java (hide the IP related code)
2. How do I show public methods to the user ( not related to code protection, just a java version of the header file above )

答:
Check out proguard. It will at least obfuscate the jar file, which otherwise is basically human readable. It's not absolutely safe from reverse engineering, but I guess neither is an so file.

I'm not an expert with Java, but this is what we have done to protect implementations in the past.

I don't know exactly what the motivations are for a Java port, but if it is just to support a Java end user, you could consider a JNI wrapper.  I guess this probably isn't the case, but I thought I would mention it.

As far as exposing interface code to the user, you could write a Java interface class (like a pure virtual abstract c++ class) and simply not proguard that class.

Body:
I have a quite complex project to migrate from C++ (Linux) to Java
Currently, the C++ version is being distributed as a shared library (.so) followed by top-level interface header class. The implementation details are fully hidden from the final user.

This question is not about porting the C++ code to Java, but rather about creating similar distribution package.

Let's assume I have a very simple 'public' class in C++, topapi.h:

class TopApi
{
public:
  void do( const string& v );
}

The actual implementation is hidden from the API user. The actual project may contain another 100 files/classes do() will call.

The distribution will contain 2 files: topapi.so and topapi.h

Users will #include "topapi.h" in their code, and link their applications with topapi.so.

The questions are:
1. How can I achieve a similar effect in Java (hide the IP related code)
2. How do I show public methods to the user ( not related to code protection, just a java version of the header file above )


问:
how to 3-way outer product in numpy?
About the numpy.outer [link] .

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product will be M*N matrix.

But how to implement a 3-array outer product, which means : given
third vector c = [c0, c1, ..., cP], how to get the outer product
between the 3 numpy arrays.

and how to get n-way outer product for n-array in numpy, for the method of einsum, how to change 'i,j,k->ijk'  to process "n" .

答:
You could use einsum for this:

```<code>>>> numpy.einsum('i,j,k->ijk', [1, 2], [3, 4, 5], [6,7,8,9])
array([[[18, 21, 24, 27],
        [24, 28, 32, 36],
        [30, 35, 40, 45]],

       [[36, 42, 48, 54],
        [48, 56, 64, 72],
        [60, 70, 80, 90]]])
</code>```

You cannot cross arbitrary amount of vectors using einsum. The indices can only be letters, so at most 52 vectors are allowed in this form (although it will raise "too many operands" when 32 vectors are provided):

```<code>def nary_outer_einsum_52(*vectors):
    import string
    subscripts = string.ascii_letters[:len(vectors)]
    subscripts = ','.join(subscripts) + '->' + subscripts
    # expands to `numpy.einsum('a,b,c,d,e->abcde', v[0], v[1], v[2], v[3], v[4])`
    return numpy.einsum(subscripts, *vectors)
</code>```

einsum supports another form which uses numeric indices instead of letters, which unfortunately only support up to 26 vectors because it just translates to the letter version internally. I do not recommend using this until the bug I mentioned is fixed.

```<code>def nary_outer_einsum_26(*vectors):
    operations = (x for i, v in enumerate(vectors) for x in (v, [i]))
    # expands to `numpy.einsum(v[0], [0], v[1], [1], v[2], [2], v[3], [3], v[4], [4])`
    return numpy.einsum(*operations)
</code>```

numpy.ix_ (@PaulPanzer's answer) can easily be scaled up to the N-ary case. Still, there is an implementation-limit of 32 vectors:

```<code>def nary_outer_ix(*vectors):
    return numpy.prod(numpy.ix_(*vectors), axis=0)
</code>```

timeit with 3 vectors:

```<code>>>> timeit.Timer('nary_outer_einsum_52([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(100000, 0.8991979530110257)   # 9 µs / iteration
>>> timeit.Timer('nary_outer_einsum_26([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(100000, 1.0089023629989242)   # 10 µs / iteration
>>> timeit.Timer('nary_outer_ix([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(10000, 0.30978472300921567)   # 31 µs / iteration
</code>```

with 26 vectors:

```<code>>>> timeit.Timer('nary_outer_einsum_52(*([[1]] * 26))', globals=globals()).autorange()
(10000, 0.6589978060073918)   # 66 µs / iteration
>>> timeit.Timer('nary_outer_einsum_26(*([[1]] * 26))', globals=globals()).autorange()
(10000, 0.7502327310066903)   # 75 µs / iteration
>>> timeit.Timer('nary_outer_ix(*([[1]] * 26))', globals=globals()).autorange()
(1000, 0.2026848039968172)    # 203 µs / iteration
</code>```

with 33 vectors:

```<code>>>> nary_outer_einsum_52(*([[1]] * 33))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in nary_outer_einsum_52
  File "/usr/local/lib/python3.6/site-packages/numpy/core/einsumfunc.py", line 948, in einsum
    return c_einsum(*operands, **kwargs)
ValueError: too many operands
>>> nary_outer_ix(*([[1]] * 33))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in nary_outer_ix
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/index_tricks.py", line 83, in ix_
    new = new.reshape((1,)*k + (new.size,) + (1,)*(nd-k-1))
ValueError: sequence too large; cannot be greater than 32
</code>```

Title: how to 3-way outer product in numpy?

Body:
You could use einsum for this:

>>> numpy.einsum('i,j,k->ijk', [1, 2], [3, 4, 5], [6,7,8,9])
array([[[18, 21, 24, 27],
        [24, 28, 32, 36],
        [30, 35, 40, 45]],

       [[36, 42, 48, 54],
        [48, 56, 64, 72],
        [60, 70, 80, 90]]])

You cannot cross arbitrary amount of vectors using einsum. The indices can only be letters, so at most 52 vectors are allowed in this form (although it will raise "too many operands" when 32 vectors are provided):

def nary_outer_einsum_52(*vectors):
    import string
    subscripts = string.ascii_letters[:len(vectors)]
    subscripts = ','.join(subscripts) + '->' + subscripts
    # expands to `numpy.einsum('a,b,c,d,e->abcde', v[0], v[1], v[2], v[3], v[4])`
    return numpy.einsum(subscripts, *vectors)

einsum supports another form which uses numeric indices instead of letters, which unfortunately only support up to 26 vectors because it just translates to the letter version internally. I do not recommend using this until the bug I mentioned is fixed.

def nary_outer_einsum_26(*vectors):
    operations = (x for i, v in enumerate(vectors) for x in (v, [i]))
    # expands to `numpy.einsum(v[0], [0], v[1], [1], v[2], [2], v[3], [3], v[4], [4])`
    return numpy.einsum(*operations)

numpy.ix_ (@PaulPanzer's answer) can easily be scaled up to the N-ary case. Still, there is an implementation-limit of 32 vectors:

def nary_outer_ix(*vectors):
    return numpy.prod(numpy.ix_(*vectors), axis=0)

timeit with 3 vectors:

>>> timeit.Timer('nary_outer_einsum_52([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(100000, 0.8991979530110257)   # 9 µs / iteration
>>> timeit.Timer('nary_outer_einsum_26([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(100000, 1.0089023629989242)   # 10 µs / iteration
>>> timeit.Timer('nary_outer_ix([1,2], [3,4,5], [6,7,8,9])', globals=globals()).autorange()
(10000, 0.30978472300921567)   # 31 µs / iteration

with 26 vectors:

>>> timeit.Timer('nary_outer_einsum_52(*([[1]] * 26))', globals=globals()).autorange()
(10000, 0.6589978060073918)   # 66 µs / iteration
>>> timeit.Timer('nary_outer_einsum_26(*([[1]] * 26))', globals=globals()).autorange()
(10000, 0.7502327310066903)   # 75 µs / iteration
>>> timeit.Timer('nary_outer_ix(*([[1]] * 26))', globals=globals()).autorange()
(1000, 0.2026848039968172)    # 203 µs / iteration

with 33 vectors:

>>> nary_outer_einsum_52(*([[1]] * 33))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in nary_outer_einsum_52
  File "/usr/local/lib/python3.6/site-packages/numpy/core/einsumfunc.py", line 948, in einsum
    return c_einsum(*operands, **kwargs)
ValueError: too many operands
>>> nary_outer_ix(*([[1]] * 33))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in nary_outer_ix
  File "/usr/local/lib/python3.6/site-packages/numpy/lib/index_tricks.py", line 83, in ix_
    new = new.reshape((1,)*k + (new.size,) + (1,)*(nd-k-1))
ValueError: sequence too large; cannot be greater than 32


问:
How to declare global variable in order to kill second EXCEL.EXE from Task Manager
Following code opens two EXCEL.EXE in the Task Manager.

I want to kill second opening EXCEL.EXE from the Task Manager when Form1 is closing.

```<code>Imports Microsoft.Office.Interop

Public Class Form1

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    'Kill all EXCEL.EXE process from Task Manager
    For Each prog As Process In Process.GetProcessesByName("EXCEL")
        prog.Kill()
    Next

    Dim FirstxlApp As New Excel.Application 'Open first EXCEL.EXE in the Task Manager

    Dim datestart As Date = Date.Now
    Dim SecondxlApp As New Excel.Application 'Open second EXCEL.EXE in the Task Manager
    Dim dateEnd As Date = Date.Now

    SecondxlApp.Visible = True

    Dim wb1 As Excel.Workbook
    wb1 = SecondxlApp.Workbooks.Open("C:\Book1.xlsx")

End Sub

Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    Dim xlp() As Process = Process.GetProcessesByName("EXCEL")
    For Each Process As Process In xlp
        If Process.StartTime >= datestart And Process.StartTime <= dateEnd Then
            Process.Kill()
            Exit For
        End If
    Next

End Sub

End Class
</code>```

How to declare global variable in order to solve following errors?

答:
Your variables dateEnd and dateStart are hidden to FormClosing method as they are only declared within the Form_Load method.

Change your code to:

Public Class Form1
    Dim dateEnd, dateStart As DateTime
 Private Sub Form_load

Then they will be accessable to all methods with the form.

Body:
Following code opens two EXCEL.EXE in the Task Manager.

I want to kill second opening EXCEL.EXE from the Task Manager when Form1 is closing.

Imports Microsoft.Office.Interop

Public Class Form1

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    'Kill all EXCEL.EXE process from Task Manager
    For Each prog As Process In Process.GetProcessesByName("EXCEL")
        prog.Kill()
    Next

    Dim FirstxlApp As New Excel.Application 'Open first EXCEL.EXE in the Task Manager

    Dim datestart As Date = Date.Now
    Dim SecondxlApp As New Excel.Application 'Open second EXCEL.EXE in the Task Manager
    Dim dateEnd As Date = Date.Now

    SecondxlApp.Visible = True

    Dim wb1 As Excel.Workbook
    wb1 = SecondxlApp.Workbooks.Open("C:\Book1.xlsx")

End Sub

Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    Dim xlp() As Process = Process.GetProcessesByName("EXCEL")
    For Each Process As Process In xlp
        If Process.StartTime >= datestart And Process.StartTime <= dateEnd Then
            Process.Kill()
            Exit For
        End If
    Next

End Sub

End Class

How to declare global variable in order to solve following errors?


问:
JAVA making time to decrease to zero by swing timer
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

```<code>        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();
</code>```

is it possible?

答: A safer option is to take the actual clock time. The reason for this is that your application can stop for pewriods of time. esp if you machine is busy. This means a countdown timer might not be called as often as you expect. If you use the System.currentTimeMillis() the time will always be right no matter what happens.</p>

Body:
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();

is it possible?


问:
pafy Runtime warning "youtube-dl not found "
I recently installed pafy for windows and getting following message during runtime.

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
  Type "copyright", "credits" or "license()" for more information.

================================ RESTART ================================

WARNING:root:pafy: youtube-dl not found; falling back to internal backend. This is not as well maintained as the youtube-dl backend. To hide this message, set the environmental variable PAFY_BACKEND to "internal".

How do I setup environmental variable for PAFY_BACKEND and get rid of Warning?

答:
If you are using windows type this command in your command line: `pip install --upgrade youtube-dl .

Else if you are using Mac or unix, follow the this link `youtube-dl installation on unix and Mac OS x

This is to install youtube-dl on your machine after which the warning will no longer appear.


问:
When creating a nerd in my nerd_table I get the following error
This is my code from create_users_table.php

```<code>public function up()
    {
      Schema::table('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }
</code>```

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,
  created_at) values (dasdasd, vincentnelissen@hotmail.nl, 1,
  2017-03-31 15:41:51, 2017-03-31 15:41:51))

And when I try to edit a nerd I get the following error:

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

This is my code from edit.blade.php:

```<code>     <!DOCTYPE html>
     <html>
     <head>
        <title>Look! I'm CRUDding</title>
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap
        /3.0.0  /css/bootstrap.min.css">
 </head>
<body>
<div class="container">

  <nav class="navbar navbar-inverse">
  <div class="navbar-header">
    <a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
  </div>
  <ul class="nav navbar-nav">
    <li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
    <li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a>
  </ul>
 </nav>

 <h1>Edit {{ $nerd->name }}</h1>

 <!-- if there are creation errors, they will show here -->
  {{ HTML::ul($errors->all()) }}

 {{ Form::model($nerd, array('route' => array('nerds.update',
  $nerd->id),   'method' => 'PUT')) }}

<div class="form-group">
    {{ Form::label('name', 'Name') }}
    {{ Form::text('name', null, array('class' => 'form-control')) }}
</div>

<div class="form-group">
    {{ Form::label('email', 'Email') }}
    {{ Form::email('email', null, array('class' => 'form-control')) }}
</div>

<div class="form-group">
    {{ Form::label('nerd_level', 'Nerd Level') }}
    {{ Form::select('nerd_level', array('0' => 'Select a Level', '1' =>
    'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement
    Dweller'), null, array('class' => 'form-control')) }}
</div>

{{ Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) }}

 {{ Form::close() }}

 </div>
 </body>
 </html>
</code>```

And when I try to delete a nerd This is the error:

FatalErrorException in NerdController.php line 128: Call to a member
  function delete() on null

return Redirect is php line 128

```<code>public function destroy($id)
{
    // delete
    $nerd = User::find($id);
    $nerd->delete();

    // redirect
    Session::flash('message', 'Successfully deleted the nerd!');
    return Redirect::to('nerds');
}
</code>```

This Error can be profitable to others who have similar problems , so they know what to change in their code as well. Or not to make a similar mistake to whoever reads it first.

Can anyone help me ?

Kind regards,

Vincent

答:
instead of Schema::table use Schema::create for creating new tables. you are using Schema::table and application expects that you are trying to modify an existing table.

so it would be something like this for create_users_table

```<code>public function up()
    {
      Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }
</code>```

Additional information

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,  created_at) values
  (dasdasd, vincentnelissen@hotmail.nl, 1, 2017-03-31 15:41:51,
  2017-03-31 15:41:51))

This error is because that you are trying to save a record to a table which doesn't have nerd_level field on it. so if you have created a migration and ran it first and later when you add the field it wont work. so you need to either rollback migration before bringing any changes to the file or should create a new migration for just adding nerd_level field to the existing table.

1st method

to rollback the migrations run following command until the create_users_table is rolled back or declare the step. see docs
Rolling Back Migrations

php artisan migrate:rollback

bring the required changes add following line.

$table->integer('nerd_level');

run migration again

php artisan migrate

2nd method (preferred way). See docs Modifying Columns

leave existing create_users_table as it is without $table->integer('nerd_level');

create a new seperate migration to just add the new column.

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

this error is because as the error describes you are trying to access a property of null object, it means that you need to first have that user(model) exist on table to be able to access its properties.

Body:
This is my code from create_users_table.php

public function up()
    {
      Schema::table('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,
  created_at) values (dasdasd, vincentnelissen@hotmail.nl, 1,
  2017-03-31 15:41:51, 2017-03-31 15:41:51))

And when I try to edit a nerd I get the following error:

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

This is my code from edit.blade.php:

     <!DOCTYPE html>

        <title>Look! I'm CRUDding</title>
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap
        /3.0.0  /css/bootstrap.min.css">

    Nerd Alert

View All Nerds

Create a Nerd

Edit {{ $nerd->name }}

  {{ HTML::ul($errors->all()) }}

 {{ Form::model($nerd, array('route' => array('nerds.update',
  $nerd->id),   'method' => 'PUT')) }}

    {{ Form::label('name', 'Name') }}
    {{ Form::text('name', null, array('class' => 'form-control')) }}

    {{ Form::label('email', 'Email') }}
    {{ Form::email('email', null, array('class' => 'form-control')) }}

    {{ Form::label('nerd_level', 'Nerd Level') }}
    {{ Form::select('nerd_level', array('0' => 'Select a Level', '1' =>
    'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement
    Dweller'), null, array('class' => 'form-control')) }}

{{ Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) }}

 {{ Form::close() }}

And when I try to delete a nerd This is the error:

FatalErrorException in NerdController.php line 128: Call to a member
  function delete() on null

return Redirect is php line 128

public function destroy($id)
{
    // delete
    $nerd = User::find($id);
    $nerd->delete();

    // redirect
    Session::flash('message', 'Successfully deleted the nerd!');
    return Redirect::to('nerds');
}

This Error can be profitable to others who have similar problems , so they know what to change in their code as well. Or not to make a similar mistake to whoever reads it first.

Can anyone help me ?

Kind regards,

Vincent

Body:
instead of Schema::table use Schema::create for creating new tables. you are using Schema::table and application expects that you are trying to modify an existing table.

so it would be something like this for create_users_table

public function up()
    {
      Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }

Additional information

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,  created_at) values
  (dasdasd, vincentnelissen@hotmail.nl, 1, 2017-03-31 15:41:51,
  2017-03-31 15:41:51))

This error is because that you are trying to save a record to a table which doesn't have nerd_level field on it. so if you have created a migration and ran it first and later when you add the field it wont work. so you need to either rollback migration before bringing any changes to the file or should create a new migration for just adding nerd_level field to the existing table.

1st method

to rollback the migrations run following command until the create_users_table is rolled back or declare the step. see docs
Rolling Back Migrations

php artisan migrate:rollback

bring the required changes add following line.

$table->integer('nerd_level');

run migration again

php artisan migrate

2nd method (preferred way). See docs Modifying Columns

leave existing create_users_table as it is without $table->integer('nerd_level');

create a new seperate migration to just add the new column.

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

this error is because as the error describes you are trying to access a property of null object, it means that you need to first have that user(model) exist on table to be able to access its properties.


问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答:
Assuming you start with a collection of strings, a simple comparer should do the job:

```<code>public class Comparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        int ia = 0;
        int ib = 0;
        var aIsInt = int.TryParse(a,out ia);
        var bIsInt = int.TryParse(b,out ib);
        if (aIsInt == bIsInt)
        {
            if (aIsInt)
            {
                return ia.CompareTo(ib);
            }
            else
            {
                return a.CompareTo(b);
            }
        }
        return aIsInt ? -1 : 1;
    }
}
</code>```

Here's a fiddle

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

Body:
Assuming you start with a collection of strings, a simple comparer should do the job:

public class Comparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        int ia = 0;
        int ib = 0;
        var aIsInt = int.TryParse(a,out ia);
        var bIsInt = int.TryParse(b,out ib);
        if (aIsInt == bIsInt)
        {
            if (aIsInt)
            {
                return ia.CompareTo(ib);
            }
            else
            {
                return a.CompareTo(b);
            }
        }
        return aIsInt ? -1 : 1;
    }
}

Here's a fiddle


问:
Javascript Set ES6
Is there a way to insert an item as first element of Set in javascript like it is done in arrays in the example below ?</p>

```<code>arr['a','b','c']
arr.unshift ('d')
//Result
arr['d','a','b','c']
</code>```

答:
The order of a Set is determined by when the items are inserted. Depending on what you want to do you can either insert items into a Set then extract those values and sort as needed or you can insert them into an array in the correct order then create a Set from that array.

let standardSet = new Set();
standardSet.add('c');
standardSet.add('a');
standardSet.add('b');
let fromStandard = Array.from(standardSet);
fromStandard.sort();
console.log(fromStandard);

let arr = [];
arr.unshift('c');
arr.unshift('b');
arr.unshift('a');
let fromArr = Array.from(new Set(arr));
console.log(fromArr);```

Title: Javascript Set ES6

Body:
Is there a way to insert an item as first element of Set in javascript like it is done in arrays in the example below ?

arr['a','b','c']
arr.unshift ('d')
//Result
arr['d','a','b','c']


问:
Accessing fields of JSON string in C#
I'm trying to access specific fields of a json string returned when I authenticate to an API. When I attempt to print or manipulate the string I receive

System.NullReferenceException: 'Object reference not set to an instance of an object.'

```<code>var response = client.GetAsync(fullUri).Result;
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("StatusCode : " + (int)response.StatusCode + " " + response.StatusCode.ToString());

var jo = JObject.Parse(content);
var token = jo["Result"]["Token"].ToString(); //error mentioned above received here
Console.WriteLine(token.ToString());          //error mentioned above also recieved here
Console.WriteLine(content);                   //error mentioned above received here too
</code>```

the string "content" holds the json looking like this:

```<code>{
    "Result":{
        "TenantId":"1",
        "Token":"38255507",
        "UserName":"kadmin",
        "RoleId":2,
        "ScopeId":"2",
        "AdminId":16596942,
        "MachineId":null,
        "MachineGroupName":null,
        "CultureInfo":"en-US",
        "TimePref":"Browser",
        "OffSetInMinutes":420,
        "Attributes":null
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}
</code>```

I've tried applying many examples I've seen on stackoverflow but none seem to work

答:
The key is case sensitive. All you need to do is change

```<code>var token = jo["result"]["Token"].ToString();
</code>```

to

```<code>var token = jo["Result"]["Token"].ToString();
</code>```

Title: Accessing fields of JSON string in C#

Body:
I'm trying to access specific fields of a json string returned when I authenticate to an API. When I attempt to print or manipulate the string I receive

System.NullReferenceException: 'Object reference not set to an instance of an object.'

var response = client.GetAsync(fullUri).Result;
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("StatusCode : " + (int)response.StatusCode + " " + response.StatusCode.ToString());

var jo = JObject.Parse(content);
var token = jo["Result"]["Token"].ToString(); //error mentioned above received here
Console.WriteLine(token.ToString());          //error mentioned above also recieved here
Console.WriteLine(content);                   //error mentioned above received here too

the string "content" holds the json looking like this:

{
    "Result":{
        "TenantId":"1",
        "Token":"38255507",
        "UserName":"kadmin",
        "RoleId":2,
        "ScopeId":"2",
        "AdminId":16596942,
        "MachineId":null,
        "MachineGroupName":null,
        "CultureInfo":"en-US",
        "TimePref":"Browser",
        "OffSetInMinutes":420,
        "Attributes":null
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}

I've tried applying many examples I've seen on stackoverflow but none seem to work

Body:
The key is case sensitive. All you need to do is change

var token = jo["result"]["Token"].ToString();

to

var token = jo["Result"]["Token"].ToString();


问:
4x 25% boxes in one line
I started learning CSS3 and got a problem, i want to create 4 black boxes(divs), and put them on in one line, 3 of them work properly, but 4th is moving to new line, what am i doing wrong?

My guess would be that its because of the 10px margin, but i dont know how to do it properly.

* {
    margin: 0px;
    padding: 0px; }

body {
    font-family: Roboto, sans-serif;
    box-sizing: border-box; }

#wrapper {
    width: 1000px;
    margin-left: auto;
    margin-right: auto; }

#block1 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block2 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block3 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block4 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="wrapper">
        <div id="block1"></div>
        <div id="block2"></div>
        <div id="block3"></div>
        <div id="block4"></div>
    </div> </body></code>```

答:
Or try reducing your % by 1%. </p>

```<code>#block4 {
width: 24%;
height: 100px;
background-color: black;
float: left;
margin-right: 10px;
}
</code>```

Title: 4x 25% boxes in one line

Body:
Or try reducing your % by 1%.

#block4 {
width: 24%;
height: 100px;
background-color: black;
float: left;
margin-right: 10px;
}


问:
Laravel 5.3 - No break between lines in mail notification?
I send an email out via the toMail channel, which is saved from a text area where I hit enter twice for new line, so it looks like this in the input:

```<code>Line 1

Line 2 with space above and below

Line 3
</code>```

When I use that text in the mail like this:

```<code>return (new MailMessage)->subject('test spacing')
                        ->line($this->text);
</code>```

It looks like this in the email:

```<code>Line 1 Line 2 with space above and below Line 3
</code>```

I changed the relevant section in email.blade.php from:

```<code>@foreach ($introLines as $line)
  {{ $line }}
@endforeach
</code>```

To:

```<code>@foreach ($introLines as $line)
  {!! nl2br(htmlspecialchars($line)) !!}
@endforeach
</code>```

But that still didn't work. In the notifications table in the db, it is saved as:

```<code>Line 1\n\nLine 2 with space above and below\n\nLine 3
</code>```

Any idea how to get the sent email to show the spacing so it's not just one big blob?

UPDATE:

So laravel inserts the notification with \n\n in the notifications table, but it is actually saved in the model table like this:

Which is what is passed to the email, but still not sure how to get those spaces in the email.

答:
simply add some html tags to make a wrap to new line

```<code>@foreach ($introLines as $line)
  <p>{{ $line }}</p>
  // or use <br />
@endforeach
</code>```

however to add new line breaks to in markdown you may do :

1 -

To have a line break without a paragraph, you will need to use two
  trailing spaces with one enter.

source

2 -

use ordinary

source : laravel docs

Body:
I send an email out via the toMail channel, which is saved from a text area where I hit enter twice for new line, so it looks like this in the input:

Line 1

Line 2 with space above and below

Line 3

When I use that text in the mail like this:

return (new MailMessage)->subject('test spacing')
                        ->line($this->text);

It looks like this in the email:

Line 1 Line 2 with space above and below Line 3

I changed the relevant section in email.blade.php from:

@foreach ($introLines as $line)
  {{ $line }}
@endforeach

To:

@foreach ($introLines as $line)
  {!! nl2br(htmlspecialchars($line)) !!}
@endforeach

But that still didn't work. In the notifications table in the db, it is saved as:

Line 1\n\nLine 2 with space above and below\n\nLine 3

Any idea how to get the sent email to show the spacing so it's not just one big blob?

UPDATE:

So laravel inserts the notification with \n\n in the notifications table, but it is actually saved in the model table like this:

Which is what is passed to the email, but still not sure how to get those spaces in the email.

Body:
simply add some html tags to make a wrap to new line

@foreach ($introLines as $line)
  <p>{{ $line }}</p>
  // or use <br />
@endforeach

however to add new line breaks to in markdown you may do :

1 -

To have a line break without a paragraph, you will need to use two
  trailing spaces with one enter.

source

2 -

use ordinary <br />

source : laravel docs


问:
Typescript Class Becoming Empty
Given a specific setup in typescript I end up at runtime with empty class objects in javascript. The setup is simply 2 classes referencing each other will equal one of them being empty in the scope of the other. I know how to avoid it (by introducing a third class in between the 2) but I'm curious as to why it happens and is there a way to still make those cross references and still have a working code. I tried tons of setup to try to make it work so here's what I found.

Setup: each class in its own module (module names and class names irrelevant)
ClassA is our main entry:

// ClassA

```<code>import ClassB = require('ClassB');
import ClassC = require('ClassC');

class ClassA
{
    constructor()
    {
        console.log(ClassC.TEST);// shows 1
        new ClassB();// shows null
        console.log(ClassC.TEST);// shows 1
    }
}
export = ClassA;
</code>```

// ClassB (in different module)

```<code>import ClassC = require('ClassC');

class ClassB
{
    public static ClassBRef:any;

    constructor()
    {
        console.log(ClassC.TEST);// in this scope ClassC is an empty object with no properties
    }
}
export = ClassB;
</code>```

// ClassC (in different module)

```<code>import ClassB = require('ClassB');

class ClassC
{
    public static TEST:number = 1;

    constructor()
    {
        ClassB.ClassBRef;
    }
}
export = ClassC;
</code>```

Because ClassB references ClassC and ClassC references ClassB here's the result: ClassC within ClassA scope exist without problem but within ClassB scope, ClassC is an empty object at runtime with no properties. In other words in typescript everything is fine but javascript will not have it. Changing module names, location, class names, using static or instance scope, in constructor or instance methods or static methods, etc .. makes no difference and ClassC is always empty in ClassB scope.

Like I said the fix is to have a third class handling communication with the 2 faulty classes (so at least one of the 2 classes has NO references to the second one) but again my question is, how to do it without needing a third class and without removing the cross reference between the 2 classes?

答:
Use the syntax
import { ClassC } from "./ClassC"; for importing the classes, instead of import ClassC = require('ClassC');

Class B:

```<code>import { ClassC } from "./ClassC"; // use this syntax

class ClassB
{
    public static ClassBRef:any;

    constructor()
    {
        console.log(ClassC.TEST);
    }
}
export { ClassB };
</code>```

Class C:

```<code>import { ClassB } from "./ClassB"; // use this syntax

class ClassC
{
    public static TEST:number = 1;

    constructor()
    {
        ClassB.ClassBRef;
    }
}

export { ClassC };
</code>```

Title: Typescript Class Becoming Empty

Body:
Given a specific setup in typescript I end up at runtime with empty class objects in javascript. The setup is simply 2 classes referencing each other will equal one of them being empty in the scope of the other. I know how to avoid it (by introducing a third class in between the 2) but I'm curious as to why it happens and is there a way to still make those cross references and still have a working code. I tried tons of setup to try to make it work so here's what I found.

Setup: each class in its own module (module names and class names irrelevant)
ClassA is our main entry:

// ClassA

import ClassB = require('ClassB');
import ClassC = require('ClassC');

class ClassA
{
    constructor()
    {
        console.log(ClassC.TEST);// shows 1
        new ClassB();// shows null
        console.log(ClassC.TEST);// shows 1
    }
}
export = ClassA;

// ClassB (in different module)

import ClassC = require('ClassC');

class ClassB
{
    public static ClassBRef:any;

    constructor()
    {
        console.log(ClassC.TEST);// in this scope ClassC is an empty object with no properties
    }
}
export = ClassB;

// ClassC (in different module)

import ClassB = require('ClassB');

class ClassC
{
    public static TEST:number = 1;

    constructor()
    {
        ClassB.ClassBRef;
    }
}
export = ClassC;

Because ClassB references ClassC and ClassC references ClassB here's the result: ClassC within ClassA scope exist without problem but within ClassB scope, ClassC is an empty object at runtime with no properties. In other words in typescript everything is fine but javascript will not have it. Changing module names, location, class names, using static or instance scope, in constructor or instance methods or static methods, etc .. makes no difference and ClassC is always empty in ClassB scope.

Like I said the fix is to have a third class handling communication with the 2 faulty classes (so at least one of the 2 classes has NO references to the second one) but again my question is, how to do it without needing a third class and without removing the cross reference between the 2 classes?

Body:
Use the syntax
import { ClassC } from "./ClassC"; for importing the classes, instead of import ClassC = require('ClassC');

Class B:

import { ClassC } from "./ClassC"; // use this syntax

class ClassB
{
    public static ClassBRef:any;

    constructor()
    {
        console.log(ClassC.TEST);
    }
}
export { ClassB };

Class C:

import { ClassB } from "./ClassB"; // use this syntax

class ClassC
{
    public static TEST:number = 1;

    constructor()
    {
        ClassB.ClassBRef;
    }
}

export { ClassC };


问:
BigQuery: Convert accented characters to their plain ascii equivalents
I have the following string:

```<code>brasília
</code>```

And I need to convert to:

```<code>brasilia
</code>```

Withou the ´ accent!

How can I do on BigQuery?

Thank you!

答:
Try below as quick and simple option for you:

#standardSQL
WITH lookups AS (
  SELECT
  'ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,ñ' AS accents,
  'c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,n' AS latins
),
pairs AS (
  SELECT accent, latin FROM lookups,
    UNNEST(SPLIT(accents)) AS accent WITH OFFSET AS p1,
    UNNEST(SPLIT(latins)) AS latin WITH OFFSET AS p2
  WHERE p1 = p2
),
yourTableWithWords AS (
  SELECT word FROM UNNEST(
        SPLIT('brasília,ångström,aperçu,barège, beau idéal, belle époque, béguin, bête noire, bêtise, Bichon Frisé, blasé, blessèd, bobèche, boîte, bombé, Bön, Boötes, boutonnière, bric-à-brac, Brontë Beyoncé,El Niño')
    ) AS word
)
SELECT
  word AS word_with_accent,
  (SELECT STRING_AGG(IFNULL(latin, char), '')
    FROM UNNEST(SPLIT(word, '')) char
    LEFT JOIN pairs
    ON char = accent) AS word_without_accent
FROM yourTableWithWords
```

<p>Output is   </p>

<pre class="lang-sql prettyprint-override"><code>word_with_accent word_without_accent
blessèd         blessed
El Niño         El Nino
belle époque    belle epoque
boîte           boite
Boötes          Bootes
blasé           blase
ångström        angstrom
bobèche         bobeche
barège          barege
bric-à-brac     bric-a-brac
bête noire      bete noire
Bichon Frisé    Bichon Frise
Brontë Beyoncé  Bronte Beyonce
bêtise          betise
beau idéal      beau ideal
bombé           bombe
brasília        brasilia
boutonnière     boutonniere
aperçu          apercu
béguin          beguin
Bön             Bon
</code>```

UPDATE

Below is how to pack this logic into SQL UDF - so accent2latin(word) can be called to make a "magic"

#standardSQL
CREATE TEMP FUNCTION accent2latin(word STRING) AS
((
  WITH lookups AS (
    SELECT
    'ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,ñ' AS accents,
    'c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,n' AS latins
  ),
  pairs AS (
    SELECT accent, latin FROM lookups,
      UNNEST(SPLIT(accents)) AS accent WITH OFFSET AS p1,
      UNNEST(SPLIT(latins)) AS latin WITH OFFSET AS p2
    WHERE p1 = p2
  )
  SELECT STRING_AGG(IFNULL(latin, char), '')
  FROM UNNEST(SPLIT(word, '')) char
  LEFT JOIN pairs
  ON char = accent
));

WITH yourTableWithWords AS (
  SELECT word FROM UNNEST(
        SPLIT('brasília,ångström,aperçu,barège, beau idéal, belle époque, béguin, bête noire, bêtise, Bichon Frisé, blasé, blessèd, bobèche, boîte, bombé, Bön, Boötes, boutonnière, bric-à-brac, Brontë Beyoncé,El Niño')
    ) AS word
)
SELECT
  word AS word_with_accent,
  accent2latin(word) AS word_without_accent
FROM yourTableWithWords
```

Body:
I have the following string:

brasília

And I need to convert to:

brasilia

Withou the ´ accent!

How can I do on BigQuery?

Thank you!

Body:
Try below as quick and simple option for you:

#standardSQL
WITH lookups AS (
  SELECT
  'ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,ñ' AS accents,
  'c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,n' AS latins
),
pairs AS (
  SELECT accent, latin FROM lookups,
    UNNEST(SPLIT(accents)) AS accent WITH OFFSET AS p1,
    UNNEST(SPLIT(latins)) AS latin WITH OFFSET AS p2
  WHERE p1 = p2
),
yourTableWithWords AS (
  SELECT word FROM UNNEST(
        SPLIT('brasília,ångström,aperçu,barège, beau idéal, belle époque, béguin, bête noire, bêtise, Bichon Frisé, blasé, blessèd, bobèche, boîte, bombé, Bön, Boötes, boutonnière, bric-à-brac, Brontë Beyoncé,El Niño')
    ) AS word
)
SELECT
  word AS word_with_accent,
  (SELECT STRING_AGG(IFNULL(latin, char), '')
    FROM UNNEST(SPLIT(word, '')) char
    LEFT JOIN pairs
    ON char = accent) AS word_without_accent
FROM yourTableWithWords

Output is

word_with_accent word_without_accent
blessèd         blessed
El Niño         El Nino
belle époque    belle epoque
boîte           boite
Boötes          Bootes
blasé           blase
ångström        angstrom
bobèche         bobeche
barège          barege
bric-à-brac     bric-a-brac
bête noire      bete noire
Bichon Frisé    Bichon Frise
Brontë Beyoncé  Bronte Beyonce
bêtise          betise
beau idéal      beau ideal
bombé           bombe
brasília        brasilia
boutonnière     boutonniere
aperçu          apercu
béguin          beguin
Bön             Bon

UPDATE

Below is how to pack this logic into SQL UDF - so accent2latin(word) can be called to make a "magic"

#standardSQL
CREATE TEMP FUNCTION accent2latin(word STRING) AS
((
  WITH lookups AS (
    SELECT
    'ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,ñ' AS accents,
    'c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,n' AS latins
  ),
  pairs AS (
    SELECT accent, latin FROM lookups,
      UNNEST(SPLIT(accents)) AS accent WITH OFFSET AS p1,
      UNNEST(SPLIT(latins)) AS latin WITH OFFSET AS p2
    WHERE p1 = p2
  )
  SELECT STRING_AGG(IFNULL(latin, char), '')
  FROM UNNEST(SPLIT(word, '')) char
  LEFT JOIN pairs
  ON char = accent
));

WITH yourTableWithWords AS (
  SELECT word FROM UNNEST(
        SPLIT('brasília,ångström,aperçu,barège, beau idéal, belle époque, béguin, bête noire, bêtise, Bichon Frisé, blasé, blessèd, bobèche, boîte, bombé, Bön, Boötes, boutonnière, bric-à-brac, Brontë Beyoncé,El Niño')
    ) AS word
)
SELECT
  word AS word_with_accent,
  accent2latin(word) AS word_without_accent
FROM yourTableWithWords


问:
MView "enable query rewrite" usage
```<code>CREATE TABLE TEST_DATE(COL1 VARCHAR2(20),COL2 NUMBER,COL3_DATE DATE,COL4_DATE DATE)
/

create materialized view TEST_SYS
REFRESH FORCE ON DEMAND
ENABLE QUERY REWRITE  --- ????
AS
SELECT COL1,COL2
FROM    TEST_date
WHERE TRUNC(SYSDATE) BETWEEN TRUNC(COL3_DATE) AND TRUNC(COL4_DATE)
/
</code>```

If Enable Query Rewrite option is disabled, MView is getting created for the above query then what is the purpose of having ENABLE QUERY REWRITE clause while creating materialized view, can we remove it and create it, and do we have to compromise on the performance of the MView if we have to comment Enable Query Rewrite.

Please explain me the use of enable query rewrite option in detail.

答: You do not need to have query rewrite enabled.  Further, given your mview definition, it probably wouldn't hep you anyway.</p>

Title: MView "enable query rewrite" usage

Body:
CREATE TABLE TEST_DATE(COL1 VARCHAR2(20),COL2 NUMBER,COL3_DATE DATE,COL4_DATE DATE)
/

create materialized view TEST_SYS
REFRESH FORCE ON DEMAND
ENABLE QUERY REWRITE  --- ????
AS
SELECT COL1,COL2
FROM    TEST_date
WHERE TRUNC(SYSDATE) BETWEEN TRUNC(COL3_DATE) AND TRUNC(COL4_DATE)
/

If Enable Query Rewrite option is disabled, MView is getting created for the above query then what is the purpose of having ENABLE QUERY REWRITE clause while creating materialized view, can we remove it and create it, and do we have to compromise on the performance of the MView if we have to comment Enable Query Rewrite.

Please explain me the use of enable query rewrite option in detail.


问:
Is there anything that might not work on office excel 2007 compare to office excel 2016?
Our company is planning to upgrade Office 2007 to Office 2016. We have worksheets that uses macros. Is it going to be an issues that anyone know of when they have transition from earlier version to Office 2016?</p>

答:
Googling "ms office vba compatibility 2007 2010 2016" yields some helpful results:

M$ has some telemetry information published in Compatibility issues in Office. It's primarily UI controls and components that are dropped from later versions

At M$ forums, someone asking the same question is being pointed to the same link that @Ralph gave

Users mention issues with API calls in VBA compatibility issues: Excel 2007, 2010, 2013 (although that's not the OP's problem apparently)

If you're upgrading your business environment, you'll be testing it out anyway prior to mass deployment - at least, all the common use cases.


问:
Sending curl requests in Groovy script
I am having difficulty sending a curl request within a Groovy script.

I keep getting invalid payload and globbing errors. If I do the following within my terminal it works fine

```<code>curl -X POST -H 'Content-type: application/json' --data '{"attachments": [{"color": "#2A9B3A", "author_name": "Richard Lewis", "title": "MY Build Status", "title_link": "http://example.co.uk", "text": "Successful Build" }]}' https://hooks.slack.com/services/webhook
</code>```

But when I try and do this within my Groovy script it fails

```<code>sh """#!/bin/bash -l
      curl -X POST -H 'Content-type: application/json' --data {"attachments": [{"color": "#2A9B3A", "author_name": "Richard Lewis", "title": "My Build Status", "title_link": "http://example.co.uk", "text": "Successful Build" }]} "https://hooks.slack.com/services/T122JHEUW/webhook"
   """
</code>```

How would I format this correctly or is there a better way to send this request? It would be cleaner if i could save the --data in a variable to pass into my request I know but I had problems with that also (payload errors), I guess down to formatting again.

答:
I can't see any wrapping around your json (using quotes) after --data. May be that is a reason. You can try using single quote around your json (similar to your other curl command, i.e. --data '{...}')

There is an option using json into a file and then use --data-binary to post from a file. For example the below one.

```<code>--data-binary "@my.json"
</code>```

And, finally, of course you may use any groovy client (or library) that do similar things like curl. I don't know much about groovy.

Title: Sending curl requests in Groovy script

Body:
I am having difficulty sending a curl request within a Groovy script.

I keep getting invalid payload and globbing errors. If I do the following within my terminal it works fine

curl -X POST -H 'Content-type: application/json' --data '{"attachments": [{"color": "#2A9B3A", "author_name": "Richard Lewis", "title": "MY Build Status", "title_link": "http://example.co.uk", "text": "Successful Build" }]}' https://hooks.slack.com/services/webhook

But when I try and do this within my Groovy script it fails

sh """#!/bin/bash -l
      curl -X POST -H 'Content-type: application/json' --data {"attachments": [{"color": "#2A9B3A", "author_name": "Richard Lewis", "title": "My Build Status", "title_link": "http://example.co.uk", "text": "Successful Build" }]} "https://hooks.slack.com/services/T122JHEUW/webhook"
   """

How would I format this correctly or is there a better way to send this request? It would be cleaner if i could save the --data in a variable to pass into my request I know but I had problems with that also (payload errors), I guess down to formatting again.

Body:
I can't see any wrapping around your json (using quotes) after --data. May be that is a reason. You can try using single quote around your json (similar to your other curl command, i.e. --data '{...}')

There is an option using json into a file and then use --data-binary to post from a file. For example the below one.

--data-binary "@my.json"

And, finally, of course you may use any groovy client (or library) that do similar things like curl. I don't know much about groovy.


问:
How to save the predictions of YOLO (You Only Look Once) Object detection in a jsonb field in a database
I want to run Darknet(YOLO) on a number of images and store its predictions in PostgreSQL Database.

This is the structure of my table:

```<code>sample=> \d+ prediction2;
                       Table "public.prediction2"
   Column    | Type  | Modifiers | Storage  | Stats target | Description
-------------+-------+-----------+----------+--------------+-------------
 path        | text  | not null  | extended |              |
 pred_result | jsonb |           | extended |              |
Indexes:
    "prediction2_pkey" PRIMARY KEY, btree (path)
</code>```

Darknet(YOLO)'s source files are written in C.

I have already stored Caffe's predictions in the database as follows. I have listed one of the rows of my database here as an example.

```<code> path                                            |   pred_result
-------------------------------------------------+------------------------------------------------------------------------------------------------------------------
 /home/reena-mary/Pictures/predict/gTe5gy6xc.jpg | {"bow tie": 0.00631, "lab coat": 0.59257, "neck brace": 0.00428, "Windsor tie": 0.01155, "stethoscope": 0.36260}
</code>```

I want to add YOLO's predictions to the jsonb data of pred_result i.e for each image path and Caffe prediction result already stored in the database, I would like to append Darknet (YOLO's) predictions.

The reason I want to do this is to add search tags to each image. So, by running Caffe and Darknet on images, I want to be able to get enough labels that can help me make my image search better.

Kindly help me with how I should do this in Darknet.

答:
This is an issue I also encountered. Actually YOLO does not provide a JSON output interface, so there is no way to get the same output as from Caffe.

However, there is a pull request that you can merge to get workable output here: https://github.com/pjreddie/darknet/pull/34/files. It outputs CSV data, which you can convert to JSON to store in the database.

You could of course also alter the source code of YOLO to make your own implementation that outputs JSON directly.

Body:
I want to run Darknet(YOLO) on a number of images and store its predictions in PostgreSQL Database.

This is the structure of my table:

sample=> \d+ prediction2;
                       Table "public.prediction2"
   Column    | Type  | Modifiers | Storage  | Stats target | Description
-------------+-------+-----------+----------+--------------+-------------
 path        | text  | not null  | extended |              |
 pred_result | jsonb |           | extended |              |
Indexes:
    "prediction2_pkey" PRIMARY KEY, btree (path)

Darknet(YOLO)'s source files are written in C.

I have already stored Caffe's predictions in the database as follows. I have listed one of the rows of my database here as an example.

 path                                            |   pred_result
-------------------------------------------------+------------------------------------------------------------------------------------------------------------------
 /home/reena-mary/Pictures/predict/gTe5gy6xc.jpg | {"bow tie": 0.00631, "lab coat": 0.59257, "neck brace": 0.00428, "Windsor tie": 0.01155, "stethoscope": 0.36260}

I want to add YOLO's predictions to the jsonb data of pred_result i.e for each image path and Caffe prediction result already stored in the database, I would like to append Darknet (YOLO's) predictions.

The reason I want to do this is to add search tags to each image. So, by running Caffe and Darknet on images, I want to be able to get enough labels that can help me make my image search better.

Kindly help me with how I should do this in Darknet.


问:
best practice to backup config files Jenkins
I am using Jenkins on remote Debian 7.8 . I want to update Debian 7.8 to 8.7. I tried to update and it went fine however Jenkins was broken and could not start the service. I tried everything but could find any solution. Finally I used purged command and it deleted previous configurations and builds.

Now I restore the server and want to update again but I want a complete Jenkins backup of config  and builds so restore it from last running instance.

What's the best practice to backup the configs as simple as possible (with less effort and problems) and configure and then merge the backuped files.

Which data / config files I have to backup?

答:
The exact layout used by Jenkins is described by JENKINS_HOME directory

```<code>JENKINS_HOME
 +- config.xml     (jenkins root configuration)
 +- *.xml          (other site-wide configuration files)
 +- userContent    (files in this directory will be served under your http://server/userContent/)
 +- fingerprints   (stores fingerprint records)
 +- plugins        (stores plugins)
 +- workspace (working directory for the version control system)
     +- [JOBNAME] (sub directory for each job)
 +- jobs
     +- [JOBNAME]      (sub directory for each job)
         +- config.xml     (job configuration file)
         +- latest         (symbolic link to the last successful build)
         +- builds
             +- [BUILD_ID]     (for each build)
                 +- build.xml      (build result summary)
                 +- log            (log file)
                 +- changelog.xml  (change log)
</code>```

It comes with a simple directive:

All the settings, build logs, artifact archives are stored under the JENKINS_HOME directory. Simply archive this directory to make a back up.

Back ups can be taken without stopping the server, but when you restore, please do stop the server.

Body:
The exact layout used by Jenkins is described by JENKINS_HOME directory

JENKINS_HOME
 +- config.xml     (jenkins root configuration)
 +- *.xml          (other site-wide configuration files)
 +- userContent    (files in this directory will be served under your http://server/userContent/)
 +- fingerprints   (stores fingerprint records)
 +- plugins        (stores plugins)
 +- workspace (working directory for the version control system)
     +- [JOBNAME] (sub directory for each job)
 +- jobs
     +- [JOBNAME]      (sub directory for each job)
         +- config.xml     (job configuration file)
         +- latest         (symbolic link to the last successful build)
         +- builds
             +- [BUILD_ID]     (for each build)
                 +- build.xml      (build result summary)
                 +- log            (log file)
                 +- changelog.xml  (change log)

It comes with a simple directive:

All the settings, build logs, artifact archives are stored under the JENKINS_HOME directory. Simply archive this directory to make a back up.

Back ups can be taken without stopping the server, but when you restore, please do stop the server.