问:
Original array still changes after editing a sliced copy
I'm trying to save a copy of the original coordinates of the vertices of a Geometry object. I tried to copy the object the way I found lots of answers for here on stackoverflow.

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.slice(0);

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);
```

<p>However, if I do this, both objects always change at the same time. The console output reads:</p>

<pre class="lang-html prettyprint-override"><code>Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
</code>```

Am I missing something here? Thanks!

答:
You can should use:

```<code>originalPositions = JSON.parse(JSON.stringify( cityGeometry.vertices ));
</code>```

as array.slice() does only a shallow copy.

Body:
I'm trying to save a copy of the original coordinates of the vertices of a Geometry object. I tried to copy the object the way I found lots of answers for here on stackoverflow.

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.slice(0);

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

However, if I do this, both objects always change at the same time. The console output reads:

Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}

Am I missing something here? Thanks!

Body:
You can should use:

originalPositions = JSON.parse(JSON.stringify( cityGeometry.vertices ));

as array.slice() does only a shallow copy.


来源: stackexchange

问:
Running javascript tests from .net unit tests
I have working CI/CD pipeline using MSBuild with "run unit tests" step and separated build server for this.
Its pretty hard to instal other tools like karma or npm for running javascript tests separately, so I want to run all javascript tests from .net unit test.

So, basically I want to create something like

```<code>[Fact]
public void Test()
{
    var file = LoadJSFile();

    // how can I impleemnt this method?
    RunJSTests(file);
}
</code>```

So, I have two questions:

1. Are there any existing tools for this (like nuget package)?

2. Maybe, I'm going in totally wrong direction and I should spend my efforts to creating separate CI step "Run Javascript Tests"?

答:
My gut feel is that in the long run a separate CI step for the JavaScript tests would be better, but there's some ideas you could investigate / follow from this post How to run QUnit test and get back test result in C# via JavaScript callback?.

The reason I suggest a separate CI step is to decouple the JS from the C#, so that if in the future you switched from pure JS to, say, Angular or typescript, the migration of tests would be simpler. Similarly any migration of C# to F# or, more likely, MSBuild to Jenkins or other CI server could be done more flexibly.

If there's little bingle info for option 1 then that suggests option 1 is somewhat niche, but I don't want to pre-judge that, but if so go with option 2 for now - you can always implement option 1 in the future if necessary and feasible.

ContentLicense: CC BY-SA 3.0

Body:
I have working CI/CD pipeline using MSBuild with "run unit tests" step and separated build server for this.
Its pretty hard to instal other tools like karma or npm for running javascript tests separately, so I want to run all javascript tests from .net unit test.

So, basically I want to create something like

[Fact]
public void Test()
{
    var file = LoadJSFile();

    // how can I impleemnt this method?
    RunJSTests(file);
}

So, I have two questions:

1. Are there any existing tools for this (like nuget package)?

2. Maybe, I'm going in totally wrong direction and I should spend my efforts to creating separate CI step "Run Javascript Tests"?


问:
Should I test all enum values in a contract?
I have a doubt about about whether I should consider a certain type of test functional or contract.

Let's say I have an API like /getToolType, that accepts a {object" "myObject"} as input, and returns at type in the form {type: "[a-z]+"}

It was agreed between client and server that the types returned will match a set of strings, let's say [hammer|knife|screwdriver], so the consumer decided to parse them in an enum, with a fallback value when the returned type is unknown.

Should the consumer include a test case for each type(hammer, knife, screwdriver) to ensure the producer is still following the agreement that it will always return , for instance , the lowercase string "hammer" when /getToolType is called with an hammer object?
Or would you consider such a test case as functional? And why?

答:
IMO the short answer is 'no'.

Contract testing is more interested in structure, if we start boundary testing the API we move into functional test territory, which is best done in the provider code base. You can use a matcher to ensure only one of those three values is returned, this should ensure the Provider build can't return other values.

I would echo @J_A_X's comments - there is no right or wrong answer, just be wary of testing all permutations of input/output data.

ContentLicense: CC BY-SA 4.0


问:
Firebase iOS / Swift and Deep Links
We have just integrated firebase, and all of a sudden our deep links are no longer working.  We're using AppAuth for authentication, so we're reliant on deep links to direct us to the right place.  I'm getting the following error:

```<code><Debug> [Firebase/Analytics][I-ACS023001] Deep Link does not contain valid required params. URL params: {...}
</code>```

Initialization of firebase as follows:

```<code>let bundleId = Bundle.main.bundleIdentifier
let filePath = Bundle.main.path(forResource: "GoogleService-Info-" + bundleId!, ofType: "plist")!
let options = FIROptions(contentsOfFile: filePath)
FIRApp.configure(with: options!)
</code>```

And here's the deep linking functions:

```<code>    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        return application(app, open: url, sourceApplication: nil, annotation: [:])
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        if url.host == AppHost.deeplink {
        ...
   }
</code>```

If i remove the call to FIRApp.configure, everything in the app works fine.  My AppAuth redirects flow into the function above without any issue.  However, with the call to configure(), it never gets into either one of the functions.  As a result, i can't do a token exchange and complete authentication.

I suspected the AppDelegate proxy might be the issue, so i tried disabling it in the plist file.  I've validated that the plist file passed to FIRApp.configure has the appropriate keys:

```<code><key>FirebaseAppDelegateProxyEnabled</key>
<false/>
</code>```

But no matter what i do, it's still activating the proxy:

```<code>[Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
</code>```

I'm using only FirebaseCrash and FirebaseCore (and FirebaseAnalytics indirectly through crash)

答:
Instead of adding the FirebaseAppDelegateProxyEnabled key to the GoogleServices-Info.plist, add it to your App's info.plist. The Google Services plist should not be modified once it's generated.

As for disabling the proxy, it's fine to do this long term. The proxy is a convenience thing (it's just swizzling some methods), and you can reimplement it manually. There's some examples here of how to handle the lack of the proxy (non-swizzling case).

Title: Firebase iOS / Swift and Deep Links

Body:
We have just integrated firebase, and all of a sudden our deep links are no longer working.  We're using AppAuth for authentication, so we're reliant on deep links to direct us to the right place.  I'm getting the following error:

<Debug> [Firebase/Analytics][I-ACS023001] Deep Link does not contain valid required params. URL params: {...}

Initialization of firebase as follows:

let bundleId = Bundle.main.bundleIdentifier
let filePath = Bundle.main.path(forResource: "GoogleService-Info-" + bundleId!, ofType: "plist")!
let options = FIROptions(contentsOfFile: filePath)
FIRApp.configure(with: options!)

And here's the deep linking functions:

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        return application(app, open: url, sourceApplication: nil, annotation: [:])
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        if url.host == AppHost.deeplink {
        ...
   }

If i remove the call to FIRApp.configure, everything in the app works fine.  My AppAuth redirects flow into the function above without any issue.  However, with the call to configure(), it never gets into either one of the functions.  As a result, i can't do a token exchange and complete authentication.

I suspected the AppDelegate proxy might be the issue, so i tried disabling it in the plist file.  I've validated that the plist file passed to FIRApp.configure has the appropriate keys:

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

But no matter what i do, it's still activating the proxy:

[Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist

I'm using only FirebaseCrash and FirebaseCore (and FirebaseAnalytics indirectly through crash)


问:
how to efficiently build up complex case class in my app flow?
I have a controller method that extract the request from the client to ModelOne, and I need to change this model one and build it up to a bigger model lets call it ModelTwo so I can sent it to another service.

This is ModelOne case class:

```<code>case class ModelOne(list: List[String], expectedListSize: Int)
</code>```

And this is ModelTwo case class:

```<code>case class ModelTwo(modelThree: Option[ModelThree])

case class ModelThree(status: Status(its enum),
                                        list: List[String],
                                        amount: Option[Int],
                                        message: Option[String])
</code>```

So what I'm doing to build it up currently is whenever I get the request from the client in the controller I call a service that have a method to build it up since I need to take the list property from ModelOne and build ModelTwo, it looks like this:

```<code>def buildModelTwoResponse(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
}
</code>```

so in the controller I go:

```<code>val modelOne = request.body.extractOpt[ModelOne]

val modelTwo = myService.buildModelTwoResponse(modelOne)
</code>```

Is there a more elegant way to do this?

答:
How about something like:</p>

```<code>case class ModelOne(list: List[String], expectedListSize: Int) {
object ModelOne {
    buildResponse(modelOne: ModelOne): ModelTwo {
       ModelTwo.fromModelOne(modelOne)
    }
}

case class ModelTwo(modelThree: Option[ModelThree])
object ModelTwo {
     def fromModelOne(modelOne: ModelOne): ModelTwo = {
         fromModelThree(ModelThree.fromModelOne(modelOne))
     }

     def fromModelThree(modelThree: ModelThree): ModelTwo = {
         ModelTwo(Some(modelThree))
     }
 }

case class ModelThree(status: Status(its enum),
                                    list: List[String],
                                    amount: Option[Int],
                                    message: Option[String])
object ModelThree {
   def fromModelOne(status: Status, modelOne: ModelOne): ModelThree = {
       ModelThree(status, modelOne.list, None, None)
   }
}
</code>```

Body:
I have a controller method that extract the request from the client to ModelOne, and I need to change this model one and build it up to a bigger model lets call it ModelTwo so I can sent it to another service.

This is ModelOne case class:

case class ModelOne(list: List[String], expectedListSize: Int)

And this is ModelTwo case class:

case class ModelTwo(modelThree: Option[ModelThree])

case class ModelThree(status: Status(its enum),
                                        list: List[String],
                                        amount: Option[Int],
                                        message: Option[String])

So what I'm doing to build it up currently is whenever I get the request from the client in the controller I call a service that have a method to build it up since I need to take the list property from ModelOne and build ModelTwo, it looks like this:

def buildModelTwoResponse(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
}

so in the controller I go:

val modelOne = request.body.extractOpt[ModelOne]

val modelTwo = myService.buildModelTwoResponse(modelOne)

Is there a more elegant way to do this?

Body:
How about something like:

case class ModelOne(list: List[String], expectedListSize: Int) {
object ModelOne {
    buildResponse(modelOne: ModelOne): ModelTwo {
       ModelTwo.fromModelOne(modelOne)
    }
}

case class ModelTwo(modelThree: Option[ModelThree])
object ModelTwo {
     def fromModelOne(modelOne: ModelOne): ModelTwo = {
         fromModelThree(ModelThree.fromModelOne(modelOne))
     }

     def fromModelThree(modelThree: ModelThree): ModelTwo = {
         ModelTwo(Some(modelThree))
     }
 }

case class ModelThree(status: Status(its enum),
                                    list: List[String],
                                    amount: Option[Int],
                                    message: Option[String])
object ModelThree {
   def fromModelOne(status: Status, modelOne: ModelOne): ModelThree = {
       ModelThree(status, modelOne.list, None, None)
   }
}


问:
Notice: Undefined index: video
This code of mine is to upload videos and same it in the database .I am getting only 1 notice that is "Undefined index: video "

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 5

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 13

Notice: Undefined index: text in C:\wamp\www\SSP Final project\php\upload.php on line 14

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 20

hear is the  form

```<code><form method="POST" action="../../php/upload.php" enctype='multipart/form-data'>
                <table class="booking_table"  cellpadding="40" style="margin:auto;margin-top:10px;">
                    <tr>
                        <td>
                            <input type="hidden" name="size" value="90000000000">
                            <input type="file" name="video">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <textarea name="text" cols="40" rows="4" placeholder="Say something about Yout band......"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="submit" name="upload" value="Upload ">
                        </td>
                    </tr>
                </table>
            </form>
</code>```

and hear is the php

```<code>var_dump($_FILES);

//the parth to store the upload video
$target= "../videos/".basename($_FILES['video']['name']);

//conect to database
$db = mysqli_connect('localhost', 'root', '', 'sspfinal');

//get all the submited data from the form
$image = $_FILES['video']['name'];
$txt = $_POST['text'];

$sql="INSERT INTO band(video,text) values ('$image','$txt')";
mysqli_query($db,$sql);//store the submited data into the database table : bands

//move the upload image to the folder
if(move_uploaded_file($_FILES['video']['name'].$target)){
    $msg="Image Uploaded Successfully";
}
else{
    $msg="There was a problem to upload";
}
</code>```

help me to find this fault

答: You forgot to use enctype='multipart/form-data' in the form tag to send the file.

Title: Notice: Undefined index: video

Body:
This code of mine is to upload videos and same it in the database .I am getting only 1 notice that is "Undefined index: video "

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 5

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 13

Notice: Undefined index: text in C:\wamp\www\SSP Final project\php\upload.php on line 14

Notice: Undefined index: video in C:\wamp\www\SSP Final project\php\upload.php on line 20

hear is the  form

<form method="POST" action="../../php/upload.php" enctype='multipart/form-data'>

                            <input type="hidden" name="size" value="90000000000">
                            <input type="file" name="video">

                            <textarea name="text" cols="40" rows="4" placeholder="Say something about Yout band......"></textarea>

                            <input type="submit" name="upload" value="Upload ">

            </form>

and hear is the php

var_dump($_FILES);

//the parth to store the upload video
$target= "../videos/".basename($_FILES['video']['name']);

//conect to database
$db = mysqli_connect('localhost', 'root', '', 'sspfinal');

//get all the submited data from the form
$image = $_FILES['video']['name'];
$txt = $_POST['text'];

$sql="INSERT INTO band(video,text) values ('$image','$txt')";
mysqli_query($db,$sql);//store the submited data into the database table : bands

//move the upload image to the folder
if(move_uploaded_file($_FILES['video']['name'].$target)){
    $msg="Image Uploaded Successfully";
}
else{
    $msg="There was a problem to upload";
}

help me to find this fault


答:
The cityGeometry.vertices is an object array, every item in this array is a quote to an object. So, if use slice to copy the array, every item in the new array also a quote to an object.

```<code>var arr1 = [obj1, obj2, obj3];
var arr2 = arr1.slice();

//arr2[0] == arr1[0] === obj1;
</code>```

They both point to the same object, so if modify arr1[0].xxx, obj1.xxx will change. the solution is use deep copy , or Object.assign when object is not deep.

```<code>var arr1 = [{x:1}, {y:2}, {z:3}];
var arr2 = [];
arr1.forEach(function(item) {
    arr2.push(Object.assign({},item))
});
arr2[0].x = 3;
console.log(arr1[0].x, arr2[0].x);
</code>```

Title: Original array still changes after editing a sliced copy

Body:
The cityGeometry.vertices is an object array, every item in this array is a quote to an object. So, if use slice to copy the array, every item in the new array also a quote to an object.

var arr1 = [obj1, obj2, obj3];
var arr2 = arr1.slice();

//arr2[0] == arr1[0] === obj1;

They both point to the same object, so if modify arr1[0].xxx, obj1.xxx will change. the solution is use deep copy , or Object.assign when object is not deep.

var arr1 = [{x:1}, {y:2}, {z:3}];
var arr2 = [];
arr1.forEach(function(item) {
    arr2.push(Object.assign({},item))
});
arr2[0].x = 3;
console.log(arr1[0].x, arr2[0].x);


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答:
What you are looking for is nohup.

See the wiki link for how to use it.

OwnerDisplayName: Eduardo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eduardo


问:
Single precision big endian float values to Python's float (double precision, big endian)
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

```<code>from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float
</code>```

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

```<code>float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}
</code>```

For your reference, this is the C code running on the Arduino implementing the hex encoding.

```<code>void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}
</code>```

Body:
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}

For your reference, this is the C code running on the Arduino implementing the hex encoding.

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}

Body:
>>> struct.unpack('<f', '\x81\x92\x32\x3e')
(0.17438699305057526,)


问:
Unable to prove this language is not context-free using Pumping Lemma
I'm trying to prove that the language { w ϵ {a, b, c}* | n_a(w) < n_b(w) and n_a(w) < n_c(w) } is not a CFL using Pumping Lemma. The symbol "n_a" represents "number of 'a'".

For pumping lemma, z = u(v^i)x(w^i)y, |vxw| <= m, |vw| >= 1.

I've chosen to use the string z = (a^m)b^(m+1)c^(m+1) to show this isn't a CFL.

However, I get stuck on the following case.

Assume 'uvx' represents the (a^m) portion of 'z', 'w' represents the beginning of the (b^m) portion of 'z' and 'y' represents the rest of 'z'.

Now pumping for i = 2, we get z' = u(v^2)x(w^2)y = a^(m + |v|)b^(m + 1 + |w|)c^(m + 1).

