问:
label not moving with Vuejs2 + Materializejs
I have a problem with the label of a text input with materializejs + vuejs

the label does not move up if I change the value of the input field with vue (it behaves correctly if I change manually the input)

a simple (not elegant) code showing that is (also on JSfiddle):

correct expected behavior by editing the field manually

not correct behavior by clicking on the last div (starting from an empty field): it changes the value of the input without moving the label

html

```<code><div id=app>
  <div class="input-field ">
    <input type="text" v-model="value" id="field">
    <label for="field">Field</label>
  </div>

  <div @click="value='newValue'">
    clickOnMe
  </div>
</div>
</code>```

Javascript

```<code>new Vue({
  el: '#app',
  data: {
    value: ''
  }
})
</code>```

答:
See Prefilling Text Inputs section, seems there's a patch function that needs to be applied

```

<pre class="lang-js prettyprint-override"><code>methods: {
  clickMe() {
    this.value = 'newValue';
    $(document).ready(function() {
        Materialize.updateTextFields();
    });
  }
}
</code>```

Body:
I have a problem with the label of a text input with materializejs + vuejs

the label does not move up if I change the value of the input field with vue (it behaves correctly if I change manually the input)

a simple (not elegant) code showing that is (also on JSfiddle):

correct expected behavior by editing the field manually

not correct behavior by clicking on the last div (starting from an empty field): it changes the value of the input without moving the label

html

    <input type="text" v-model="value" id="field">
    Field

    clickOnMe

Javascript

new Vue({
  el: '#app',
  data: {
    value: ''
  }
})

Body:
See Prefilling Text Inputs section, seems there's a patch function that needs to be applied

<div @click="clickMe">

methods: {
  clickMe() {
    this.value = 'newValue';
    $(document).ready(function() {
        Materialize.updateTextFields();
    });
  }
}


来源: stackexchange

问:
Swift Multithreading Getter
I have a function getAccessToken() that makes an API call and may return on a separate thread but I need my program to wait until it returns to continue.

I know I can use dispatch to make sure it returns on the same thread but I am curious if a variable with a getter making the call would accomplish the same thing.

ex:

```<code>var accesstoken : String {
    get {
         return getAccessToken()
    }
}
</code>```

The reason I ask is because when I access the token I want to be able to just use one line of code instead of having to make sure to wait for the token to return every time.

Ideally I would be able to do something like Common.getAccessToken() or Common.accessToken and not have to do anything extra.

答:
Your code example doesn't achieve anything that a direct call getAccessToken() couldn't do. What you need is to wrap that call in a synchronous dispatch call:

```<code>class MyType {
    let queue: DispatchQueue

    //...

    private func generateAccessToken() -> String {
        //...
    }

    public var accessToken: String {
        return queue.sync { generateAccessToken() }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swift Multithreading Getter

Body:
I have a function getAccessToken() that makes an API call and may return on a separate thread but I need my program to wait until it returns to continue.

I know I can use dispatch to make sure it returns on the same thread but I am curious if a variable with a getter making the call would accomplish the same thing.

ex:

var accesstoken : String {
    get {
         return getAccessToken()
    }
}

The reason I ask is because when I access the token I want to be able to just use one line of code instead of having to make sure to wait for the token to return every time.

Ideally I would be able to do something like Common.getAccessToken() or Common.accessToken and not have to do anything extra.

Body:
Your code example doesn't achieve anything that a direct call getAccessToken() couldn't do. What you need is to wrap that call in a synchronous dispatch call:

class MyType {
    let queue: DispatchQueue

    //...

    private func generateAccessToken() -> String {
        //...
    }

    public var accessToken: String {
        return queue.sync { generateAccessToken() }
    }
}


问:
How can I write a shell script that goes into a screen and invokes something?
My IRC bot sporadically dies sometimes and I have it in a screen. The way to invoke it again is node protobot.js.

I have to always find that screen and reinvoke it. I'd like a faster way.

How can I invoke screen reliably from within a shell script in order to invoke node to revive it?

答:
Your process needs care and feeding? Do not put it in the screen to begin with.

Investigate process monitoring, for instance with Monit, or God, or some other keep-it-alive software. There are tons of alternatives. When you've seen these two, the Net should provide you with pros and cons and other names of software.

ContentLicense: CC BY-SA 2.5


问:
Output of the dplyr summarize() fundtion
Is there a convenient way to have dplyr::summarize_all() output the results in a more readable format without having to manually rearrange it after the fact?

Ultimately, I'd like to be able to port the output of summarize more easily to tables in Word, etc.

I would like to avoid the work of doing something like what's below.

Thank you

Example:

```<code>library(dplyr)
library(e1071) # for skewness() function
# make fake data
a <- rnorm(20)
b <- rnorm(20)
c <- rnorm(20)
x <- rnorm(20)
y <- rnorm(20)
z <- rnorm(20)

# create dataframe
dat = data.frame(a, b, c, x, y, z)

# run summarize()
descriptives <- dat %>% summarize_all(funs(mean, sd, skewness))
descriptives

# rearrange descriptives
matrix(descriptives, 6, 3,
    dimnames = list(c("a", "b", "c", "x", "y", "z"),
    c("mean", "SD", "skew")), byrow = FALSE)

# RETURNS
#  mean       SD        skew
#a 0.1533271  0.8106499 -0.02879986
#b -0.5117311 0.5608904 -0.2668225
#c 0.1267941  0.8214882 -0.4260682
#x 0.05337055 0.9817041 -0.1932566
#y -0.1091145 0.9050062 -0.3409686
#z -0.3195788 0.8833493 -0.6663437
</code>```

Body:
Is there a convenient way to have dplyr::summarize_all() output the results in a more readable format without having to manually rearrange it after the fact?

Ultimately, I'd like to be able to port the output of summarize more easily to tables in Word, etc.

I would like to avoid the work of doing something like what's below.

Thank you

Example:

library(dplyr)
library(e1071) # for skewness() function
# make fake data
a <- rnorm(20)
b <- rnorm(20)
c <- rnorm(20)
x <- rnorm(20)
y <- rnorm(20)
z <- rnorm(20)

# create dataframe
dat = data.frame(a, b, c, x, y, z)

# run summarize()
descriptives <- dat %>% summarize_all(funs(mean, sd, skewness))
descriptives

# rearrange descriptives
matrix(descriptives, 6, 3,
    dimnames = list(c("a", "b", "c", "x", "y", "z"),
    c("mean", "SD", "skew")), byrow = FALSE)

# RETURNS
#  mean       SD        skew
#a 0.1533271  0.8106499 -0.02879986
#b -0.5117311 0.5608904 -0.2668225
#c 0.1267941  0.8214882 -0.4260682
#x 0.05337055 0.9817041 -0.1932566
#y -0.1091145 0.9050062 -0.3409686
#z -0.3195788 0.8833493 -0.6663437

Body:
library(tidyr)
library(dplyr)
library(e1071) # for skewness() function
# make fake data
a <- rnorm(20)
b <- rnorm(20)
c <- rnorm(20)
x <- rnorm(20)
y <- rnorm(20)
z <- rnorm(20)

# create dataframe
dat = data.frame(a, b, c, x, y, z)

# run process
dat %>%
  summarize_all(funs(mean, sd, skewness)) %>%
  gather() %>%
  separate(key, c("var","type")) %>%
  spread(type, value)

#   var          mean        sd   skewness
# 1   a  0.0182792019 0.9098886 -0.3851676
# 2   b  0.0003444183 0.9815170  0.6032848
# 3   c -0.2724927337 0.9557808 -0.1961959
# 4   x -0.2679435647 0.6557561 -1.0111428
# 5   y -0.1951287997 0.8190830  0.5120989
# 6   z -0.0395147539 1.2758244  0.0464844


问:
How to create and populate json object in node js
In Java, there is JsonObject object= new JsonObject(); then one can add contents, how can I do this in node js?

答:
Json derives from Javascript, it means "JavaScript Object Notation". Thus, in js it is just a plain object:</p>

```<code>var obj = {};
obj.foo = "bar";
</code>```

Body:
Json derives from Javascript, it means "JavaScript Object Notation". Thus, in js it is just a plain object:

var obj = {};
obj.foo = "bar";


问:
How to have Nested Map RDD's in Spark
I have a text file like:-

```<code>ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867
</code>```

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

```<code>ratio = MAP.get(Hour).get(ID)
</code>```

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

```<code>JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));
</code>```

However, there is no lookup() like functionality available here, correct?

答:
For my use-case, I have decided to go with the following:-

I created a JavaPairRDD{Hour,MAP{ID,Ratio}}. At any time the task would be running, I would require the map corresponding to that hour only.
So I did the following:-

```<code>Map<String, Double> result = new HashMap<>();
 javaRDDPair.lookup(HOUR).stream().forEach(map ->{
            result.putAll(map.entrySet().stream().collect(Collectors.toMap(entry-> entry.getKey(), entry-> entry.getValue())));
        });