Whenever |v| ≠ 0, we see that this isn't in the language, since n_a(z') is not less than n_c(z'). However, for the case where |v| = 0, we get z' = a^(m)b^(m + 1 + |w|)c^(m + 1), which IS in the language. Therefore, pumping with i = 2 would not work. Is this correct?

I tried with other values of 'i', but I'm still not able to prove this language is not a CFL. What am I doing wrong? Is this language actually context-free? Should I be using a completely different 'z' string?

答:
Let R be a non-terminal that indicates the following:

There are no more a than there are b or c in the final product

Stated alternatively:

For w ϵ G(R), n_a(w) <= n_b(b) and n_a(w) <= n_c(w)

So the rules for this guy are (let ϵ be the empty string):

```<code>R => ϵ

R => bR
R => Rb
R => cR
R => Rc

R => abcR
R => abRc
R => aRbc
R => Rabc

R => acbR
R => acRb
R => aRcb
R => Racb

R => bacR
R => baRc
R => bRac
R => Rbac

R => bcaR
R => bcRa
R => bRca
R => Rbca

R => cbaR
R => cbRa
R => cRba
R => Rcba

R => cabR
R => caRb
R => cRab
R => Rcab
</code>```

Those 29 are all the possibles transformations that guarantees that any word derived from R will have no more as than bs and no more as than cs.

But the question isn't about G(R), it is stated explicitly that n_a(w) <= n_b(b) and n_a(w) <= n_c(w). So, I'll have 3 more non-terminals:

S, the start point

B, derived directly or indirectly from S and guaranteed to have at least one more b than a (considering how it"isborn")

C, derived directly or indirectly from S and guaranteed to have at least one more c than a (considering how it"isborn")

My strategy will be the following:

Those non-terminals will all be similar to R, but they won't have any empty transformation; also, from S I'll have a transformation that will generate bB, or Bb, or cC, or Cc; from B, it is guaranteed to have at least one b more than a, then it will have a transformation to cR or Rc; and for C, transformation to bR or Rb

So, this will be my complete grammar, starting with S:

```<code>S => bB
S => Bb
S => cC
S => Cc

S => bS
S => Sb
S => cS
S => Sc

S => abcS
S => abSc
S => aSbc
S => Sabc

S => acbS
S => acSb
S => aScb
S => Sacb

S => bacS
S => baSc
S => bSac
S => Sbac

S => bcaS
S => bcSa
S => bSca
S => Sbca

S => cbaS
S => cbSa
S => cSba
S => Scba

S => cabS
S => caSb
S => cSab
S => Scab

B => cS
B => Sc

B => bB
B => Bb
B => cB
B => Bc

B => abcB
B => abBc
B => aBbc
B => Babc

B => acbB
B => acBb
B => aBcb
B => Bacb

B => bacB
B => baBc
B => bBac
B => Bbac

B => bcaB
B => bcBa
B => bBca
B => Bbca

B => cbaB
B => cbBa
B => cBba
B => Bcba

B => cabB
B => caBb
B => cBab
B => Bcab

C => bR
C => Rb

C => bC
C => Cb
C => cC
C => Cc

C => abcC
C => abCc
C => aCbc
C => Cabc

C => acbC
C => acCb
C => aCcb
C => Cacb

C => bacC
C => baCc
C => bCac
C => Cbac

C => bcaC
C => bcCa
C => bCca
C => Cbca

C => cbaC
C => cbCa
C => cCba
C => Ccba

C => cabC
C => caCb
C => cCab
C => Ccab

R => ϵ

R => bR
R => Rb
R => cR
R => Rc

R => abcR
R => abRc
R => aRbc
R => Rabc

R => acbR
R => acRb
R => aRcb
R => Racb

R => bacR
R => baRc
R => bRac
R => Rbac

R => bcaR
R => bcRa
R => bRca
R => Rbca

R => cbaR
R => cbRa
R => cRba
R => Rcba

R => cabR
R => caRb
R => cRab
R => Rcab
</code>```

Body:
Let R be a non-terminal that indicates the following:

There are no more a than there are b or c in the final product

Stated alternatively:

For w ϵ G(R), n_a(w) <= n_b(b) and n_a(w) <= n_c(w)

So the rules for this guy are (let ϵ be the empty string):

R => ϵ

R => bR
R => Rb
R => cR
R => Rc

R => abcR
R => abRc
R => aRbc
R => Rabc

R => acbR
R => acRb
R => aRcb
R => Racb

R => bacR
R => baRc
R => bRac
R => Rbac

R => bcaR
R => bcRa
R => bRca
R => Rbca

R => cbaR
R => cbRa
R => cRba
R => Rcba

R => cabR
R => caRb
R => cRab
R => Rcab

Those 29 are all the possibles transformations that guarantees that any word derived from R will have no more as than bs and no more as than cs.

But the question isn't about G(R), it is stated explicitly that n_a(w) <= n_b(b) and n_a(w) <= n_c(w). So, I'll have 3 more non-terminals:

S, the start point

B, derived directly or indirectly from S and guaranteed to have at least one more b than a (considering how it"isborn")

C, derived directly or indirectly from S and guaranteed to have at least one more c than a (considering how it"isborn")

My strategy will be the following:

Those non-terminals will all be similar to R, but they won't have any empty transformation; also, from S I'll have a transformation that will generate bB, or Bb, or cC, or Cc; from B, it is guaranteed to have at least one b more than a, then it will have a transformation to cR or Rc; and for C, transformation to bR or Rb

So, this will be my complete grammar, starting with S:

S => bB
S => Bb
S => cC
S => Cc

S => bS
S => Sb
S => cS
S => Sc

S => abcS
S => abSc
S => aSbc
S => Sabc

S => acbS
S => acSb
S => aScb
S => Sacb

S => bacS
S => baSc
S => bSac
S => Sbac

S => bcaS
S => bcSa
S => bSca
S => Sbca

S => cbaS
S => cbSa
S => cSba
S => Scba

S => cabS
S => caSb
S => cSab
S => Scab

B => cS
B => Sc

B => bB
B => Bb
B => cB
B => Bc

B => abcB
B => abBc
B => aBbc
B => Babc

B => acbB
B => acBb
B => aBcb
B => Bacb

B => bacB
B => baBc
B => bBac
B => Bbac

B => bcaB
B => bcBa
B => bBca
B => Bbca

B => cbaB
B => cbBa
B => cBba
B => Bcba

B => cabB
B => caBb
B => cBab
B => Bcab

C => bR
C => Rb

C => bC
C => Cb
C => cC
C => Cc

C => abcC
C => abCc
C => aCbc
C => Cabc

C => acbC
C => acCb
C => aCcb
C => Cacb

C => bacC
C => baCc
C => bCac
C => Cbac

C => bcaC
C => bcCa
C => bCca
C => Cbca

C => cbaC
C => cbCa
C => cCba
C => Ccba

C => cabC
C => caCb
C => cCab
C => Ccab

R => ϵ

R => bR
R => Rb
R => cR
R => Rc

R => abcR
R => abRc
R => aRbc
R => Rabc

R => acbR
R => acRb
R => aRcb
R => Racb

R => bacR
R => baRc
R => bRac
R => Rbac

R => bcaR
R => bcRa
R => bRca
R => Rbca

R => cbaR
R => cbRa
R => cRba
R => Rcba

R => cabR
R => caRb
R => cRab
R => Rcab


问:
No unique constraint matching given keys for referenced table "users" (PostgreSQL)
so I'm getting an error that no unique constraint matches given keys for one of my tables. I have two tables: Users and Items, of which we have a many-to-one relationship (many items for one user). I am using Flask-SQLAlchemy to do all of this:

```<code>    class ItemModel(db.Model):
        __tablename__ = 'items'

        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(40))
        description = db.Column(db.String(80))
        price = db.Column(db.Float(precision=2))
        emailAddress = db.Column(db.String(40), db.ForeignKey('users.email'))

    class UserModel(db.Model):

        __tablename__ = 'users'

        id = db.Column(db.Integer)
        email = db.Column(db.String(40), primary_key=True)
        name = db.Column(db.String(40))
        last_name = db.Column(db.String(40))

        items = db.relationship('ItemModel', lazy="dynamic")
</code>```

To create the tables, I have this statement in my 'app.py':

```<code>    @app.before_first_request
    def create_database():
        print("Creating tables.")
        db.create_all()
</code>```

The error is: no unique constraint matching given keys for referenced table users.

I am not sure where I'm going wrong since I have a foreign key in ItemModel that matches with the primary key in UserModel. Any suggestions/tips are welcome!

Thanks.

答: I actually got this to work - As Erwin Brandstetter mentioned above, the error occurred because you need to create the user tables first. In my case, I needed to update the user table in terms of the foreign key/primary key relationship on Postgres itself.</p>

Body:
so I'm getting an error that no unique constraint matches given keys for one of my tables. I have two tables: Users and Items, of which we have a many-to-one relationship (many items for one user). I am using Flask-SQLAlchemy to do all of this:

    class ItemModel(db.Model):
        __tablename__ = 'items'

        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(40))
        description = db.Column(db.String(80))
        price = db.Column(db.Float(precision=2))
        emailAddress = db.Column(db.String(40), db.ForeignKey('users.email'))

    class UserModel(db.Model):

        __tablename__ = 'users'

        id = db.Column(db.Integer)
        email = db.Column(db.String(40), primary_key=True)
        name = db.Column(db.String(40))
        last_name = db.Column(db.String(40))

        items = db.relationship('ItemModel', lazy="dynamic")

To create the tables, I have this statement in my 'app.py':

    @app.before_first_request
    def create_database():
        print("Creating tables.")
        db.create_all()

The error is: no unique constraint matching given keys for referenced table users.

I am not sure where I'm going wrong since I have a foreign key in ItemModel that matches with the primary key in UserModel. Any suggestions/tips are welcome!

Thanks.


问:
best way to add an xml element around xml or a row-by-row basis
On SQL Server 2012 (SP1), what's the best way to take data that looks like this:

```<code>declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>')

id  data
1   <node />
2   <node />
</code>```

and turn it into

```<code>id  data
1   <root><node /></root>
2   <root><node /></root>
</code>```

?

Is there a way that's more efficient than just converting it to character data, adding the node start and end tag and then converting it back to xml? I'm dealing with this issue on larger data sets, so this is just a simple example.

答:
You can use simple XQuery to add <root> parent in your query result. No back-and-forth conversion between XML and VARCHAR data types involved :

```<code>SELECT  id, data.query('<root>{.}</root>') AS data
FROM @t
</code>```

Quick test : http://rextester.com/RLZ30365

Brief explanation :

{} : indicates that texts in between should be treated as XQuery expression instead of literals

. : reference to current context node, which in this case is <node />

Body:
On SQL Server 2012 (SP1), what's the best way to take data that looks like this:

declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>')

id  data
1   <node />
2   <node />

and turn it into

id  data
1   <root><node /></root>
2   <root><node /></root>

?

Is there a way that's more efficient than just converting it to character data, adding the node start and end tag and then converting it back to xml? I'm dealing with this issue on larger data sets, so this is just a simple example.

Body:
You can use simple XQuery to add <root> parent in your query result. No back-and-forth conversion between XML and VARCHAR data types involved :

SELECT  id, data.query('<root>{.}</root>') AS data
FROM @t

Quick test : http://rextester.com/RLZ30365

Brief explanation :

{} : indicates that texts in between should be treated as XQuery expression instead of literals

. : reference to current context node, which in this case is <node />


问:
Segmentation Fault when using sscanf
In a file, each line either starts with a word or a tab, for example:

this test

------tab  // using dashes because multiple spaces make it code format

not tab

In my loop i am trying to get each word, using sscanf. Here is my code:

```<code>while(fgets(str, sizeof(str), file) != NULL) {
     if(str[0] == '\t') {
        char *test;
        sscanf(str, "%s", test);
     }
     // This following code gives the segmentation fault
     else {
          char *temp;
          sscanf(str, "%s", temp);
     }
}
</code>```

I tried outputting the str in the else and it is a valid str.

答:
Your "temp" and "test" pointers are uninitialized, so any attempt to sscanf() into them will crash.