</code>```

This could now be further used as a broadcast variable.

Title: How to have Nested Map RDD's in Spark

Body:
I have a text file like:-

ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

ratio = MAP.get(Hour).get(ID)

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));

However, there is no lookup() like functionality available here, correct?

Body:
For my use-case, I have decided to go with the following:-

I created a JavaPairRDD{Hour,MAP{ID,Ratio}}. At any time the task would be running, I would require the map corresponding to that hour only.
So I did the following:-

Map<String, Double> result = new HashMap<>();
 javaRDDPair.lookup(HOUR).stream().forEach(map ->{
            result.putAll(map.entrySet().stream().collect(Collectors.toMap(entry-> entry.getKey(), entry-> entry.getValue())));
        });

This could now be further used as a broadcast variable.


问:
Error reported while running pyomo optimization with cbc solver and using timelimit
I am trying to solve Optimisation problem with pyomo (Pyomo 5.3 (CPython 2.7.13 on Linux 3.10.0-514.26.2.el7.x86_64)) using CBC solver (Version: 2.9.8) and specifying a time limit in solver of 60 sec. The solver is getting a feasible solution (-1415.8392) but apparently not yet optimal (-1415.84) as you can see below.

After time limit ends model seemingly exits with an error code. I want to print or get values of all variables of feasible solution using CBC in specified time limit. Or is there any other way by which I can set, if Model gets 99% value of an Optimal solution, to exit and print the feasible solution.

The error code is posted below.

```
Cbc0004I Integer solution of -1415.8392 found after 357760 iterations and 29278 nodes (47.87 seconds)
Cbc0010I After 30000 nodes, 6350 on tree, -1415.8392 best solution, best possible -1415.84 (48.87 seconds)
Cbc0010I After 31000 nodes, 6619 on tree, -1415.8392 best solution, best possible -1415.84 (50.73 seconds)
Cbc0010I After 32000 nodes, 6984 on tree, -1415.8392 best solution, best possible -1415.84 (52.49 seconds)
Cbc0010I After 33000 nodes, 7384 on tree, -1415.8392 best solution, best possible -1415.84 (54.31 seconds)
Cbc0010I After 34000 nodes, 7419 on tree, -1415.8392 best solution, best possible -1415.84 (55.73 seconds)
Cbc0010I After 35000 nodes, 7824 on tree, -1415.8392 best solution, best possible -1415.84 (57.37 seconds)
Traceback (most recent call last):
  File "model_final.py", line 392, in
    solver.solve(model, timelimit = 60*1, tee=True)
  File "/home/aditya/0r/lib/python2.7/site-packages/pyomo/opt/base/solvers.py", line 655, in solve
    default_variable_value=self._default_variable_value)
  File "/home/aditya/0r/lib/python2.7/site-packages/pyomo/core/base/PyomoModel.py", line 242, in load_from
    % str(results.solver.status))
ValueError: Cannot load a SolverResults object with bad status: error
```

When I run the model generated by pyomo manually using the same command-line parameters as pyomo /usr/bin/cbc -sec 60 -printingOptions all -import /tmp/tmpJK1ieR.pyomo.lp -import -stat=1 -solve -solu /tmp/tmpJK1ieR.pyomo.soln it seems to exit normally and also writes the solution as shown below.

```
Cbc0010I After 35000 nodes, 7824 on tree, -1415.8392 best solution, best possible -1415.84 (57.06 seconds)
Cbc0038I Full problem 205 rows 289 columns, reduced to 30 rows 52 columns
Cbc0010I After 36000 nodes, 8250 on tree, -1415.8392 best solution, best possible -1415.84 (58.73 seconds)
Cbc0020I Exiting on maximum time
Cbc0005I Partial search - best objective -1415.8392 (best possible -1415.84), took 464553 iterations and 36788 nodes (60.11 seconds)
Cbc0032I Strong branching done 15558 times (38451 iterations), fathomed 350 nodes and fixed 2076 variables
Cbc0035I Maximum depth 203, 5019 variables fixed on reduced cost
Cbc0038I Probing was tried 31933 times and created 138506 cuts of which 0 were active after adding rounds of cuts (4.431 seconds)
Cbc0038I Gomory was tried 30898 times and created 99534 cuts of which 0 were active after adding rounds of cuts (4.855 seconds)
Cbc0038I Knapsack was tried 30898 times and created 12926 cuts of which 0 were active after adding rounds of cuts (8.271 seconds)
Cbc0038I Clique was tried 100 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
Cbc0038I MixedIntegerRounding2 was tried 30898 times and created 13413 cuts of which 0 were active after adding rounds of cuts (3.652 seconds)
Cbc0038I FlowCover was tried 100 times and created 4 cuts of which 0 were active after adding rounds of cuts (0.019 seconds)
Cbc0038I TwoMirCuts was tried 30898 times and created 15292 cuts of which 0 were active after adding rounds of cuts (2.415 seconds)
Cbc0038I Stored from first was tried 30898 times and created 15734 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
Cbc0012I Integer solution of -1411.9992 found by Reduced search after 467825 iterations and 36838 nodes (60.12 seconds)
Cbc0020I Exiting on maximum time
Cbc0005I Partial search - best objective -1411.9992 (best possible -1415.4522), took 467825 iterations and 36838 nodes (60.12 seconds)
Cbc0032I Strong branching done 476 times (1776 iterations), fathomed 1 nodes and fixed 18 variables
Cbc0035I Maximum depth 21, 39 variables fixed on reduced cost
Cuts at root node changed objective from -1484.12 to -1415.45
Probing was tried 133 times and created 894 cuts of which 32 were active after adding rounds of cuts (0.060 seconds)
Gomory was tried 133 times and created 1642 cuts of which 0 were active after adding rounds of cuts (0.047 seconds)
Knapsack was tried 133 times and created 224 cuts of which 0 were active after adding rounds of cuts (0.083 seconds)
Clique was tried 100 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.001 seconds)
MixedIntegerRounding2 was tried 133 times and created 163 cuts of which 0 were active after adding rounds of cuts (0.034 seconds)
FlowCover was tried 100 times and created 5 cuts of which 0 were active after adding rounds of cuts (0.026 seconds)
TwoMirCuts was tried 133 times and created 472 cuts of which 0 were active after adding rounds of cuts (0.021 seconds)
ImplicationCuts was tried 25 times and created 41 cuts of which 0 were active after adding rounds of cuts (0.003 seconds)

Result - Stopped on time limit

Objective value:                -1411.99922848
Lower bound:                    -1415.452
Gap:                            0.00
Enumerated nodes:               36838
Total iterations:               467825
Time (CPU seconds):             60.13
Time (Wallclock seconds):       60.98

Total time (CPU seconds):       60.13   (Wallclock seconds):       61.01
```

The top few lines of the CBC solution file are:

```
Stopped on time - objective value -1411.99922848
      0 c_e_x1454_                         0                       0
      1 c_e_x1455_                         0                       0
      2 c_e_x1456_                         0                       0
      3 c_e_x1457_                         0                       0
      4 c_e_x1458_                         0                       0
      5 c_e_x1459_                         0                       0
      6 c_e_x1460_                         0                       0
      7 c_e_x1461_                         0                       0
      8 c_e_x1462_                         0                       0
```

Can anyone tell me how can I get these values without generating any error?

Thanks in advance.

答: You could try to set the bound gap tolerance such that it will accept the other answer. I'm surprised that the solver status is coming back with error if there is a feasible solution found. Could you print out the whole results object?</p>

Body:
I am trying to solve Optimisation problem with pyomo (Pyomo 5.3 (CPython 2.7.13 on Linux 3.10.0-514.26.2.el7.x86_64)) using CBC solver (Version: 2.9.8) and specifying a time limit in solver of 60 sec. The solver is getting a feasible solution (-1415.8392) but apparently not yet optimal (-1415.84) as you can see below.

After time limit ends model seemingly exits with an error code. I want to print or get values of all variables of feasible solution using CBC in specified time limit. Or is there any other way by which I can set, if Model gets 99% value of an Optimal solution, to exit and print the feasible solution.

The error code is posted below.

Cbc0004I Integer solution of -1415.8392 found after 357760 iterations and 29278 nodes (47.87 seconds)
Cbc0010I After 30000 nodes, 6350 on tree, -1415.8392 best solution, best possible -1415.84 (48.87 seconds)
Cbc0010I After 31000 nodes, 6619 on tree, -1415.8392 best solution, best possible -1415.84 (50.73 seconds)
Cbc0010I After 32000 nodes, 6984 on tree, -1415.8392 best solution, best possible -1415.84 (52.49 seconds)
Cbc0010I After 33000 nodes, 7384 on tree, -1415.8392 best solution, best possible -1415.84 (54.31 seconds)
Cbc0010I After 34000 nodes, 7419 on tree, -1415.8392 best solution, best possible -1415.84 (55.73 seconds)
Cbc0010I After 35000 nodes, 7824 on tree, -1415.8392 best solution, best possible -1415.84 (57.37 seconds)
Traceback (most recent call last):
  File "model_final.py", line 392, in
    solver.solve(model, timelimit = 60*1, tee=True)
  File "/home/aditya/0r/lib/python2.7/site-packages/pyomo/opt/base/solvers.py", line 655, in solve
    default_variable_value=self._default_variable_value)
  File "/home/aditya/0r/lib/python2.7/site-packages/pyomo/core/base/PyomoModel.py", line 242, in load_from
    % str(results.solver.status))
ValueError: Cannot load a SolverResults object with bad status: error

When I run the model generated by pyomo manually using the same command-line parameters as pyomo /usr/bin/cbc -sec 60 -printingOptions all -import /tmp/tmpJK1ieR.pyomo.lp -import -stat=1 -solve -solu /tmp/tmpJK1ieR.pyomo.soln it seems to exit normally and also writes the solution as shown below.

Cbc0010I After 35000 nodes, 7824 on tree, -1415.8392 best solution, best possible -1415.84 (57.06 seconds)
Cbc0038I Full problem 205 rows 289 columns, reduced to 30 rows 52 columns
Cbc0010I After 36000 nodes, 8250 on tree, -1415.8392 best solution, best possible -1415.84 (58.73 seconds)
Cbc0020I Exiting on maximum time
Cbc0005I Partial search - best objective -1415.8392 (best possible -1415.84), took 464553 iterations and 36788 nodes (60.11 seconds)
Cbc0032I Strong branching done 15558 times (38451 iterations), fathomed 350 nodes and fixed 2076 variables
Cbc0035I Maximum depth 203, 5019 variables fixed on reduced cost
Cbc0038I Probing was tried 31933 times and created 138506 cuts of which 0 were active after adding rounds of cuts (4.431 seconds)
Cbc0038I Gomory was tried 30898 times and created 99534 cuts of which 0 were active after adding rounds of cuts (4.855 seconds)
Cbc0038I Knapsack was tried 30898 times and created 12926 cuts of which 0 were active after adding rounds of cuts (8.271 seconds)
Cbc0038I Clique was tried 100 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
Cbc0038I MixedIntegerRounding2 was tried 30898 times and created 13413 cuts of which 0 were active after adding rounds of cuts (3.652 seconds)
Cbc0038I FlowCover was tried 100 times and created 4 cuts of which 0 were active after adding rounds of cuts (0.019 seconds)
Cbc0038I TwoMirCuts was tried 30898 times and created 15292 cuts of which 0 were active after adding rounds of cuts (2.415 seconds)
Cbc0038I Stored from first was tried 30898 times and created 15734 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
Cbc0012I Integer solution of -1411.9992 found by Reduced search after 467825 iterations and 36838 nodes (60.12 seconds)
Cbc0020I Exiting on maximum time
Cbc0005I Partial search - best objective -1411.9992 (best possible -1415.4522), took 467825 iterations and 36838 nodes (60.12 seconds)
Cbc0032I Strong branching done 476 times (1776 iterations), fathomed 1 nodes and fixed 18 variables
Cbc0035I Maximum depth 21, 39 variables fixed on reduced cost
Cuts at root node changed objective from -1484.12 to -1415.45
Probing was tried 133 times and created 894 cuts of which 32 were active after adding rounds of cuts (0.060 seconds)
Gomory was tried 133 times and created 1642 cuts of which 0 were active after adding rounds of cuts (0.047 seconds)
Knapsack was tried 133 times and created 224 cuts of which 0 were active after adding rounds of cuts (0.083 seconds)
Clique was tried 100 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.001 seconds)
MixedIntegerRounding2 was tried 133 times and created 163 cuts of which 0 were active after adding rounds of cuts (0.034 seconds)
FlowCover was tried 100 times and created 5 cuts of which 0 were active after adding rounds of cuts (0.026 seconds)
TwoMirCuts was tried 133 times and created 472 cuts of which 0 were active after adding rounds of cuts (0.021 seconds)
ImplicationCuts was tried 25 times and created 41 cuts of which 0 were active after adding rounds of cuts (0.003 seconds)

Result - Stopped on time limit

Objective value:                -1411.99922848
Lower bound:                    -1415.452
Gap:                            0.00
Enumerated nodes:               36838
Total iterations:               467825
Time (CPU seconds):             60.13
Time (Wallclock seconds):       60.98

Total time (CPU seconds):       60.13   (Wallclock seconds):       61.01

The top few lines of the CBC solution file are:

Stopped on time - objective value -1411.99922848
      0 c_e_x1454_                         0                       0
      1 c_e_x1455_                         0                       0
      2 c_e_x1456_                         0                       0
      3 c_e_x1457_                         0                       0
      4 c_e_x1458_                         0                       0
      5 c_e_x1459_                         0                       0
      6 c_e_x1460_                         0                       0
      7 c_e_x1461_                         0                       0
      8 c_e_x1462_                         0                       0

Can anyone tell me how can I get these values without generating any error?

Thanks in advance.


问:
Passing Boolean value as a String to a method expecting a String
In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.

```<code>fileexists = File.file?("#{$fileLocation}")

puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s
</code>```

This will result in:

```<code>true
true
true
</code>```

Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.

```<code>slack(message: "#{fileexists}")
</code>```

Results in the error message.

```<code>'message' value must be a String! Found TrueClass instead.
</code>```

Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.

So let's try something slightly different:

```<code>slack(message: "#{fileexists.to_s}")
</code>```

This results in the same error.

```<code>'message' value must be a String! Found TrueClass instead.
</code>```

Now this is where things GET REALLY WEIRD!!

```<code>slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")
</code>```

If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.

I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.

Does Ruby check types of params as they're passed like this?

Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?

答:
I'm only guessing here because we don't know what the method definition of slack is expecting an un-named String, but you're passing a hash.

```<code>slack(fileexists.to_s)
</code>```

Body:
In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.

fileexists = File.file?("#{$fileLocation}")

puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s

This will result in:

true
true
true

Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.

slack(message: "#{fileexists}")

Results in the error message.

'message' value must be a String! Found TrueClass instead.

Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.

So let's try something slightly different:

slack(message: "#{fileexists.to_s}")

This results in the same error.

'message' value must be a String! Found TrueClass instead.

Now this is where things GET REALLY WEIRD!!

slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")

If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.

I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.

Does Ruby check types of params as they're passed like this?

Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?

Body:
I'm only guessing here because we don't know what the method definition of slack is expecting an un-named String, but you're passing a hash.

slack(fileexists.to_s)


问:
C - Matrix input function gets runtime error if matrix is bigger than 5x5, but there is no size defined at the code
I'm using this function to read the input matrix:

```<code>void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}
</code>```

And I'm creating the matrix like this:

```<code>scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);
</code>```

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

答:
```<code>int **matriz1=(int **)malloc(v1 * sizeof(int));
</code>```

This line is wrong. As already stated by other answers, the elements pointed to by matriz1 are not integers but pointers to integers, so using sizeof with a type name should be sizeof(int *) here.

Also, casting the return value of malloc() is unnecessary and arguably bad style in C.

To avoid errors like that, sizeof can also take an expression as an operand and uses the type this expression would evaluate to, which comes very handy with malloc() -- it should look like this:

```<code>int **matriz1 = malloc(v1 * sizeof *matriz1);
</code>```

If you change the type of matriz1 later, sizeof *matriz1 still gives the correct element size -- it's the size of whatever matriz1 points to.

Body:
I'm using this function to read the input matrix:

void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}

And I'm creating the matrix like this:

scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

Body:
int **matriz1=(int **)malloc(v1 * sizeof(int));

This line is wrong. As already stated by other answers, the elements pointed to by matriz1 are not integers but pointers to integers, so using sizeof with a type name should be sizeof(int *) here.

Also, casting the return value of malloc() is unnecessary and arguably bad style in C.

To avoid errors like that, sizeof can also take an expression as an operand and uses the type this expression would evaluate to, which comes very handy with malloc() -- it should look like this:

int **matriz1 = malloc(v1 * sizeof *matriz1);

If you change the type of matriz1 later, sizeof *matriz1 still gives the correct element size -- it's the size of whatever matriz1 points to.


问:
rails 3 json custom json formatting
I have a collection of @clients with attributes id and email
I want to render this json format

```<code> [
 {"id":" 1","label":"johndoe@yahoo.com","value":"1"},{"id":"  2","label":"paulsmith@gmail.com.com","value":"2"}
]
</code>```

in clients_controller I defined the following method

```<code>def search
    @clients = Client.where(:user_id => current_user.id).select('id','email')
    render :partial => "clients/search"
  end
</code>```

and here is the view _search.json.erb

```<code>[
 <%= raw @client.map{|client| '{"id":"' +" #{client.id}" +'","label":"' + "#{client.email}" +  '","value":"' +"#{client.id}" +'"}' }.join(",") %>
]
</code>```

this is working, but I found it fugly...is there a more elegant way to generate a custom json format in a view?

答:
You just need use the to_json method. In you case it's</p>

```<code>@client.to_json(:only => [:id, :label, :value])
</code>```

Title: rails 3 json custom json formatting

Body:
I have a collection of @clients with attributes id and email
I want to render this json format

 [
 {"id":" 1","label":"johndoe@yahoo.com","value":"1"},{"id":"  2","label":"paulsmith@gmail.com.com","value":"2"}
]

in clients_controller I defined the following method

def search
    @clients = Client.where(:user_id => current_user.id).select('id','email')
    render :partial => "clients/search"
  end

and here is the view _search.json.erb

[
 <%= raw @client.map{|client| '{"id":"' +" #{client.id}" +'","label":"' + "#{client.email}" +  '","value":"' +"#{client.id}" +'"}' }.join(",") %>
]

this is working, but I found it fugly...is there a more elegant way to generate a custom json format in a view?

Body:
You just need use the to_json method. In you case it's

@client.to_json(:only => [:id, :label, :value])


问:
why i can't import com.google.android.gms.location.LocationListener; and LocationRequest, also LocationServices?
I am trying to build an android app using android studio that uses the direct user location, and I am got error on import com.google.android.gms.location.LocationListener; it says it can't resolve symbol 'LocationListener', and also for 'LocationRequest' and 'LocationServices' I tried searching for an answer but I can't figure out what the problem is.</p>

答:
Check out this link for the list of Google Play libraries and you can add the location library.

https://developers.google.com/android/guides/setup

```<code>implementation 'com.google.android.gms:play-services-location:11.6.0'
</code>```

This should resolve.

Body:
Check out this link for the list of Google Play libraries and you can add the location library.

https://developers.google.com/android/guides/setup

implementation 'com.google.android.gms:play-services-location:11.6.0'

This should resolve.


问:
overloaded method value + with alternatives
I am new to scala, I am trying to create a list with my existing list.

my current list

```<code>val votesByLang: scala.collection.immutable.Map[String,Seq[(String, Int)]] = Map(pythom -> List((pythom,10)), scala -> List((scala,1), (scala,10), (scala,1)), java -> List((java,4)))