Replace them with static arrays (e.g. char temp[100];) or point them to allocated memory (e.g. char *temp = malloc(100);, which you'll need to free() afterwards), but be aware that using (s)scanf like that is dangerous due to the potential of buffer overflows.

Title: Segmentation Fault when using sscanf

Body:
In a file, each line either starts with a word or a tab, for example:

this test

------tab  // using dashes because multiple spaces make it code format

not tab

In my loop i am trying to get each word, using sscanf. Here is my code:

while(fgets(str, sizeof(str), file) != NULL) {
     if(str[0] == '\t') {
        char *test;
        sscanf(str, "%s", test);
     }
     // This following code gives the segmentation fault
     else {
          char *temp;
          sscanf(str, "%s", temp);
     }
}

I tried outputting the str in the else and it is a valid str.


问:
Rails 3 Multi Model Form with Multiple new instances of submodel
I have three models presented in a multi-model form.

```<code>class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  has_many :other_children
  accepts_nested_attributes_for :other_children
end

class OtherChild < ActiveRecord::Base
  belongs_to :child
end

= form_for @parent do |f|
  # fields for parent
  = f.fields_for :children, @parent.children do |cf|
    = cf.fields_for :other_children, @parent.children do |ocf|
      # fields_for other child
    = cf.fields_for :other_children, @parent.children.new do |ocf|
      # fields_for other child
</code>```

This works except when I duplicate the second set of child fields via jquery. To be more clear, the fields_for with the new other_child model has a create button which trigger some jquery such as $(new_child_form).clone().insertBefore($(new_child_form)) allowing more than one child model to be added in the same form submit. I know I could submit each child form individually via ajax but this is not what I want.

Rails is getting more than one parent[children_attributes][0][other_children_attributes][1] and only seems to use the last one. Any ideas?

答: You can do this with or without using jQuery to clone.  I solved this problem by having a link invoke Javascript that inserted elements but generated a unique ID based on the current time.  If you do go with jQuery for cloning you have to be sure to update the IDs of the cloned fields so Rails treats them as new children.  Ryan Bates illustrates how to do this in Railscasts 196-197 and his solution continues to work with Rails 3.</p>

Body:
I have three models presented in a multi-model form.

class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  has_many :other_children
  accepts_nested_attributes_for :other_children
end

class OtherChild < ActiveRecord::Base
  belongs_to :child
end

= form_for @parent do |f|
  # fields for parent
  = f.fields_for :children, @parent.children do |cf|
    = cf.fields_for :other_children, @parent.children do |ocf|
      # fields_for other child
    = cf.fields_for :other_children, @parent.children.new do |ocf|
      # fields_for other child

This works except when I duplicate the second set of child fields via jquery. To be more clear, the fields_for with the new other_child model has a create button which trigger some jquery such as $(new_child_form).clone().insertBefore($(new_child_form)) allowing more than one child model to be added in the same form submit. I know I could submit each child form individually via ajax but this is not what I want.

Rails is getting more than one parent[children_attributes][0][other_children_attributes][1] and only seems to use the last one. Any ideas?


问:
Randomly Generate a Word from a txt.file (Python)
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

```<code>ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")
</code>```

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

```<code>Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.
</code>```

答:
Instead of manually incrementing i, you could use enumerate(). The problem with your code is that you do line = lines[i]. You're taking the character at i position and assigning it to line.

```<code>for i, line in enumerate(ifile.readlines(), start=1):
    words = line.split()
    myword = random.choice(words)

    otfile.write("Line: %d - Word: %s\n" % (i, myword))
</code>```

The output of course changes due to the randomness. However a run could yield:

```<code>Line: 1 - Word: the
Line: 2 - Word: chocolate
Line: 3 - Word: I
Line: 4 - Word: was
Line: 5 - Word: clothes
</code>```

Body:
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.

Body:
Instead of manually incrementing i, you could use enumerate(). The problem with your code is that you do line = lines[i]. You're taking the character at i position and assigning it to line.

for i, line in enumerate(ifile.readlines(), start=1):
    words = line.split()
    myword = random.choice(words)

    otfile.write("Line: %d - Word: %s\n" % (i, myword))

The output of course changes due to the randomness. However a run could yield:

Line: 1 - Word: the
Line: 2 - Word: chocolate
Line: 3 - Word: I
Line: 4 - Word: was
Line: 5 - Word: clothes


问:
Unique git url for github repo with multiple branches?
I'm looking at a flask app which I would like to import into an openshift project (https://github.com/lpolepeddi/intro-to-flask) . This contains a a series of 'checkpoints'(branches) as part of a tut. I want to grab the final code which is at https://github.com/lpolepeddi/intro-to-flask/tree/20_visibility_control for the starting point of a project . Is the a way to get a unique git url for this branch of the form

```<code>https://github.com/lpolepeddi/intro-to-flask.git
</code>```

So that I can pull it in with a command like:

```<code> git remote add upstream -m master https://github.com/shekhargulati/flask-login-openshift-quickstart.git
</code>```

答:
Although as far as I know "single branch GitHub url" doesn't exist, you could just clone entire repo and later change branch:

```<code>git clone https://github.com/lpolepeddi/intro-to-flask.git
cd intro-to-flask
git checkout 20_visibility_control
</code>```

or as stated in this answer, clone only one branch:

```<code>git clone --branch 20_visibility_control --single-branch https://github.com/lpolepeddi/intro-to-flask.git
</code>```

Body:
I'm looking at a flask app which I would like to import into an openshift project (https://github.com/lpolepeddi/intro-to-flask) . This contains a a series of 'checkpoints'(branches) as part of a tut. I want to grab the final code which is at https://github.com/lpolepeddi/intro-to-flask/tree/20_visibility_control for the starting point of a project . Is the a way to get a unique git url for this branch of the form

https://github.com/lpolepeddi/intro-to-flask.git

So that I can pull it in with a command like:

 git remote add upstream -m master https://github.com/shekhargulati/flask-login-openshift-quickstart.git

Body:
Although as far as I know "single branch GitHub url" doesn't exist, you could just clone entire repo and later change branch:

git clone https://github.com/lpolepeddi/intro-to-flask.git
cd intro-to-flask
git checkout 20_visibility_control

or as stated in this answer, clone only one branch:

git clone --branch 20_visibility_control --single-branch https://github.com/lpolepeddi/intro-to-flask.git


问:
scanf is collecting the wrong input
```<code> #include<stdio.h>
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }
</code>```

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.

答:
You need to use "%lf" for double.

This is the warning from clang compiler.

warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
    scanf("%f", &c);

Here is the scanf reference. It's format is %[*][width][length]specifier. The specifier for 'floating point number' is f. So we use %f to read float x. To read double x, we need to specify the length as l. Combined the format is %lf.

Title: scanf is collecting the wrong input

Body:
 #include<stdio.h>
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.


问:
How to swap a disabled option DOM element to enabled?
I have a list with enabled and disabled option. I do know how to disable an option element but what I don't know how to enable it again.

```<code><select size="1" id="x">
  <option value="47" disabled="disabled">Value 47</option>
  ...

selectElement.options[i].disabled = 'disabled';
// ... how to enable?
</code>```

It should be done with Plain Javascript and no JavaScript Framework. (I wish I could use Prototype or a similar framework but I cannot introduce one of them.)

答:
The DOM object's property is a boolean value, that should be set to true or false:

```<code>selectElement.options[i].disabled = false;
</code>```

Also see Boolean HTML Attributes.

Body:
I have a list with enabled and disabled option. I do know how to disable an option element but what I don't know how to enable it again.

<select size="1" id="x">
  <option value="47" disabled="disabled">Value 47</option>
  ...

selectElement.options[i].disabled = 'disabled';
// ... how to enable?

It should be done with Plain Javascript and no JavaScript Framework. (I wish I could use Prototype or a similar framework but I cannot introduce one of them.)

Body:
The DOM object's property is a boolean value, that should be set to true or false:

selectElement.options[i].disabled = false;

Also see Boolean HTML Attributes.


答:
```<code>i=1
for lines in ifile:
  print(lines)
  words = lines.strip().split()
  print(words)
  myword = random.choice(words)
  print(myword[random.randrange(0, len(myword))])
  myword = myword[random.randrange(0, len(myword))]  # chr , need str Comment this line
</code>```

Title: Randomly Generate a Word from a txt.file (Python)


问:
Compare date to range of dates in CSV - BASH
I am trying to compare user input to a here doc to compare if the input is greater or lesser than 2 numbers (dates), and if it is I print the first column.
My file looks like this:

```<code>Earth,19480210,19490228
Earth,19490229,19500216
Metal,19500217,19510205
</code>```

user could input 20100215 as the date. Here is my while loop which compares using  2 variables contained within a while read

```<code>while IFS=, read -r term start end; do
if [[ $query -ge $start && $query -le $end ]];then
    echo $term
fi
    echo $query
    exit
done << EOF
$(cat chzod)
EOF
</code>```

The output looks like this: Your chinese zodiac is: Water

Fire

Earth

I do not know why the while loop generates multiple elements, and if there are any possible solutions to this.
Thanks,
Kieran

答:
Your question is still a bit unclear, and I'm somewhat reading between the lines here, but if I'm guessing right, you want to loop over all entries in the CSV file, and if the $query falls between start and end, you want to output term. But, if after looping through the entire file, if no match is made, you are attempting to print out the query again?

If that is the case, then you are stumbling over the loop logic. There are many ways to handle this, but when executing multiple queries, of which you need to confirm whether a match was made, the easiest solution is simply to set a flag you toggle when a match is made. Then after completing all comparisons, you check the flag to see if it has been set.

A quick example would be:

```<code>#!/bin/bash

fname="${1:-chzod}"    # take csv file as first argument (default: chzod)

printf "query: "       # prompt for query
read -r query

test -z query && exit  # validate query

declare -i matched=0   # declare matched flag, set to '0'

while IFS=, read -r term start end; do
    if [[ $query -ge $start && $query -le $end ]];then
        echo $term
        matched=1      # set 'matched' flag
    fi
done < "$fname"        # redirect CSV file into loop

# check 'matched' flag and if unset, output unmatched query
test "$matched" -eq '0' && echo "unmatched query: $query"
</code>```

Example Use/Output

Using your CSV file, you would expect the following example results:

```<code>$ bash readearth.sh dat/earth.dat
query: 19490229
Earth

$ bash readearth.sh dat/earth.dat
query: 19510204
Metal

$ bash readearth.sh dat/earth.dat
query: 20100215
unmatched query: 20100215
</code>```

If I misinterpreted your intent, just drop me a line and I'm happy to help further.

Body:
I am trying to compare user input to a here doc to compare if the input is greater or lesser than 2 numbers (dates), and if it is I print the first column.
My file looks like this:

Earth,19480210,19490228
Earth,19490229,19500216
Metal,19500217,19510205

user could input 20100215 as the date. Here is my while loop which compares using  2 variables contained within a while read

while IFS=, read -r term start end; do
if [[ $query -ge $start && $query -le $end ]];then
    echo $term
fi
    echo $query
    exit
done << EOF
$(cat chzod)
EOF

The output looks like this: Your chinese zodiac is: Water

Fire

Earth

I do not know why the while loop generates multiple elements, and if there are any possible solutions to this.
Thanks,
Kieran

Body:
Your question is still a bit unclear, and I'm somewhat reading between the lines here, but if I'm guessing right, you want to loop over all entries in the CSV file, and if the $query falls between start and end, you want to output term. But, if after looping through the entire file, if no match is made, you are attempting to print out the query again?

If that is the case, then you are stumbling over the loop logic. There are many ways to handle this, but when executing multiple queries, of which you need to confirm whether a match was made, the easiest solution is simply to set a flag you toggle when a match is made. Then after completing all comparisons, you check the flag to see if it has been set.

A quick example would be:

#!/bin/bash

fname="${1:-chzod}"    # take csv file as first argument (default: chzod)

printf "query: "       # prompt for query
read -r query

test -z query && exit  # validate query

declare -i matched=0   # declare matched flag, set to '0'

while IFS=, read -r term start end; do
    if [[ $query -ge $start && $query -le $end ]];then
        echo $term
        matched=1      # set 'matched' flag
    fi
done < "$fname"        # redirect CSV file into loop

# check 'matched' flag and if unset, output unmatched query
test "$matched" -eq '0' && echo "unmatched query: $query"

Example Use/Output

Using your CSV file, you would expect the following example results:

$ bash readearth.sh dat/earth.dat
query: 19490229
Earth

$ bash readearth.sh dat/earth.dat
query: 19510204
Metal

$ bash readearth.sh dat/earth.dat
query: 20100215
unmatched query: 20100215

If I misinterpreted your intent, just drop me a line and I'm happy to help further.


问:
Buffer overflow in c and order of pushing local variables on stack
Firstly, I'm using this compilation flags:
gcc -fno-stack-protector -z execstack -m 32

Ok lets look, on code below

```<code>int main(int argc, char *argv[]){
    char pass[8];
    char logged = 'n';
    strcpy( pass, argv[1] );
    if( logged == 'y' ){
        printf("Hello \n");
    } else {
        printf("Run hacker :(\n");
    }
    return 0;
}
</code>```

And second code

```<code>int main(int argc, char *argv[]){
    char logged = 'n';
    char pass[8];
    strcpy( pass, argv[1] );
    if( logged == 'y' ){
        printf("Hello \n");
    } else {
        printf("Run hacker :(\n");
    }
    return 0;
}
</code>```

These codes are vulnerable for stack overflow attack. (passing 'yyyyyyyyy' as arg would pass the test)

But why? Order of local variables in second code is different than in first code. So queue of pushing local variables on stack should be other too, but it is not?

答:
First a stack overflow vulnerability is not exactly the same thing as stack corruption.

This code is writing an automatic variable that is allocated on the stack (in your frame). The compiler reserved 8 bytes on the stack for the pass string. If you write more than 8 bytes, you will be corrupting whatever else is on the stack right next to pass[] array. Doesn't really matter what it is; it will be corrupted, and that is what stack corruption means.

With some skill, one can generate an input (argv[1]) string (really an instruction byte stream) that will align with the return instruction from the main and thus can force execution of your code. That is what vulnerability is.

You seem to understand that the order of variables on your stack just determines what and how may be corrupted, and you should see exactly what you expected if you turn off the stack protection by using -fno-stack-protector, plus minus the exact stack layout imposed by your compiler. With the protection on, both cases should dump the stack smashing backtrace and diagnostics.

Note that different linux distrubution set the no-stack-protector default to different values, but as long as you explicitly control it on the command line you are all set.
The -z execstack option is a mechanism dealing with whether or not to allow executing on the stack; here it is irrelevant as your code is just corrupting the stack.

Body:
Firstly, I'm using this compilation flags:
gcc -fno-stack-protector -z execstack -m 32

Ok lets look, on code below

int main(int argc, char *argv[]){
    char pass[8];
    char logged = 'n';
    strcpy( pass, argv[1] );
    if( logged == 'y' ){
        printf("Hello \n");
    } else {
        printf("Run hacker :(\n");
    }
    return 0;
}

And second code

int main(int argc, char *argv[]){
    char logged = 'n';
    char pass[8];
    strcpy( pass, argv[1] );
    if( logged == 'y' ){
        printf("Hello \n");
    } else {
        printf("Run hacker :(\n");
    }
    return 0;
}

These codes are vulnerable for stack overflow attack. (passing 'yyyyyyyyy' as arg would pass the test)

But why? Order of local variables in second code is different than in first code. So queue of pushing local variables on stack should be other too, but it is not?


问:
Centering Text In CSS
I'm sorry I know this is SUPER simple but I cannot figure this out.

Here is my current Css style

```<code>@import url(https://fonts.googleapis.com/css?family=Advent+Pro:100);
html {
}
#overlay {
font-family: 'Advent Pro', sans-serif;
font-size: 7em;
margin: .2em .5em;
color: rgba(255, 255, 255, 1);
position: fixed;
right: 0;
}
video#bgvid {
position: fixed;
right: 0;
top: 0;
width: 100%;
height: auto;
z-index: -100;
background-size: cover;
}
</code>```

How can I center #overlay?!

答:
Use text-align:center. You may need to give it a width too like 100% if needed.

Hope this helps.

Title: Centering Text In CSS

Body:
I'm sorry I know this is SUPER simple but I cannot figure this out.

Here is my current Css style

@import url(https://fonts.googleapis.com/css?family=Advent+Pro:100);
html {
}
#overlay {
font-family: 'Advent Pro', sans-serif;
font-size: 7em;
margin: .2em .5em;
color: rgba(255, 255, 255, 1);
position: fixed;
right: 0;
}
video#bgvid {
position: fixed;
right: 0;
top: 0;
width: 100%;
height: auto;
z-index: -100;
background-size: cover;
}

How can I center #overlay?!


问:
HTTP request doesn't fire off
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.</p>

```<code>import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}
</code>```

答:
This is from the documentation:

The http.get does not send the request just yet. This Observable is cold, which means that the request won't go out until something subscribes to the Observable.

See this link for more information and a detailed example: https://angular.io/docs/ts/latest/guide/server-communication.html

Here is a specific example:

```<code>getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}
</code>```

And then subscribe to it as so:

```<code>ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}
</code>```

Title: HTTP request doesn't fire off

Body:
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.

import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}

Body:
This is from the documentation:

The http.get does not send the request just yet. This Observable is cold, which means that the request won't go out until something subscribes to the Observable.

See this link for more information and a detailed example: https://angular.io/docs/ts/latest/guide/server-communication.html

Here is a specific example:

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

And then subscribe to it as so:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}


问:
How to debug React Express Webpack app in WebStorm
I'm trying to debug the back-end of the react - express application. I'm using webpack for bundling.

How to edit configuration on WebStorm so that I could debug both front end and back-end? I'm using WebStorm 2016.

答:
Went through some documentations on WebStrom and finally managed to get it working. First select Edit Configurations then a menu will pop up which will allow you to edit Run/Debug Configurations. Click the + button on the left side and add a node js. From that change the Node interpreter  from default(local) node_modules to the babel node inside your project dependencies. eg ~/MyWork/Project/node_modules/.bin/babel-node. Then Add --presets=babel-preset-es2015 as Node Parameters. Fill the rest of the configurations and click save and run the project.

Here is an example:


问:
Data Import Apache Solr to Datastax Solr - DateFormat Transformer DIH
I am trying to import data from Apache Solr to Datastax Solr using DIH. I am able to fetch the document, but when DIh tries to create the document I get the below error in date fields:

```<code>org.apache.solr.common.SolrException: Invalid Date String:'Thu Jun 08 16:23:00 PDT 2017'
at org.apache.solr.schema.DateField.parseMath(DateField.java:182)
at com.datastax.bdp.search.solr.core.types.V1TypeMapper.formatToCassandraType(V1TypeMapper.java:166)
at com.datastax.bdp.search.solr.core.types.V2TypeMapper.formatToCassandraType(V2TypeMapper.java:101)
at com.datastax.bdp.search.solr.Cql3CassandraRowWriter.write(Cql3CassandraRowWriter.java:170)
at com.datastax.bdp.search.solr.handler.update.CassandraDirectUpdateHandler.addDoc(CassandraDirectUpdateHandler.java:161)
at org.apache.solr.update.processor.RunUpdateProcessor.processAdd(RunUpdateProcessorFactory.java:69)
at org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:51)
at org.apache.solr.update.processor.DistributedUpdateProcessor.versionAdd(DistributedUpdateProcessor.java:595)
at org.apache.solr.update.processor.DistributedUpdateProcessor.processAdd(DistributedUpdateProcessor.java:435)
at org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:51)
at org.apache.solr.update.processor.AbstractDefaultValueUpdateProcessorFactory$DefaultValueUpdateProcessor.processAdd(AbstractDefaultValueUpdateProcessorFactory.java:94)
at org.apache.solr.handler.dataimport.SolrWriter.upload(SolrWriter.java:70)
at org.apache.solr.handler.dataimport.DataImportHandler$1.upload(DataImportHandler.java:235)
at org.apache.solr.handler.dataimport.DocBuilder.buildDocument(DocBuilder.java:504)
at org.apache.solr.handler.dataimport.DocBuilder.buildDocument(DocBuilder.java:408)
at org.apache.solr.handler.dataimport.DocBuilder.doFullDump(DocBuilder.java:323)
at org.apache.solr.handler.dataimport.DocBuilder.execute(DocBuilder.java:231)
at org.apache.solr.handler.dataimport.DataImporter.doFullImport(DataImporter.java:411)
at org.apache.solr.handler.dataimport.DataImporter.runCmd(DataImporter.java:476)
at org.apache.solr.handler.dataimport.DataImporter$1.run(DataImporter.java:457)
</code>```

I am using the DateFormat transformer in my DIH but there seems to be no effect on it. DateFormat transformer transforms the date fiels from Apache Solr to the format specified in 'dateTimeFormat' before creating the document to index in Datastax Solr.

```<code><dataConfig>
  <document>
     <entity name="sep_byOrderNumber" processor="SolrEntityProcessor" query="OrderNumber:${dataimporter.request.OrderNumberList}" rows="${dataimporter.request.batchSize}" url="${dataimporter.request.urlSource}" transformer="DateFormatTransformer" loglevel="debug">
      <field column="OrderCreateDate" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ" />
     </entity>
  </document>
</dataconfig>
</code>```

Can someone please help identify the issue?

答:
Change your dateTimeFormat to : EEE MMM dd HH:mm:ss z yyyy

```<code>Letter  Date or Time Component             Presentation Examples
y       Year                               Year         1996; 96
M       Month in year (context sensitive)  Month        July; Jul; 07
d       Day in month                       Number       10
E       Day name in week                   Text         Tuesday; Tue
H       Hour in day (0-23)                 Number       0
m       Minute in hour                     Number       30
s       Second in minute                   Number       55
z       Time zone                          Time zone    Pacific Standard Time; PST; GMT-08:00
</code>```

Source : http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Body:
I am trying to import data from Apache Solr to Datastax Solr using DIH. I am able to fetch the document, but when DIh tries to create the document I get the below error in date fields:

org.apache.solr.common.SolrException: Invalid Date String:'Thu Jun 08 16:23:00 PDT 2017'
at org.apache.solr.schema.DateField.parseMath(DateField.java:182)
at com.datastax.bdp.search.solr.core.types.V1TypeMapper.formatToCassandraType(V1TypeMapper.java:166)
at com.datastax.bdp.search.solr.core.types.V2TypeMapper.formatToCassandraType(V2TypeMapper.java:101)
at com.datastax.bdp.search.solr.Cql3CassandraRowWriter.write(Cql3CassandraRowWriter.java:170)
at com.datastax.bdp.search.solr.handler.update.CassandraDirectUpdateHandler.addDoc(CassandraDirectUpdateHandler.java:161)
at org.apache.solr.update.processor.RunUpdateProcessor.processAdd(RunUpdateProcessorFactory.java:69)
at org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:51)
at org.apache.solr.update.processor.DistributedUpdateProcessor.versionAdd(DistributedUpdateProcessor.java:595)
at org.apache.solr.update.processor.DistributedUpdateProcessor.processAdd(DistributedUpdateProcessor.java:435)
at org.apache.solr.update.processor.UpdateRequestProcessor.processAdd(UpdateRequestProcessor.java:51)
at org.apache.solr.update.processor.AbstractDefaultValueUpdateProcessorFactory$DefaultValueUpdateProcessor.processAdd(AbstractDefaultValueUpdateProcessorFactory.java:94)
at org.apache.solr.handler.dataimport.SolrWriter.upload(SolrWriter.java:70)
at org.apache.solr.handler.dataimport.DataImportHandler$1.upload(DataImportHandler.java:235)
at org.apache.solr.handler.dataimport.DocBuilder.buildDocument(DocBuilder.java:504)
at org.apache.solr.handler.dataimport.DocBuilder.buildDocument(DocBuilder.java:408)
at org.apache.solr.handler.dataimport.DocBuilder.doFullDump(DocBuilder.java:323)
at org.apache.solr.handler.dataimport.DocBuilder.execute(DocBuilder.java:231)
at org.apache.solr.handler.dataimport.DataImporter.doFullImport(DataImporter.java:411)
at org.apache.solr.handler.dataimport.DataImporter.runCmd(DataImporter.java:476)
at org.apache.solr.handler.dataimport.DataImporter$1.run(DataImporter.java:457)

I am using the DateFormat transformer in my DIH but there seems to be no effect on it. DateFormat transformer transforms the date fiels from Apache Solr to the format specified in 'dateTimeFormat' before creating the document to index in Datastax Solr.

<dataConfig>
  <document>
     <entity name="sep_byOrderNumber" processor="SolrEntityProcessor" query="OrderNumber:${dataimporter.request.OrderNumberList}" rows="${dataimporter.request.batchSize}" url="${dataimporter.request.urlSource}" transformer="DateFormatTransformer" loglevel="debug">
      <field column="OrderCreateDate" dateTimeFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ" />
     </entity>
  </document>
</dataconfig>

Can someone please help identify the issue?

Body:
Change your dateTimeFormat to : EEE MMM dd HH:mm:ss z yyyy

Letter  Date or Time Component             Presentation Examples
y       Year                               Year         1996; 96
M       Month in year (context sensitive)  Month        July; Jul; 07
d       Day in month                       Number       10
E       Day name in week                   Text         Tuesday; Tue
H       Hour in day (0-23)                 Number       0
m       Minute in hour                     Number       30
s       Second in minute                   Number       55
z       Time zone                          Time zone    Pacific Standard Time; PST; GMT-08:00

Source : http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html


问:
how to efficiently build up complex case class in my app flow?
I have a controller method that extract the request from the client to ModelOne, and I need to change this model one and build it up to a bigger model lets call it ModelTwo so I can sent it to another service.

This is ModelOne case class:

```<code>case class ModelOne(list: List[String], expectedListSize: Int)
</code>```

And this is ModelTwo case class:

```<code>case class ModelTwo(modelThree: Option[ModelThree])

case class ModelThree(status: Status(its enum),
                                        list: List[String],
                                        amount: Option[Int],
                                        message: Option[String])
</code>```

So what I'm doing to build it up currently is whenever I get the request from the client in the controller I call a service that have a method to build it up since I need to take the list property from ModelOne and build ModelTwo, it looks like this:

```<code>def buildModelTwoResponse(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
}
</code>```

so in the controller I go:

```<code>val modelOne = request.body.extractOpt[ModelOne]

val modelTwo = myService.buildModelTwoResponse(modelOne)
</code>```

Is there a more elegant way to do this?

答:
A more elegant way would be to define a second constructor for your ModelTwo type in its companion object by defining an apply function:

```<code>case class ModelTwo(modelThree: Option[ModelThree])

// Add this
object ModelTwo {

  // Move your service function logic to here
  def apply(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
  }
}
</code>```

Then you wouldn't need your service function anymore, so instead of doing this:

```<code>// You don't need this
val modelTwo = myService.buildModelTwoResponse(modelOne)
</code>```

You could do this:

```<code>val modelTwo = ModelTwo(modelOne)
</code>```

Body:
I have a controller method that extract the request from the client to ModelOne, and I need to change this model one and build it up to a bigger model lets call it ModelTwo so I can sent it to another service.

This is ModelOne case class:

case class ModelOne(list: List[String], expectedListSize: Int)

And this is ModelTwo case class:

case class ModelTwo(modelThree: Option[ModelThree])

case class ModelThree(status: Status(its enum),
                                        list: List[String],
                                        amount: Option[Int],
                                        message: Option[String])

So what I'm doing to build it up currently is whenever I get the request from the client in the controller I call a service that have a method to build it up since I need to take the list property from ModelOne and build ModelTwo, it looks like this:

def buildModelTwoResponse(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
}

so in the controller I go:

val modelOne = request.body.extractOpt[ModelOne]

val modelTwo = myService.buildModelTwoResponse(modelOne)

Is there a more elegant way to do this?

Body:
A more elegant way would be to define a second constructor for your ModelTwo type in its companion object by defining an apply function:

case class ModelTwo(modelThree: Option[ModelThree])

// Add this
object ModelTwo {

  // Move your service function logic to here
  def apply(modelOne: ModelOne): ModelTwo = {
    ModelTwo(Some(ModelThree(Status.Done, modelOne.list, None, None)))
  }
}

Then you wouldn't need your service function anymore, so instead of doing this:

// You don't need this
val modelTwo = myService.buildModelTwoResponse(modelOne)

You could do this:

val modelTwo = ModelTwo(modelOne)


问:
Why do we need Buffer.isBuffer method?
Why do we need  Buffer.isBuffer method when we know it's doing the same thing as instanceof Buffer ?

https://github.com/nodejs/node/blob/master/lib/buffer.js#L306

答:
It's not technically necessary. It exists for convenience and is probably, to at least a degree, idiomatic.

No extended explanation was given when it was defined, but it appears to have been a refactoring (DRY – answer "what is a buffer" once and reuse) and/or a stylistic preference:

```<code>-  if (!(buffer instanceof Buffer)) {
+  if (!Buffer.isBuffer(buffer)) {
</code>```

There was probably some inspiration taken from Array.isArray().

And, it does also offer some additional backwards compatibility (or possibly some future-proofing), as not all of Node's versions have had a single type for Buffers:

```<code>Buffer.isBuffer = function isBuffer(b) {
  return b instanceof Buffer || b instanceof SlowBuffer;
};
</code>```

Title: Why do we need Buffer.isBuffer method?

Body:
It's not technically necessary. It exists for convenience and is probably, to at least a degree, idiomatic.

No extended explanation was given when it was defined, but it appears to have been a refactoring (DRY – answer "what is a buffer" once and reuse) and/or a stylistic preference:

-  if (!(buffer instanceof Buffer)) {
+  if (!Buffer.isBuffer(buffer)) {

There was probably some inspiration taken from Array.isArray().

And, it does also offer some additional backwards compatibility (or possibly some future-proofing), as not all of Node's versions have had a single type for Buffers:

Buffer.isBuffer = function isBuffer(b) {
  return b instanceof Buffer || b instanceof SlowBuffer;
};


问:
Autolayout constraint issue for tableview
When I switch orientation

Hi, I am trying to get my table to be constrained with all selected in the left side of the picture. It is giving me errors which you can see on the right. Can anyone help me fix those errors? Thanks!

答: Click on "Resolve Auto Layout issues"  and select "reset to suggested constraint". It'll be helpful for you.


问:
User-defined formula not updating after opening Excel 2013 and acknowledging Security Warning
After opening an Excel 2013 Worksheet, I get the following messages:

"Protected View - Be careful ..." and the button "Enable Editing"

"Security Warning - Some active content has been disabled. Click for more details." and the button "Enable Content".

These are expected messages that pop up in accordance to my Trust Center Settings, as I use macros and user-defined functions stored in my add-in.

The problem I'm recently experiencing is, that I'm get different results depending on how I acknowledge the "Security Warning":

a) If I click the "Enable Content" button, then my custom formulas return the #NAME? error in those cells that contain my user-defined formulas (e.g. ufCombineRanges).  Re-calculating manually (F9) doesn't solve the problem.  On the other hand, if I select the cell, edit it (F2) and press Enter, then the formula computes and continues to update correctly after that.

Result after pressing Security Warning "Enable Content" Button

b) If I click the "X" button, then my custom formulas compute and continue to update correctly.

Result after pressing Security Warning X Button

When using the user-defined formula in a brand new worksheet, this does not happen.  The problem seems to be related to the way Excel updates the formulas after pressing that "Enable Content" button.

Any ideas what the cause could be, i.e. how this can be fixed?

Is there a function that can be called, that will update the user-defined formulas, other than the equivalent of F9?

Any help/ideas are greatly appreciated.

FYI:  This is the code for the user-defined function:

```<code>Function ufCombineRanges(Separator As String, ParamArray Ranges() As Variant) As String
    Application.Volatile
    Dim i As Long
    Dim TheRange As Variant
    For i = LBound(Ranges) To UBound(Ranges)
        For Each TheRange In Ranges(i)
            If TheRange.Text <> "" Then
                OutStr = OutStr & TheRange.Text & Separator
            End If
         Next TheRange
    Next i
    If Len(OutStr) > 0 Then
        ufCombineRanges = Left(OutStr, Len(OutStr) - Len(Separator))
    Else
        ufCombineRanges = ""
    End If
End Function
</code>```

答:
If the UDFs are in linked workbooks/add-ins, then you should be able to Edit Links.. Change-Source or Check-Status.

If the UDFs are defined in the same workbook, you might need to update all of the formulas. The easy way to do that is to Find/Replace all "=" with "=", which effectively changes all of your formulas without actually changing them, but it's enough to make Excel calculate the cells. Then save, and you shouldn't have the problem again.

Body:
After opening an Excel 2013 Worksheet, I get the following messages:

"Protected View - Be careful ..." and the button "Enable Editing"

"Security Warning - Some active content has been disabled. Click for more details." and the button "Enable Content".

These are expected messages that pop up in accordance to my Trust Center Settings, as I use macros and user-defined functions stored in my add-in.

The problem I'm recently experiencing is, that I'm get different results depending on how I acknowledge the "Security Warning":

a) If I click the "Enable Content" button, then my custom formulas return the #NAME? error in those cells that contain my user-defined formulas (e.g. ufCombineRanges).  Re-calculating manually (F9) doesn't solve the problem.  On the other hand, if I select the cell, edit it (F2) and press Enter, then the formula computes and continues to update correctly after that.

Result after pressing Security Warning "Enable Content" Button

b) If I click the "X" button, then my custom formulas compute and continue to update correctly.

Result after pressing Security Warning X Button

When using the user-defined formula in a brand new worksheet, this does not happen.  The problem seems to be related to the way Excel updates the formulas after pressing that "Enable Content" button.

Any ideas what the cause could be, i.e. how this can be fixed?

Is there a function that can be called, that will update the user-defined formulas, other than the equivalent of F9?

Any help/ideas are greatly appreciated.

FYI:  This is the code for the user-defined function:

Function ufCombineRanges(Separator As String, ParamArray Ranges() As Variant) As String
    Application.Volatile
    Dim i As Long
    Dim TheRange As Variant
    For i = LBound(Ranges) To UBound(Ranges)
        For Each TheRange In Ranges(i)
            If TheRange.Text <> "" Then
                OutStr = OutStr & TheRange.Text & Separator
            End If
         Next TheRange
    Next i
    If Len(OutStr) > 0 Then
        ufCombineRanges = Left(OutStr, Len(OutStr) - Len(Separator))
    Else
        ufCombineRanges = ""
    End If
End Function


问:
Keeps on "Launching : Launching delegate ... "
I just start to try out my Hello World app development on Bada. I installed the SDK 1.0.0 on Windows XP (VM on Mac OS X).

In my Hello World app, I only add a Form and modified OnAppInitializing function and OnForeground function.

I tried both Run and Debug. The simulator is launched and running fine. But the progress of my Hello World is always 78% ~ 82% with "Launching : Launching delegate ..." The Hello World app is not shown on screen.

Any hint ?

答: Reinstalled SDK and it works fine now.</p>

Body: Reinstalled SDK and it works fine now.


问:
Change FROM and REPLYTO address in Laravel 5.4
i can't send email with user address as FROM and Reply To

In the FormRequest :

```<code>    public function persist()
{
    $reservation = Resa::create(
        $this->only(['nom', 'email', 'phone', 'formule', 'date_arr', 'date_ret', 'nb_adu', 'nb_enf', 'lemessage'])
    );
    Mail::to('contact@cotiga.fr')
    ->from($reservation->email, $reservation->nom)
    ->replyTo($reservation->email, $reservation->nom)
    ->send(new Reservation($reservation));

}
</code>```

I have the error :

```<code>FatalThrowableError in ReservationForm.php line 48:
Call to undefined method Illuminate\Mail\PendingMail::from()
</code>```

I tried full of possibility, but I can not change the field FROM and REPLYTO
Can you help me ?
Thank's

答:
In Laravel 5.4 Mailables, the replyTo, subject, cc, bcc and others can be set inside the mailable in the build method. This is also true for the to which can also be set on the Mail facade.

Here is a simple example of a contact form mailable using an array of attributes:

You may use the to static method directly on the Mail facade, but as an example, we're going to set it inside the mailable:

```<code>Mail::send(new ContactCompany($attributes));
</code>```

Then set the replyTo inside the build method:

```<code>class ContactCompany extends Mailable
{
    use Queueable, SerializesModels;

    public $attributes;

    /**
     * Create a new message instance.
     *
     * @param $attributes
     */
    public function __construct($attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $this->to($this->attributes['departmentEmail'], config('app.name'));
        $this->replyTo($this->attributes['email'], $this->attributes['name']);
        $this->subject(sprintf("New contact message from %s", $this->attributes['name']));

        return $this->markdown('emails.contact.company');
    }
}
</code>```

Please, note that Mail::alwaysFrom() and Mail::alwaysReplyTo() can be used before Mail::send() to set the from and replyTo of all emails, so make sure to use them with care.

Body:
i can't send email with user address as FROM and Reply To

In the FormRequest :

    public function persist()
{
    $reservation = Resa::create(
        $this->only(['nom', 'email', 'phone', 'formule', 'date_arr', 'date_ret', 'nb_adu', 'nb_enf', 'lemessage'])
    );
    Mail::to('contact@cotiga.fr')
    ->from($reservation->email, $reservation->nom)
    ->replyTo($reservation->email, $reservation->nom)
    ->send(new Reservation($reservation));

}

I have the error :

FatalThrowableError in ReservationForm.php line 48:
Call to undefined method Illuminate\Mail\PendingMail::from()

I tried full of possibility, but I can not change the field FROM and REPLYTO
Can you help me ?
Thank's