votesByLang.map{
  case (witch,counts) => (witch,counts.foldLeft(0)((x,y)=>x+y))
}.toSeq
</code>```

This gives the an error :

```<code>      <console>:13: error: overloaded method value + with alternatives:
      (x: Int)Int <and>
      (x: Char)Int <and>
      (x: Short)Int <and>
      (x: Byte)Int
      cannot be applied to ((String, Int))
      votesByLang.map{case (witch,counts)=>(witch,counts.foldLeft(0) ((x,y)=>x+y))}.toSeq
</code>```

but if I use _ for any the same works fine and yeilds result

```<code>votesByLang.map{
  case (witch,counts) => (witch,counts.foldLeft(0)((_+_._2)))
}.toSeq
</code>```

result:
Seq[(String, Int)] = Vector((pythom,10), (scala,12), (java,4))

What is wrong with the first approach

答:
As Marth Suggested the below works.</p>

```<code> votesByLang.map{
 case (witch,counts)=>(witch,counts.foldLeft(0)((x:Int,y)=>x+y._2))}.toSeq
</code>```

Body:
I am new to scala, I am trying to create a list with my existing list.

my current list

val votesByLang: scala.collection.immutable.Map[String,Seq[(String, Int)]] = Map(pythom -> List((pythom,10)), scala -> List((scala,1), (scala,10), (scala,1)), java -> List((java,4)))

votesByLang.map{
  case (witch,counts) => (witch,counts.foldLeft(0)((x,y)=>x+y))
}.toSeq

This gives the an error :

      <console>:13: error: overloaded method value + with alternatives:
      (x: Int)Int <and>
      (x: Char)Int <and>
      (x: Short)Int <and>
      (x: Byte)Int
      cannot be applied to ((String, Int))
      votesByLang.map{case (witch,counts)=>(witch,counts.foldLeft(0) ((x,y)=>x+y))}.toSeq

but if I use _ for any the same works fine and yeilds result

votesByLang.map{
  case (witch,counts) => (witch,counts.foldLeft(0)((_+_._2)))
}.toSeq

result:
Seq[(String, Int)] = Vector((pythom,10), (scala,12), (java,4))

What is wrong with the first approach

Body:
As Marth Suggested the below works.

 votesByLang.map{
 case (witch,counts)=>(witch,counts.foldLeft(0)((x:Int,y)=>x+y._2))}.toSeq


问:
How to contribute failing test cases
I found a bug in an open source project on GitHub, and wrote a failing test for it, but haven't suggested a fix due to insufficient familiarity with the code.

How does one usually contribute such tests? Shall I create a pull request? Note that the continuous integration would fail for my commit as it adds a (currently) failing test..

(For reference here's the actual test)

答: You can try to use the "Issues" functionality of Git. Create an issue as a bug report, instead of creating a pull request.</p>

Title: How to contribute failing test cases


问:
Remove prefix of each line in a file and output to another file using sed
I have a source code file in which comments are prefixed with // (ie. double slashes and an empty space), I want to convert the source code into a document so I tried to cat file.c and pipe it to sed, the thinking is to replace "double slash and a space" if a line starts with it, with empty string, but it looks like the slash has some special meaning in sed, so what's the best way of constructing the sed arguments?

Thanks!

答:
The slash only has meaning if you allow it.</p>

```<code>sed 's#^// +##' < file.c
</code>```

Body:
The slash only has meaning if you allow it.

sed 's#^// +##' < file.c


问:
Cascade dropdown JQuery - Not displaying dropdown after postback
EDITED FOR CLARITY:

I have a JQuery dialog that contains two dropdown lists. It is displayed on a button click event.

I have this code in the page load event. In the code-behind I populate a couple dropdown lists with data that gets filtered. When the .commonClass fires the LoadVessels(), there is a post back.

It works perfect the first time I use it. If I close the dialog and then do the click event that does the LoadVessels(), it will post back. I don't have the dropdowns reloading from the database and I can see those values in debug console.

When I display the dialog, I see values in the ddlOperations dropdown. I can also debug and see values in the other dropdowns when it goes to the ddlOperations click event. It appears to loop through but the items on screen are not being affected.

HTML:

```<code><div id="divOpSubOp" title="Select Operations/Sub-Operations" style="width:500px; display:none;">
       <div class="row" style="margin-bottom:10px;">
            <label class="col-xs-3 control-label">
                  <span id="lblPier">Select Operation:</span></label>
         <div class="col-xs-5">
            <asp:DropDownList ID="ddlOperations" runat="server" ClientIDMode="Static" class="form-control"></asp:DropDownList>
         </div>
       </div>
       <div class="row">
            <label class="col-xs-3 control-label">
             <span id="Span1">Select Sub-Operation:</span>
            </label>
          <div class="col-xs-5">
             <asp:DropDownList ID="ddlSubOperations" runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>
             <asp:DropDownList ID="ddlSubOperations1" style="display:none" runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>
             <asp:DropDownList ID="ddlSubOperations2" style="display:none"  runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>
           </div>
         </div>
         <div class="row">
             <asp:Button ID="btnGenerate" runat="server"
ClientIDMode="Static" Text="Generate" CssClass="btn btn-primary"
OnClientClick="return ValidateGenerate()" />
                </div>
            </div>

<script type="text/javascript">
  function pageLoad() {
        Sys.Application.add_load(function () {
            theForm.__EVENTARGUMENT.value = '';
        });

$(".commanClass").click(function () {
            LoadVessels();
     });

$("#ddlOperations").change(function () {
    $("#hfOperation").val($(this).val());
    $("#ddlSubOperations").empty();
    var SubOpsIdbyVal = [];

    $("#ddlSubOperations2 > option").each(function () {
        if ($(this).val() == $("#ddlOperations").val()) {
            SubOpsIdbyVal.push($(this).text());
        }
    });

    $("#ddlSubOperations").append($("<option value='0'></option>"));
    for (i = 0; i < SubOpsIdbyVal.length; i++) {
        $("#ddlSubOperations1").val(SubOpsIdbyVal[i]);
        $("#ddlSubOperations").append($("<option value='" + SubOpsIdbyVal[i] + "'>" + $("#ddlSubOperations1 option:selected").text() + "</option>"));
    }
});
}

function LoadVessels() {
        if ($('#divShiftGroup input:radio:checked').val() != undefined &&
 $('#divPortGroup input:radio:checked').val() != undefined
          && $("#txtDate").val() != "" &&
 ($("input:radio[name='YardVessel']").is(":checked"))) {
            __doPostBack("<%=upInner.UniqueID %>", 'LoadVoyageDDL');
    }
</script>
</code>```

The initial population of the dropdown lists are done in the code behind in VB.net

```<code>If Not IsPostBack Then
        ddlOperations.DataSource = "CALL TO SQL"
        ddlOperations.DataTextField = "Descr"
        ddlOperations.DataValueField = "OpsId"
        ddlOperations.DataBind()
        ddlOperations.Items.Insert(0, "")

        ddlSubOperations1.DataSource = "CALL TO SQL"
        ddlSubOperations1.DataTextField = "Descr"
        ddlSubOperations1.DataValueField = "SubOpsId"
        ddlSubOperations1.DataBind()

        ddlSubOperations2.DataSource = "CALL TO SQL"
        ddlSubOperations2.DataTextField = "SubOpsId"
        ddlSubOperations2.DataValueField = "OpsId"
        ddlSubOperations2.DataBind()
End If
</code>```

答:
If you want your filtration to persist across pages either your backend needs to generate a filtered list or something on the client side code needs to be executed on page load.

It is initially applied when the change event is fired on your ddlOperations. However, after a postback and your page reloads the code will not be executed until a change event is once again fired on ddl operations change.  Try moving your filtration code into a function and executing it on page load if there is a ddl operation selected, in addition to registering it to the on change event.

Body:
EDITED FOR CLARITY:

I have a JQuery dialog that contains two dropdown lists. It is displayed on a button click event.

I have this code in the page load event. In the code-behind I populate a couple dropdown lists with data that gets filtered. When the .commonClass fires the LoadVessels(), there is a post back.

It works perfect the first time I use it. If I close the dialog and then do the click event that does the LoadVessels(), it will post back. I don't have the dropdowns reloading from the database and I can see those values in debug console.

When I display the dialog, I see values in the ddlOperations dropdown. I can also debug and see values in the other dropdowns when it goes to the ddlOperations click event. It appears to loop through but the items on screen are not being affected.

HTML:

                  Select Operation:

            <asp:DropDownList ID="ddlOperations" runat="server" ClientIDMode="Static" class="form-control"></asp:DropDownList>

             Select Sub-Operation:

             <asp:DropDownList ID="ddlSubOperations" runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>
             <asp:DropDownList ID="ddlSubOperations1" style="display:none" runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>
             <asp:DropDownList ID="ddlSubOperations2" style="display:none"  runat="server" ClientIDMode="Static" class="form-control">
             </asp:DropDownList>

             <asp:Button ID="btnGenerate" runat="server"
ClientIDMode="Static" Text="Generate" CssClass="btn btn-primary"
OnClientClick="return ValidateGenerate()" />

The initial population of the dropdown lists are done in the code behind in VB.net

If Not IsPostBack Then
        ddlOperations.DataSource = "CALL TO SQL"
        ddlOperations.DataTextField = "Descr"
        ddlOperations.DataValueField = "OpsId"
        ddlOperations.DataBind()
        ddlOperations.Items.Insert(0, "")

        ddlSubOperations1.DataSource = "CALL TO SQL"
        ddlSubOperations1.DataTextField = "Descr"
        ddlSubOperations1.DataValueField = "SubOpsId"
        ddlSubOperations1.DataBind()

        ddlSubOperations2.DataSource = "CALL TO SQL"
        ddlSubOperations2.DataTextField = "SubOpsId"
        ddlSubOperations2.DataValueField = "OpsId"
        ddlSubOperations2.DataBind()
End If


问:
how to delete logs in wso2 api manager periodically
I am using a combination of WSO2 API Manager and Identity server.
Now my server machine gets full because of logs. Though logs getting rotated , they are not being deleted.
Is there a way to manage logs in WSO2?  May be automatically delete them after a time period. Or limit the size if logs file</p>

答:
You can configure logging in repository/conf/log4j.properties file.

Add following configurations in the log4j.appender.CARBON_LOGFILE=org.apache.log4j.RollingFileAppendersection.

```<code>log4j.appender.CARBON_LOGFILE.MaxFileSize=20MB
log4j.appender.CARBON_LOGFILE.MaxBackupIndex=1000
</code>```

So this will ensure total 20MB * 1000 will be used. i. e first 1000 entries of 20MB chunks will be retained

Ref: WSO2 ESB log is too big, how to set?

Body:
You can configure logging in repository/conf/log4j.properties file.

Add following configurations in the log4j.appender.CARBON_LOGFILE=org.apache.log4j.RollingFileAppendersection.

log4j.appender.CARBON_LOGFILE.MaxFileSize=20MB
log4j.appender.CARBON_LOGFILE.MaxBackupIndex=1000

So this will ensure total 20MB * 1000 will be used. i. e first 1000 entries of 20MB chunks will be retained

Ref: WSO2 ESB log is too big, how to set?


问:
Vim: reopen all previous files in a new session after restart
I usually have long lived vim session with dozens of files open. Once in a while, I need to restart vim, say to install a new plugin or apply some new config.

How can I reopen all the previous files after restart?

答:
You can use builtin sessions, perhaps with vim-session plugin.

A Vim session contains all the information about what you are editing.

This includes things such as the file list, window layout, global variables,
options and other information.  (Exactly what is remembered is controlled by
the 'sessionoptions' option.)

The command

```<code>:mksession mysession.vim
</code>```

saves the current session into the named file. Next time you start vim you can load the session:

```<code>vim -S mysession.vim
</code>```

or inside vim

```<code>:source mysession.vim
</code>```

You can automate saving sessions on VimLeave autocommand and reload a session on VimEnter but be careful abut restoring a session when vim is called, e.g., from git.

ContentLicense: CC BY-SA 4.0

Body:
You can use builtin sessions, perhaps with vim-session plugin.

A Vim session contains all the information about what you are editing.

This includes things such as the file list, window layout, global variables,
options and other information.  (Exactly what is remembered is controlled by
the 'sessionoptions' option.)

The command

:mksession mysession.vim

saves the current session into the named file. Next time you start vim you can load the session:

vim -S mysession.vim

or inside vim

:source mysession.vim

You can automate saving sessions on VimLeave autocommand and reload a session on VimEnter but be careful abut restoring a session when vim is called, e.g., from git.


问:
How can I restore latest backup programmatically?
How can I restore the latest SQL Server backup to a target server programmatically?

We have mixed environment, Azure and on-prem and we need to backup a SQL database in Azure then restore it to an on-prem SQL Server that we use to run the reports.

In Azure environment we have a production SQL Server and we backup one specific database to Azure blob storage, this is done each day at midnight.

Backup file format is databasename_year-month-day.bak. Our database is named scups therefore our backups are named scups_2017-11-14.bak, scups_2017-11-15.bak etc. Backups are about 35 Gb in size and they complete within a few minutes.

On-Prem environment:

Windows task scheduler on an on-prem SQL Server Reporting Services runs AZcopy (Azure PowerShell) and SQL backup is downloaded from Azure blob storage to its local disk, this process starts at 1:45 AM and database is downloaded within an hour.

At 5:00 AM restore job on our on-prem reporting server is invoked via SQL Server agent and this restores the database, ready to be used by the people that run the reports.

This process works but problem is, currently we have to modify the SQL Server job every evening so that correct date of database backup is restored.

So, I have to modify the SQL Server job to include specific file, for example we have to replace scups_2017-11-15.bak with scups_2017-11-16.bak so that latest database backup from 11/16 is restored.

How can I modify the script so that it restores the latest backup each morning?
And, is there a better way to automate this process?

I would appreciate any suggestions.

This is our SQL Server job:

```<code>USE MASTER
GO

ALTER DATABASE scups
SET multi_user WITH ROLLBACK IMMEDIATE
GO

-- Now put it into single user mode and drop it. Use Rollback Immediate to disconnect any -- sessions and rollback their transactions. Safe since you are about to drop the DB.
ALTER DATABASE scups
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

DROP DATABASE scups
GO
--pause sleep 2 minutes

USE master

RESTORE DATABASE [scups]
FILE = N'scups_Data',
FILE = N'ftrow_fulltext_catalog',
FILE = N'ftrow_CourseForumEntries'
FROM DISK = N'C:\download\ScupsFullBackup\scups_2017-11-14.bak'
WITH FILE = 1,
MOVE N'scups_Data' TO N'U:\data\scups.mdf',
MOVE N'ftrow_fulltext_catalog' TO N'U:\data\scups1.ndf',
MOVE N'ftrow_CourseForumEntries' TO N'U:\data\scups2.ndf',
MOVE N'scups_Log' TO N'L:\logs\scups_log.ldf',
RECOVERY, REPLACE, STATS = 10
</code>```

答:
Assuming that the name of the backup file is the only variable, you should be able to do something like this:

```<code>use maintdb;
go

create procedure dbo.restoreScups(@backupFile varchar(4000))
as
begin
ALTER DATABASE scups
SET multi_user WITH ROLLBACK IMMEDIATE
GO

-- Now put it into single user mode and drop it. Use Rollback Immediate to disconnect any -- sessions and rollback their transactions. Safe since you are about to drop the DB.
ALTER DATABASE scups
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

DROP DATABASE scups
GO
--pause sleep 2 minutes

USE master

RESTORE DATABASE [scups]
FILE = N'scups_Data',
FILE = N'ftrow_fulltext_catalog',
FILE = N'ftrow_CourseForumEntries'
FROM DISK = @backupfile
WITH FILE = 1,
MOVE N'scups_Data' TO N'U:\data\scups.mdf',
MOVE N'ftrow_fulltext_catalog' TO N'U:\data\scups1.ndf',
MOVE N'ftrow_CourseForumEntries' TO N'U:\data\scups2.ndf',
MOVE N'scups_Log' TO N'L:\logs\scups_log.ldf',
RECOVERY, REPLACE, STATS = 10;

end
</code>```

Then you can call this procedure from something like powershell like this:
$query = @'
exec maintdb.dbo.restoreScups @backupFile = 'C:\download\ScupsFullBackup\scups_2017-11-14.bak';
@'

```<code>invoke-sqlcmd -ServerInstance yourServer -Query $query;
</code>```

Body:
How can I restore the latest SQL Server backup to a target server programmatically?

We have mixed environment, Azure and on-prem and we need to backup a SQL database in Azure then restore it to an on-prem SQL Server that we use to run the reports.

In Azure environment we have a production SQL Server and we backup one specific database to Azure blob storage, this is done each day at midnight.

Backup file format is databasename_year-month-day.bak. Our database is named scups therefore our backups are named scups_2017-11-14.bak, scups_2017-11-15.bak etc. Backups are about 35 Gb in size and they complete within a few minutes.

On-Prem environment:

Windows task scheduler on an on-prem SQL Server Reporting Services runs AZcopy (Azure PowerShell) and SQL backup is downloaded from Azure blob storage to its local disk, this process starts at 1:45 AM and database is downloaded within an hour.

At 5:00 AM restore job on our on-prem reporting server is invoked via SQL Server agent and this restores the database, ready to be used by the people that run the reports.

This process works but problem is, currently we have to modify the SQL Server job every evening so that correct date of database backup is restored.

So, I have to modify the SQL Server job to include specific file, for example we have to replace scups_2017-11-15.bak with scups_2017-11-16.bak so that latest database backup from 11/16 is restored.

How can I modify the script so that it restores the latest backup each morning?
And, is there a better way to automate this process?

I would appreciate any suggestions.

This is our SQL Server job:

USE MASTER
GO

ALTER DATABASE scups
SET multi_user WITH ROLLBACK IMMEDIATE
GO

-- Now put it into single user mode and drop it. Use Rollback Immediate to disconnect any -- sessions and rollback their transactions. Safe since you are about to drop the DB.
ALTER DATABASE scups
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

DROP DATABASE scups
GO
--pause sleep 2 minutes

USE master

RESTORE DATABASE [scups]
FILE = N'scups_Data',
FILE = N'ftrow_fulltext_catalog',
FILE = N'ftrow_CourseForumEntries'
FROM DISK = N'C:\download\ScupsFullBackup\scups_2017-11-14.bak'
WITH FILE = 1,
MOVE N'scups_Data' TO N'U:\data\scups.mdf',
MOVE N'ftrow_fulltext_catalog' TO N'U:\data\scups1.ndf',
MOVE N'ftrow_CourseForumEntries' TO N'U:\data\scups2.ndf',
MOVE N'scups_Log' TO N'L:\logs\scups_log.ldf',
RECOVERY, REPLACE, STATS = 10

Body:
Assuming that the name of the backup file is the only variable, you should be able to do something like this:

use maintdb;
go

create procedure dbo.restoreScups(@backupFile varchar(4000))
as
begin
ALTER DATABASE scups
SET multi_user WITH ROLLBACK IMMEDIATE
GO

-- Now put it into single user mode and drop it. Use Rollback Immediate to disconnect any -- sessions and rollback their transactions. Safe since you are about to drop the DB.
ALTER DATABASE scups
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

DROP DATABASE scups
GO
--pause sleep 2 minutes

USE master

RESTORE DATABASE [scups]
FILE = N'scups_Data',
FILE = N'ftrow_fulltext_catalog',
FILE = N'ftrow_CourseForumEntries'
FROM DISK = @backupfile
WITH FILE = 1,
MOVE N'scups_Data' TO N'U:\data\scups.mdf',
MOVE N'ftrow_fulltext_catalog' TO N'U:\data\scups1.ndf',
MOVE N'ftrow_CourseForumEntries' TO N'U:\data\scups2.ndf',
MOVE N'scups_Log' TO N'L:\logs\scups_log.ldf',
RECOVERY, REPLACE, STATS = 10;

end

Then you can call this procedure from something like powershell like this:
$query = @'
exec maintdb.dbo.restoreScups @backupFile = 'C:\download\ScupsFullBackup\scups_2017-11-14.bak';
@'

invoke-sqlcmd -ServerInstance yourServer -Query $query;


问:
Angular 5 No provider for Window
My Angular 5 app is building fine with npm start, but when I navigate to a particular component in Chrome, I'm getting this cryptic error in the console. I can't find a single mention of it in search.

(I'm trying to upgrade this component from Angular 4 to Angular 5.)

```<code>core.js:1350 ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4617)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>
</code>```

答: The error was coming from a component test file. I rebuilt my node_modules, restarted the editor (VS Code), and the error went away. I didn't need to add any provider for window.</p>

Title: Angular 5 No provider for Window

Body:
My Angular 5 app is building fine with npm start, but when I navigate to a particular component in Chrome, I'm getting this cryptic error in the console. I can't find a single mention of it in search.

(I'm trying to upgrade this component from Angular 4 to Angular 5.)

core.js:1350 ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4617)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>


问:
java compare method explanation
```<code>   public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){
                if(o1.getValue() < o2.getValue() ){
                    return -1;
                }
                else if(o1.getValue() > o2.getValue()){
                    return 1;
                }
                else{
                        if(o1.getKey() < o2.getKey()){
                            return -1;
                        }else{
                            return 1;
                        }
                }
}