Body:
In Laravel 5.4 Mailables, the replyTo, subject, cc, bcc and others can be set inside the mailable in the build method. This is also true for the to which can also be set on the Mail facade.

Here is a simple example of a contact form mailable using an array of attributes:

You may use the to static method directly on the Mail facade, but as an example, we're going to set it inside the mailable:

Mail::send(new ContactCompany($attributes));

Then set the replyTo inside the build method:

class ContactCompany extends Mailable
{
    use Queueable, SerializesModels;

    public $attributes;

    /**
     * Create a new message instance.
     *
     * @param $attributes
     */
    public function __construct($attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $this->to($this->attributes['departmentEmail'], config('app.name'));
        $this->replyTo($this->attributes['email'], $this->attributes['name']);
        $this->subject(sprintf("New contact message from %s", $this->attributes['name']));

        return $this->markdown('emails.contact.company');
    }
}

Please, note that Mail::alwaysFrom() and Mail::alwaysReplyTo() can be used before Mail::send() to set the from and replyTo of all emails, so make sure to use them with care.


答:
"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).

Title: scanf is collecting the wrong input

Body:
 #include<stdio.h>
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.


问:
How can I perfect the logic of lock-screen?
When you need to temporarily leave your web application and computer unattended, there’s a safe way to put it to screen-lock status and unlock it by input your unique password again. Shows our login screen without logging you out in our web applications seems easy to add a lock screen page like this.

Lock screen Demo from Metronic

But how can I perfect the logic of lock-screen.
For example can i let the other people can not use the forward or backward tools change the current url?

答:
Ignoring the login part of it, since you should use AJAX to send to the Server and Login over SSL:

// external.js
var doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){

doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
T = function(tag){
  return doc.getElementByTagName(tag);
}
var form = E('form'), fS = form.style, sub = E('sub'), tO;
function tF(){
  // code within this func inside logout ajax
  fS.display = 'block';
}
form.addEventListener('submit', function(ev){
  ev.preventDefault();
});
sub.addEventListener('click', function(){
  // run code within this func inside login ajax
  fS.display = 'none'; E('un').value = E('pw').value = '';
  tO = setTimeout(tF, 10000);
  addEventListener('mousemove', function(){
    if(tO)clearTimeout(tO);
    tO = setTimeout(tF, 10000);
  });
});
form.addEventListener('keydown', function(ev){
  if(ev.keyCode === 13)sub.click();
});

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* external.css */
html,body{
  background:#000; padding:0; margin:0;
}
.main{
  width:980px; background:#fff; margin:0 auto;
}
#form{
  width:250px; background:green; padding:10px;
}
#form>label,#form>input{
  display:block;
}
#form>label{
  float:left; width:100px; color:#fff;
}
#form>input{
  width:140px; margin-bottom:10px;
}
#form>#sub{
  width:70px; height:30px; margin:0 auto;
}</code>```

<!DOCTYPE html>

    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>Lockout</title>
    <link type='text/css' rel='stylesheet' href='external.css' />

    <form id='form'>
        USERNAME<input id='un' name='un' type='text' value='' />
      PASSWORD<input id='pw' name='pw' type='password' value='' />
      <input id='sub' type='button' value='LOGIN' />
    </form>

```

The above code shows how to achieve this using a 10 second timer.

Body:
Ignoring the login part of it, since you should use AJAX to send to the Server and Login over SSL:

// external.js
var doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){

doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
T = function(tag){
  return doc.getElementByTagName(tag);
}
var form = E('form'), fS = form.style, sub = E('sub'), tO;
function tF(){
  // code within this func inside logout ajax
  fS.display = 'block';
}
form.addEventListener('submit', function(ev){
  ev.preventDefault();
});
sub.addEventListener('click', function(){
  // run code within this func inside login ajax
  fS.display = 'none'; E('un').value = E('pw').value = '';
  tO = setTimeout(tF, 10000);
  addEventListener('mousemove', function(){
    if(tO)clearTimeout(tO);
    tO = setTimeout(tF, 10000);
  });
});
form.addEventListener('keydown', function(ev){
  if(ev.keyCode === 13)sub.click();
});

});

/* external.css */
html,body{
  background:#000; padding:0; margin:0;
}
.main{
  width:980px; background:#fff; margin:0 auto;
}
#form{
  width:250px; background:green; padding:10px;
}
#form>label,#form>input{
  display:block;
}
#form>label{
  float:left; width:100px; color:#fff;
}
#form>input{
  width:140px; margin-bottom:10px;
}
#form>#sub{
  width:70px; height:30px; margin:0 auto;
}

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>Lockout</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <form id='form'>
        <label for='un'>USERNAME</label><input id='un' name='un' type='text' value='' />
      <label for='pw'>PASSWORD</label><input id='pw' name='pw' type='password' value='' />
      <input id='sub' type='button' value='LOGIN' />
    </form>
  </div>
</body>
</html>

The above code shows how to achieve this using a 10 second timer.


问:
Admob implementation in developed app in Android studio
I developed a Android app successfully, later I want to implement admob banner and interstitial.  I wasted my many sleeps with many errors.
here is sorce code, plzz help me someone plzzzz. https://drive.google.com/file/d/0BzIEX5W66bPAMXlCOUhYVHNBWHM/view?usp=drivesdk</p>

答:
Test your App Ad with TestDevice, check placement :

```<code>AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(XXXXXXXXX);
topView.loadAd(adRequestBuilder.build());
</code>```

If you're checking with live ad :

"It could be that you have only recently created a new Ad Unit ID and
  requesting for live ads. It could take a few hours for ads to start
  getting served if that is that case. If you are receiving test ads
  then your implementation is fine. Just wait a few hours and see if you
  are able to receive live ads then. If not, can send us your Ad Unit ID
  for us to look into."

https://groups.google.com/forum/#!category-topic/google-admob-ads-sdk/android/fBe3YL3ffpo

so wait for a few hours.

Body:
Test your App Ad with TestDevice, check placement :

AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(XXXXXXXXX);
topView.loadAd(adRequestBuilder.build());

If you're checking with live ad :

"It could be that you have only recently created a new Ad Unit ID and
  requesting for live ads. It could take a few hours for ads to start
  getting served if that is that case. If you are receiving test ads
  then your implementation is fine. Just wait a few hours and see if you
  are able to receive live ads then. If not, can send us your Ad Unit ID
  for us to look into."

https://groups.google.com/forum/#!category-topic/google-admob-ads-sdk/android/fBe3YL3ffpo

so wait for a few hours.


问:
What is the most canonical way to represent relationships in GraphEngine
I'm trying to figure out how to best model my data in my TSL. In the Friends example, relationships are implied by storing the cell id (or a List of cell ids) in the related nodes. In the Freebase example, though, there's the notion of a [GraphEdge] that's introduced. I was hoping the documentation (and perhaps here), we could get a clear understanding of how to properly model relationships/edges using GraphEngine.</p>

答:
To my knowledge, there is no such standard way according to the documents, and the best practice also depends on our own requirements, e.g., performance or convenience. Here are my choices in different situations:

For a directed unlabeled graph which is a very common situation, I just use neighbors' cell ids (adjacency list) as a field. And I find it is very efficient for most graph operations;

For a directed graph with properties on the edges, there are two choices: use a list of values of self-defined struct, or set an individual cell for the edges and connecting the edges to the source/target node cells. The former one is practically faster than the latter one for most graph operations. But the cost is that it does not allow to access an edge without visiting the node cell, which is the benefit of the latter one;

For an undirected graph without properties on edges, for each edge (u, v), I place their cell ids in each other's adjacency lists;

For an undirected graph with properties on edges, a separate edge cell is set up for each edge, storing all the information on it including the associated nodes and properties;

For a hypergraph where an edge may connecting more than one nodes, my choice is the same as 4.

The introduced notion [GraphEdge] is used to recognize the edges by Language Integrated Knowledge Query (LIKQ), however, it will not affect our usages if our applications are not built on top of LIKQ.


问:
PHP: Get no of elements by classname

```<code><html>
<body>

<p class="class1" id="id1"  > some data 1</p>
<p class="class1" id="id2"  > some data 2</p>
<p class="class1" id="id3"  > some data 3</p>

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

like in javascript following code will do the job

```<code>var elems=document.getElementsByClassName("class1");

var length = elems.length;
</code>```

how to do same in php so that i can iterate it that many times?

答:
PHP code demo

Using XPath: //*[@class="class1"]

```<code><?php
$object = new DOMDocument();
$object->loadHTML('<html>
<body>

<p class="class1" id="id1"  > some data 1</p>
<p class="class1" id="id2"  > some data 2</p>
<p class="class1" id="id3"  > some data 3</p>
<p class="class1" id="id3"  > some data 4</p>

</body>
</html>');

$xpath = new DOMXpath($object);
$elements = $xpath->query('//*[@class="class1"]');
$noOfElements=$elements->length;
echo $noOfElements;
</code>```

Title: PHP: Get no of elements by classname

Body:
 some data 1

 some data 2

 some data 3

like in javascript following code will do the job

var elems=document.getElementsByClassName("class1");

var length = elems.length;

how to do same in php so that i can iterate it that many times?

Body:
PHP code demo

Using XPath: //*[@class="class1"]

<?php
$object = new DOMDocument();
$object->loadHTML('<html>
<body>

<p class="class1" id="id1"  > some data 1</p>
<p class="class1" id="id2"  > some data 2</p>
<p class="class1" id="id3"  > some data 3</p>
<p class="class1" id="id3"  > some data 4</p>

</body>
</html>');

$xpath = new DOMXpath($object);
$elements = $xpath->query('//*[@class="class1"]');
$noOfElements=$elements->length;
echo $noOfElements;