public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){

                if(o1.getValue() == o2.getValue()){
                    return (o1.getKey() - o2.getKey());
                }
                else{
                    return (o2.getValue() - o1.getValue());
                }

}
</code>```

As per my understanding above two compare method should give same result but they are behaving differently.

Can somebody help to understand why are they different?

答:
The first one doesn't correctly handle the case where both keys and values are equal.

The second one doesn't correctly handle overflow.

Title: java compare method explanation

Body:
   public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){
                if(o1.getValue() < o2.getValue() ){
                    return -1;
                }
                else if(o1.getValue() > o2.getValue()){
                    return 1;
                }
                else{
                        if(o1.getKey() < o2.getKey()){
                            return -1;
                        }else{
                            return 1;
                        }
                }
}

public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){

                if(o1.getValue() == o2.getValue()){
                    return (o1.getKey() - o2.getKey());
                }
                else{
                    return (o2.getValue() - o1.getValue());
                }

}

As per my understanding above two compare method should give same result but they are behaving differently.

Can somebody help to understand why are they different?


问:
How to batch process some frames with different dimension but same name pattern some how by R
In the R environment, I have already have some variable, their name:

```<code>id_01_r
id_02_l
id_05_l
id_06_r
id_07_l
id_09_1
id_11_l
</code>```

So, their pattern seems like id_ and follows two figures, then _ and r or l randomly.

Each of them corresponds to one frame but different dim() output.

Also, there are some other variables in the environment, so first I should extract these frames. For this, I'm going to adopt:

```<code>> a <- list(ls()[grep("id*",ls())])` #a little sample for just id* I know
</code>```

But, this function put them as one element, so I don't think it's    good way

```<code>> length(a)     [1] 1
</code>```

I know how to read them in like below, but now for extact and same processes, I'm so confused.

```<code>i_set <- Sys.glob(paths='mypath/////id*.txt')
for (i in i_set) {
    assign(substring(i, startx, endx),read.table(file=i,header=F))
    }
</code>```

Here, the key point is I want to do a series of same data processing for each of these frames. But based on these, what can I do instead of one by one?
Thanks your kind consideration.

答:
Here is an example:</p>

```<code>id_01_r <- iris
id_02_l <- mtcars
foo <- 42

vars <- grep("^id_\\d{2}_[rl]$", ls(), value = TRUE)
# [1] "id_01_r" "id_02_l"

process_data <- function(df) {
  dim(df)
}

processed_data <- lapply(
  mget(vars),
  process_data
)

# $id_01_r
# [1] 150   5
#
# $id_02_l
# [1] 32 11
</code>```

Body:
In the R environment, I have already have some variable, their name:

id_01_r
id_02_l
id_05_l
id_06_r
id_07_l
id_09_1
id_11_l

So, their pattern seems like id_ and follows two figures, then _ and r or l randomly.

Each of them corresponds to one frame but different dim() output.

Also, there are some other variables in the environment, so first I should extract these frames. For this, I'm going to adopt:

> a <- list(ls()[grep("id*",ls())])` #a little sample for just id* I know

But, this function put them as one element, so I don't think it's    good way

> length(a)     [1] 1

I know how to read them in like below, but now for extact and same processes, I'm so confused.

i_set <- Sys.glob(paths='mypath/////id*.txt')
for (i in i_set) {
    assign(substring(i, startx, endx),read.table(file=i,header=F))
    }

Here, the key point is I want to do a series of same data processing for each of these frames. But based on these, what can I do instead of one by one?
Thanks your kind consideration.

Body:
Here is an example:

id_01_r <- iris
id_02_l <- mtcars
foo <- 42

vars <- grep("^id_\\d{2}_[rl]$", ls(), value = TRUE)
# [1] "id_01_r" "id_02_l"

process_data <- function(df) {
  dim(df)
}

processed_data <- lapply(
  mget(vars),
  process_data
)

# $id_01_r
# [1] 150   5
#
# $id_02_l
# [1] 32 11


问:
Issues with extra MIDI track being created in AKsequencer, using audiokit
I've been trying to solve a mystery sinewave issue with little success. I'm starting a new question here as I think I have dug into the specifics of this problem.

When setting up an AKSequencer, and feeding it a MIDI file, I'm seeing some strange results.

For a 4 track song (with a corresponding 4 track midi file, duration matching all stems of the song), I'm seeing that the sequencer is actually generated with 5 tracks. What is the extra track?

Also, I'm getting an error in the console:

[seq] 1026: Invalid beat range

which I believe happens when the track is empty.

So this looks like the culprit for my mystery sinewave.

Any ideas on how I can fix this? It's been driving me a little crazy...

 Thanks!

答: I believe CL is correct that the extra track is a midi track. Usually a sine wave means that you're not connected to anything else to generate the sounds, so the sequencer lets you know this by using the sine wave (wouldn't have been my first choice, but thats an internal Apple decision).</p>


问:
Code explanation to determine whether a class is derived from another class
The intention is to detect whether the Template type parameter D is derived from Template type parameter B. The below code has private static methods in the class IsDerivedHelper. The question is How does the static method inside the Helper class works? It doesn't have a definition in it.

```<code>#include<iostream>
#include<type_traits>

using namespace std;

class IOne
{
private:
public:
    IOne() = delete;
    virtual void print() = 0;
};

class One :public IOne
{
public:
    One() = default;
    virtual void print()
    {
        cout << "printed from class One" << endl;
    }
};

class Two
{

};

template<typename D, typename B> class IsDerivedHelper
{
    class No{};
    class Yes { No no[3]; };
    static Yes Test(B*);
    static No Test(...);
public:
    enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};

void main()
{
    auto v = IsDerivedHelper<One, IOne>::Is;    // Value is 1
    // auto v = IsDerivedHelper<Two, IOne>::Is; // Value is 0
    if (v)
    {
        cout << "Is derived" << endl;
    }
    else
    {
        cout << "Not a derived." << endl;
    }
}
</code>```

Thanks in advance.

答:
THis works at compile time really , the core is the decision of which IsDerivedHelper::Test overload to use

this call here

```<code>sizeof(Test(static_cast<D*>(0)))
</code>```

Will return the sizeof the return value of which overload is chosen. All at compile time.

The two overloads are

```<code>   static Yes Test(B*);
    static No Test(...);
</code>```

The first one is used if the argument passed is derived from B.
The second one is used in any other case. ... means 'any args'

the static methods are never called, everything is evaluated at compile time.

It is a clever set of tricks

Body:
The intention is to detect whether the Template type parameter D is derived from Template type parameter B. The below code has private static methods in the class IsDerivedHelper. The question is How does the static method inside the Helper class works? It doesn't have a definition in it.

#include<iostream>
#include<type_traits>

using namespace std;

class IOne
{
private:
public:
    IOne() = delete;
    virtual void print() = 0;
};

class One :public IOne
{
public:
    One() = default;
    virtual void print()
    {
        cout << "printed from class One" << endl;
    }
};

class Two
{

};

template<typename D, typename B> class IsDerivedHelper
{
    class No{};
    class Yes { No no[3]; };
    static Yes Test(B*);
    static No Test(...);
public:
    enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};

void main()
{
    auto v = IsDerivedHelper<One, IOne>::Is;    // Value is 1
    // auto v = IsDerivedHelper<Two, IOne>::Is; // Value is 0
    if (v)
    {
        cout << "Is derived" << endl;
    }
    else
    {
        cout << "Not a derived." << endl;
    }
}

Thanks in advance.

Body:
THis works at compile time really , the core is the decision of which IsDerivedHelper::Test overload to use

this call here

sizeof(Test(static_cast<D*>(0)))

Will return the sizeof the return value of which overload is chosen. All at compile time.

The two overloads are

   static Yes Test(B*);
    static No Test(...);

The first one is used if the argument passed is derived from B.
The second one is used in any other case. ... means 'any args'

the static methods are never called, everything is evaluated at compile time.

It is a clever set of tricks


问:
Validate email address format in .NET without exceptions
Currently I'm using this code:

```<code>    public static bool IsEmailAddress(this string value)
    {
        try
        {
            new System.Net.Mail.MailAddress(value);
            return true;
        }
        catch ()
        {
            return false;
        }
    }
</code>```

Is there a way to do this without using exceptions?

答:
You could use a regular expression.

```<code>private const string EmailRegularExpression = @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
private static Regex EmailValidRegex = new Regex(CommonValues.EmailRegularExpression, RegexOptions.Compiled | RegexOptions.IgnoreCase)

public static bool IsEmailValid(string emailAddress)
{
    return !string.IsNullOrWhiteSpace(emailAddress) && EmailValidRegex.IsMatch(emailAddress);
}
</code>```

See also http://www.regular-expressions.info/email.html which is where I snagged the expression from.

Body:
Currently I'm using this code:

    public static bool IsEmailAddress(this string value)
    {
        try
        {
            new System.Net.Mail.MailAddress(value);
            return true;
        }
        catch ()
        {
            return false;
        }
    }

Is there a way to do this without using exceptions?

Body:
You could use a regular expression.

private const string EmailRegularExpression = @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
private static Regex EmailValidRegex = new Regex(CommonValues.EmailRegularExpression, RegexOptions.Compiled | RegexOptions.IgnoreCase)

public static bool IsEmailValid(string emailAddress)
{
    return !string.IsNullOrWhiteSpace(emailAddress) && EmailValidRegex.IsMatch(emailAddress);
}

See also http://www.regular-expressions.info/email.html which is where I snagged the expression from.


问:
Set locale to cartopy ticker
I was wondering and searching on the docs: is there a way to set the locale, for example, to use commas instead of points as separators for decimals in cartopy ticklabels?

In matplotlib it can be done, but it doesn't apply to cartopy.mpl.ticker's LongitudeFormatter and LatitudeFormatter.

Maybe it's something for the developers to add in newer versions?

答:
Nothing too special about the LongitudeFormatter and LatitudeFormatter, they are just specialised Formatters.

So, the gridlines object has properties 'xformatter' and 'yformatter', which have a 'set_useLocale' method.

This worked for me...

```<code>>>> ax = plt.gca()
>>> gl = ax.gridlines(draw_labels=True,
...                   xlocs=[-120.5, -50.8, 30.7, 134.2, 157.8])
>>> gl.xformatter.set_useLocale(True)
>>> plt.show()
</code>```

BUT you do have to have the machine locale set to start with.
In order to get "," numeric seperators, I started with :

```<code>$ export LC_NUMERIC="it_IT.UTF-8"
$ python
</code>```

I don't know much about it, but I think you can't change this dynamically through the Python interface, it needs to be in the calling environment

 -- see Setting Python locale doesn't work

Title: Set locale to cartopy ticker

Body:
Nothing too special about the LongitudeFormatter and LatitudeFormatter, they are just specialised Formatters.

So, the gridlines object has properties 'xformatter' and 'yformatter', which have a 'set_useLocale' method.

This worked for me...

>>> ax = plt.gca()
>>> gl = ax.gridlines(draw_labels=True,
...                   xlocs=[-120.5, -50.8, 30.7, 134.2, 157.8])
>>> gl.xformatter.set_useLocale(True)
>>> plt.show()

BUT you do have to have the machine locale set to start with.
In order to get "," numeric seperators, I started with :

$ export LC_NUMERIC="it_IT.UTF-8"
$ python

I don't know much about it, but I think you can't change this dynamically through the Python interface, it needs to be in the calling environment

 -- see Setting Python locale doesn't work


问:
How do I authenticate HTTP requests in WordPress 4.7?
The new WordPress v4.7 integrates WordPress REST API plugin into the core of WP. This makes posts, pages, and media publicly available using HTTP calls even on private sites.

Is there a setting in WP to block or authenticate GET and POST (etc.) requests?

I'm building an Angular 1.5 REST app with WP and it would be great to authenticate these public requests.

答:
The latest WordPress API now includes authentication for all requests. Adding the filter is_user_logged_in to the rest_authentication_errors filer should require authentication:

add_filter('rest_authentication_errors', function($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error('rest_not_logged_in', 'You are not currently logged in.', array('status' => 401));
    }
    return $result;
});
```

Body:
The latest WordPress API now includes authentication for all requests. Adding the filter is_user_logged_in to the rest_authentication_errors filer should require authentication:

add_filter(&#039;rest_authentication_errors&#039;, function($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error(&#039;rest_not_logged_in&#039;, &#039;You are not currently logged in.&#039;, array(&#039;status&#039; => 401));
    }
    return $result;
});


问:
How to migrate EF + SQL Server to EF + WebServices + SQL Server to create a secure solution?
We currently have a WinForms application that accesses our SQL Server database through Entity Framework. The solution was built with database-first methods. Our database is hosted in Microsoft's Azure SQL services.

We need to secure the application connection to the database but the application will reside on employee laptops that need to work from anywhere. Currently the firewall is open to any IP because obviously the IP address for employees change depending on where they are located.

We need to introduce a web services layer but I don't want to run an entire website just to provide a web service to authenticate against. Creating an entire MVVC between the database and a web service, configuring packages, authentication, etc. just seems a bit much just to wrap the EF / DB communication with AD authentication.

How can we add a web service layer that is seamless for Entity Framework that will allow for Azure AD authentication? Is there an Azure service that works with EF to provide SQL Server access with better authentication? What options are out there that we don't know about?

Update: Adding a little to narrow down the question...
Is there a solution or Azure service that can provide a secure web service layer between EF (easily) and our SQL database? For example, does EF work with Azure Web Apps or Azure Mobile Apps without needing separate models for the web services layer?

Thanks in advance for any help.

答:
You can use token-based authentication as explained here and here.

A file-based authentication is also available as explained here.


问:
Extract columns from text based table output
qfarm /load command shows me the load from my servers.
Output:

```<code>PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
</code>```

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

```<code>PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.
</code>```

Is there any other possibility, like a table or something?

答:
One way to do this is to build objects out of the command's output. Tested the following:

```<code>#requires -version 3

# sample data output from command
$sampleData = @"
Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
"@ -split "`n"

$sampleData | Select-Object -Skip 2 | ForEach-Object {
  $len = $_.Length
  [PSCustomObject] @{
    "ServerName"         = $_.Substring(0,  22).Trim()
    "ServerLoad"         = $_.Substring(22, 13).Trim() -as [Int]
    "LoadThrottlingLoad" = $_.Substring(35, 22).Trim()
    "LogonMode"          = $_.Substring(57, $len - 57).Trim()
  }
}
</code>```

In your case, you should be able to replace $sampleData with your qfarm load command; e.g.:

```<code>qfarm /load | Select-Object -Skip 2 | ForEach-Object {
...
</code>```

Of course, this is assuming no blank lines in the output and that my column positions for the start of each item is correct.

PowerShell version 2 equivalent:

```<code>#requires -version 2

function Out-Object {
  param(
    [Collections.Hashtable[]] $hashData
  )
  $order = @()
  $result = @{}
  $hashData | ForEach-Object {
    $order += ($_.Keys -as [Array])[0]
    $result += $_
  }
  New-Object PSObject -Property $result | Select-Object $order
}

# sample data output from command
$sampleData = @"
Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
"@ -split "`n"

$sampleData | Select-Object -Skip 2 | ForEach-Object {
  $len = $_.Length
  Out-Object `
    @{"ServerName"         = $_.Substring(0,  22).Trim()},
    @{"ServerLoad"         = $_.Substring(22, 13).Trim() -as [Int]},
    @{"LoadThrottlingLoad" = $_.Substring(35, 22).Trim()},
    @{"LogonMode"          = $_.Substring(57, $len - 57).Trim()}
}
</code>```

Body:
qfarm /load command shows me the load from my servers.
Output:

PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.

Is there any other possibility, like a table or something?

Body:
One way to do this is to build objects out of the command's output. Tested the following:

#requires -version 3

# sample data output from command
$sampleData = @"
Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
"@ -split "`n"

$sampleData | Select-Object -Skip 2 | ForEach-Object {
  $len = $_.Length
  [PSCustomObject] @{
    "ServerName"         = $_.Substring(0,  22).Trim()
    "ServerLoad"         = $_.Substring(22, 13).Trim() -as [Int]
    "LoadThrottlingLoad" = $_.Substring(35, 22).Trim()
    "LogonMode"          = $_.Substring(57, $len - 57).Trim()
  }
}

In your case, you should be able to replace $sampleData with your qfarm load command; e.g.:

qfarm /load | Select-Object -Skip 2 | ForEach-Object {
...

Of course, this is assuming no blank lines in the output and that my column positions for the start of each item is correct.

PowerShell version 2 equivalent:

#requires -version 2

function Out-Object {
  param(
    [Collections.Hashtable[]] $hashData
  )
  $order = @()
  $result = @{}
  $hashData | ForEach-Object {
    $order += ($_.Keys -as [Array])[0]
    $result += $_
  }
  New-Object PSObject -Property $result | Select-Object $order
}

# sample data output from command
$sampleData = @"
Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
"@ -split "`n"

$sampleData | Select-Object -Skip 2 | ForEach-Object {
  $len = $_.Length
  Out-Object `
    @{"ServerName"         = $_.Substring(0,  22).Trim()},
    @{"ServerLoad"         = $_.Substring(22, 13).Trim() -as [Int]},
    @{"LoadThrottlingLoad" = $_.Substring(35, 22).Trim()},
    @{"LogonMode"          = $_.Substring(57, $len - 57).Trim()}
}


答:
One method is a numbers table.  If you don't have too many rows, I also like a recursive CTE:

```<code>with cte as (
      select col1, col2, col3, mind, maxd
      from (select col1, col2, min(dte) as mind, max(dte) as maxd
            from t
            group by col1, col2, col3
           ) t
      union all
      select col1, col2, col3, dateadd(day, 1, mind), maxd
      from cte
      where  dateadd(day, 1, mind) < maxd
     )
select col1, col2, col3, mind
from cte;
</code>```

This is limited to 100 rows for each col1/col2 combination, unless you set the max recursion option.

Title: How can I duplicate the result set like below

Body:
I have a table like below and I want to duplicate the records while the min date being less or equal the max date

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-26

I'd like to have the result set like below

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-24
686151209   E13232677   1333439 2017-10-25
86151209    E13232677   1333439 2017-10-26

Body:
One method is a numbers table.  If you don't have too many rows, I also like a recursive CTE:

with cte as (
      select col1, col2, col3, mind, maxd
      from (select col1, col2, min(dte) as mind, max(dte) as maxd
            from t
            group by col1, col2, col3
           ) t
      union all
      select col1, col2, col3, dateadd(day, 1, mind), maxd
      from cte
      where  dateadd(day, 1, mind) < maxd
     )
select col1, col2, col3, mind
from cte;

This is limited to 100 rows for each col1/col2 combination, unless you set the max recursion option.


问:
XXS on same domain not working
I am trying to search through an iFrame from a separate website.

One is my.website.com

Other is website.com

website.com is searching for text located in the iframe from my.website.com but its getting blocked by jquery. Is this blocked because its a different website? They are both the same domain.

I was looking at CORS headers to see if there was a way to allow jquery to search the text... Its dumb that its blocking even searching, its not manipulating anything.

Found this solution here: Cross sub domain iframes and JavaScript

How do I do this though. Where do I add the default.domain?

答:
You can access every variable of the parent window website.com in your case throught the window.parent object.
Maybe you can try setting some variables of website.com with the following function inside my.website.com

```<code>document.onload = function () {
    if (window !== window.top && window.parent !== window) {
        // we're probably inside an iframe
        window.parent.someVariable = 'Some value!';
    }
};
</code>```

And then you can call someVariable inside website.com

A reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference
  to itself.

When a window is loaded in an , , or , its
  parent is the window with the element embedding the window.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/parent

Title: XXS on same domain not working

Body:
You can access every variable of the parent window website.com in your case throught the window.parent object.
Maybe you can try setting some variables of website.com with the following function inside my.website.com

document.onload = function () {
    if (window !== window.top && window.parent !== window) {
        // we're probably inside an iframe
        window.parent.someVariable = 'Some value!';
    }
};

And then you can call someVariable inside website.com

A reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference
  to itself.

When a window is loaded in an , , or , its
  parent is the window with the element embedding the window.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/parent


问:
How to read values from property file in a JavaBean (domain class)?
I have a domain class and I want to read values from property file (autowiring messageSource wouldn't work here) so any ideas ?
I am using spring,hibernate
and here's a sample:</p>

```<code>package com.myapp.domain;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name = "domain")
public class MyDomain implements Serializable {

    private long entityId;
    private String domain="some_hardcoded_value" // need to read it from a property file;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    public long getEntityId() {
        return entityId;
    }

    public void setEntityId(long entityId) {
        this.entityId = entityId;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Column(name = "domain")
    public String getDomain() {
        return domain;
    }

}
</code>```

答:
Adding to Ansari's code

```<code>Properties p = new Properties();
p.load (Thread.currentThread().getContextClassLoader().
         getResourceAsStream("some.properties"));

p.list(System.out);  // or p.get("name")   --> name=value.
</code>```

After searching in internet i found below

```<code><!--Bean to load properties file -->

<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties">
<!--reads config.properties file-->
</code>```

Please read this article http://www.zparacha.com/how-to-read-properties-file-in-spring/

Body:
I have a domain class and I want to read values from property file (autowiring messageSource wouldn't work here) so any ideas ?
I am using spring,hibernate
and here's a sample:

package com.myapp.domain;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name = "domain")
public class MyDomain implements Serializable {

    private long entityId;
    private String domain="some_hardcoded_value" // need to read it from a property file;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    public long getEntityId() {
        return entityId;
    }

    public void setEntityId(long entityId) {
        this.entityId = entityId;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Column(name = "domain")
    public String getDomain() {
        return domain;
    }

}

Body:
Adding to Ansari's code

Properties p = new Properties();
p.load (Thread.currentThread().getContextClassLoader().
         getResourceAsStream("some.properties"));

p.list(System.out);  // or p.get("name")   --> name=value.

After searching in internet i found below

<!--Bean to load properties file -->

<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties">
<!--reads config.properties file-->

Please read this article http://www.zparacha.com/how-to-read-properties-file-in-spring/


问:
NSCompoundPredicate not working as I want
I'm building an expense manager and I have a search function with filters. For each filter selected, I append the respective predicate to an array of predicates for the fetchedResultsController. In my filters I have the options "Budget" and "Expense". The following code shows how I append the predicates.

```<code>    if filterCell[0][0] {
        predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
    }
    if filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
    }
</code>```

Going back to the main tableview,I got this line of code:

```<code>fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicatesArray)
</code>```

This is working just fine when only one budget or expense is picked, when they are both chosen, the tableview is empty (It's obvious, type can't be both "budget" and "expense") so I switched to orPredicateWithSubpredicates. Now if I pick "budget" in my filter and press OK, I still get the expenses entries and vice-versa because this viewcontroller contains  a default predicate (User gets to this view when he picks a period of dates, like 13.11 - 16.11 for example) and using the orPredicateWithSubpredicates does nothing since my date predicate will always be true, the only option being the andPredicateWithSubpredicates

What should I modify in my code so it can work properly?

答:
I solved it. The problem was when setting the predicates not applying them.The correct way is the andPredicateWithSubpredicates and the way I applied the predicate is with this code:

```<code>    if filterCell[0][0] && filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "(type == %@) OR (type == %@)", "budget" as NSString, "expense" as NSString))
    } else if filterCell[0][0] {
        predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
    } else if filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
    }
</code>```

Body:
I'm building an expense manager and I have a search function with filters. For each filter selected, I append the respective predicate to an array of predicates for the fetchedResultsController. In my filters I have the options "Budget" and "Expense". The following code shows how I append the predicates.

    if filterCell[0][0] {
        predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
    }
    if filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
    }

Going back to the main tableview,I got this line of code:

fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicatesArray)

This is working just fine when only one budget or expense is picked, when they are both chosen, the tableview is empty (It's obvious, type can't be both "budget" and "expense") so I switched to orPredicateWithSubpredicates. Now if I pick "budget" in my filter and press OK, I still get the expenses entries and vice-versa because this viewcontroller contains  a default predicate (User gets to this view when he picks a period of dates, like 13.11 - 16.11 for example) and using the orPredicateWithSubpredicates does nothing since my date predicate will always be true, the only option being the andPredicateWithSubpredicates

What should I modify in my code so it can work properly?

Body:
I solved it. The problem was when setting the predicates not applying them.The correct way is the andPredicateWithSubpredicates and the way I applied the predicate is with this code:

    if filterCell[0][0] && filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "(type == %@) OR (type == %@)", "budget" as NSString, "expense" as NSString))
    } else if filterCell[0][0] {
        predicatesArray.append(NSPredicate(format: "type == %@", "budget" as NSString))
    } else if filterCell[0][1] {
        predicatesArray.append(NSPredicate(format: "type == %@", "expense" as NSString))
    }