问:
Making an Observable from a callback
I have an auth guard that needs an asynchronous response true/false when the site is visited and the user is already logged in.

I'm using Firebase's onAuthStateChanged (link to docs) and it uses a callback function.  How can I turn my isLoggedIn() method into something that can return Observable<boolean>?

Typscript:

```<code>get isLoggedIn(): Observable<boolean> {

    // want something like this:
    return Observable.fromCallback(firebase.auth().onAuthStateChanged).map(user => !!user);

    // this returns () => boolean, but I need a promise or observable
    return firebase
      .auth()
      .onAuthStateChanged((user) => {
        return !!user;
      });

}
</code>```

答:
You can do it like this.</p>

```<code>get isLoggedIn(): Observable<boolean> {

  // want something like this:
  return Observable.create(
    observer => firebase
        .auth()
        .onAuthStateChanged((user) => {
          observer.next(!!user)
        });
    );
}
</code>```

Title: Making an Observable from a callback

Body:
I have an auth guard that needs an asynchronous response true/false when the site is visited and the user is already logged in.

I'm using Firebase's onAuthStateChanged (link to docs) and it uses a callback function.  How can I turn my isLoggedIn() method into something that can return Observable<boolean>?

Typscript:

get isLoggedIn(): Observable<boolean> {

    // want something like this:
    return Observable.fromCallback(firebase.auth().onAuthStateChanged).map(user => !!user);

    // this returns () => boolean, but I need a promise or observable
    return firebase
      .auth()
      .onAuthStateChanged((user) => {
        return !!user;
      });

}

Body:
You can do it like this.

get isLoggedIn(): Observable<boolean> {

  // want something like this:
  return Observable.create(
    observer => firebase
        .auth()
        .onAuthStateChanged((user) => {
          observer.next(!!user)
        });
    );
}


来源: stackexchange

问:
Show function source code from repl
I would like to view the definition of a method in REPL. I follow this link (https://github.com/JuliaLang/julia/issues/2625) but it doesn't work:

```<code>julia> f(x) = x^2
f (generic function with 1 method)

julia> expand(f)
f (generic function with 1 method)

julia> methods(f)
# 1 method for generic function "f":
f(x) at REPL[155]:1

julia> implementation(f,1)
ERROR: UndefVarError: implementation not defined
 in eval_user_input(::Any, ::Base.REPL.REPLBackend) at ./REPL.jl:64
 in macro expansion at ./REPL.jl:95 [inlined]
 in (::Base.REPL.##3#4{Base.REPL.REPLBackend})() at ./event.jl:68
</code>```

It seems that the method implementation doesn't exist.

答:
I believe a direct way isn't implemented yet.

Here's one of the creators saying so 6 months ago - doesn't seem to have been made, as there are a few duplicate issues of this.

https://stackoverflow.com/a/37662987/7754070

ContentLicense: CC BY-SA 3.0

Title: Show function source code from repl

Body:
I would like to view the definition of a method in REPL. I follow this link (https://github.com/JuliaLang/julia/issues/2625) but it doesn't work:

julia> f(x) = x^2
f (generic function with 1 method)

julia> expand(f)
f (generic function with 1 method)

julia> methods(f)
# 1 method for generic function "f":
f(x) at REPL[155]:1

julia> implementation(f,1)
ERROR: UndefVarError: implementation not defined
 in eval_user_input(::Any, ::Base.REPL.REPLBackend) at ./REPL.jl:64
 in macro expansion at ./REPL.jl:95 [inlined]
 in (::Base.REPL.##3#4{Base.REPL.REPLBackend})() at ./event.jl:68

It seems that the method implementation doesn't exist.


问:
How can I make a random set generator with equal possibility to generate uniform sets and non-uniform sets?
So let's say I have a set of items:

```<code>['a', 'b', 'c', 'd', 'e']
</code>```

and I want to generate a random set (order does not matter) from those choices:

```<code>['a', 'e', 'd', 'c']
</code>```

which is child's play, but instead of it being unlikely to generate a uniform result:

```<code>['c', 'c', 'c', 'c']
</code>```

compared to something less uniform like:

```<code>['a', 'b', 'e', 'd']
</code>```

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

答:
Your original question seems to be stated incorrectly, which is why you are getting so many incorrect responses. In fact, the simple approach will give you the result that you want. You should do this by choosing a random value from your original set, like this:

function randomSet(set, size) {
  let result = []
  for (let i = 0; i < size; i++) {
    // get a random index from the original set
    let index = Math.floor(Math.random() * set.length)
    result.push(set[index])
  }
  return result
}

console.log(randomSet(['a', 'b', 'c'], 3))

// These are all equally likely:
// ['a','a','a']
// ['a','b','b']
// ['a','b','c']
// ['c','b','a']
// ['a','b','a']
// ['a','a','b']
// ['b','a','a']
// ['b','a','b']
// ['b','b','b']
// etc.```
</div>
</div>
</p>

<p>Alternatively, it's possible that you are misunderstanding the definition of a set. Many of your examples like <code>['c', 'c', 'c', 'c', 'b', 'a']</code> are not sets, because they contain repeat characters. Proper sets cannot contain repeat characters and the order of their contents does not matter. If you want to generate a random <em>set</em> from your initial set (in other words, generate a subset), you can do that by picking a size less than or equal to your initial set size, and filling a new set of that size with random elements from the initial set:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function randomSet(set) {
  let result = []
  let size = Math.floor(Math.random() * set.length)
  while(result.length !== size) {
    // get a random index from the original set
    let index = Math.floor(Math.random() * set.length)
    // in this case, we construct the new set simply by removing items from the original set
    result.splice(index, 1)
  }
  return result
}

console.log(randomSet(['a', 'b', 'c']))

// These are all equally likely:
// ['a','b','c']
// ['a','b']
// ['b','c']
// ['a','c']
// ['a']
// ['b']
// ['c']
// no other sets are possible</code>```

Body:
So let's say I have a set of items:

['a', 'b', 'c', 'd', 'e']

and I want to generate a random set (order does not matter) from those choices:

['a', 'e', 'd', 'c']

which is child's play, but instead of it being unlikely to generate a uniform result:

['c', 'c', 'c', 'c']

compared to something less uniform like:

['a', 'b', 'e', 'd']

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

Body:
Your original question seems to be stated incorrectly, which is why you are getting so many incorrect responses. In fact, the simple approach will give you the result that you want. You should do this by choosing a random value from your original set, like this:

function randomSet(set, size) {
  let result = []
  for (let i = 0; i < size; i++) {
    // get a random index from the original set
    let index = Math.floor(Math.random() * set.length)
    result.push(set[index])
  }
  return result
}

console.log(randomSet(['a', 'b', 'c'], 3))

// These are all equally likely:
// ['a','a','a']
// ['a','b','b']
// ['a','b','c']
// ['c','b','a']
// ['a','b','a']
// ['a','a','b']
// ['b','a','a']
// ['b','a','b']
// ['b','b','b']
// etc.

Alternatively, it's possible that you are misunderstanding the definition of a set. Many of your examples like ['c', 'c', 'c', 'c', 'b', 'a'] are not sets, because they contain repeat characters. Proper sets cannot contain repeat characters and the order of their contents does not matter. If you want to generate a random set from your initial set (in other words, generate a subset), you can do that by picking a size less than or equal to your initial set size, and filling a new set of that size with random elements from the initial set:

function randomSet(set) {
  let result = []
  let size = Math.floor(Math.random() * set.length)
  while(result.length !== size) {
    // get a random index from the original set
    let index = Math.floor(Math.random() * set.length)
    // in this case, we construct the new set simply by removing items from the original set
    result.splice(index, 1)
  }
  return result
}

console.log(randomSet(['a', 'b', 'c']))

// These are all equally likely:
// ['a','b','c']
// ['a','b']
// ['b','c']
// ['a','c']
// ['a']
// ['b']
// ['c']
// no other sets are possible


问:
Only text values being posted to php file but not files
I have the following code for an HTML form:

```<code><form id="idForm" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <input type="submit" name="submit" value="Submit" />
</form>
</code>```

and the following Javascript code on the same page where the form is located. Also, this code is written below the form code:

```<code>$("#idForm").submit(function() {
    alert("hi");
    var url = "submit.php";

    $.ajax({
        type: "POST",
        url: url,
        data: $("#idForm").serialize(),
        success: function(data) {
            alert(data);
        }
    });

    return false;
});
</code>```

And here is the PHP code that I'm using to see if the form data is being posted:

```<code>if (isset($_FILES['image'])) {
    $image = $_FILES['image'];
    echo $image;
}

if (isset($_POST['first'])) {
    $name = $_POST['first'];
    echo $name;
}
</code>```

With the above code, it seems as though the attached file is not being sent to the PHP file. Only the values are being sent, since they are echoed when I inspected the element using Google Chrome dev tool.

I want to be able to post both text value and files to the PHP file for processing.

Why am I getting this problem? How do I fix this?

Also, as part of the solution, I want to prevent the page from being refreshed when the submit button is clicked.

Thanks much!

答:
Unfortunately input[type='file'] cannot be submitted by .serialize(), you have to manipulate by formData.
You will find a very good formData example in here</p>

Body:
I have the following code for an HTML form:

<form id="idForm" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

and the following Javascript code on the same page where the form is located. Also, this code is written below the form code:

$("#idForm").submit(function() {
    alert("hi");
    var url = "submit.php";

    $.ajax({
        type: "POST",
        url: url,
        data: $("#idForm").serialize(),
        success: function(data) {
            alert(data);
        }
    });

    return false;
});

And here is the PHP code that I'm using to see if the form data is being posted:

if (isset($_FILES['image'])) {
    $image = $_FILES['image'];
    echo $image;
}

if (isset($_POST['first'])) {
    $name = $_POST['first'];
    echo $name;
}

With the above code, it seems as though the attached file is not being sent to the PHP file. Only the values are being sent, since they are echoed when I inspected the element using Google Chrome dev tool.

I want to be able to post both text value and files to the PHP file for processing.

Why am I getting this problem? How do I fix this?

Also, as part of the solution, I want to prevent the page from being refreshed when the submit button is clicked.

Thanks much!


问:
Yii2 Kartik TimePicker -- can't use in more than one modal window
I have a page that launches modal windows that include two TimePicker widgets. When opening the first modal, everything works. It can be reopened as well. However, when opening another modal, I get a console error:

```<code>Uncaught TypeError: Cannot read property 'apply' of undefined
at HTMLInputElement.eval (eval at globalEval (jquery.js:343), <anonymous>:851:29)
at Function.each (jquery.js:365)
at jQuery.fn.init.each (jquery.js:137)
at jQuery.fn.init.$.fn.timepicker (eval at globalEval (jquery.js:343), <anonymous>:841:21)
at HTMLDocument.eval (eval at globalEval (jquery.js:343), <anonymous>:3:107)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at jQuery.fn.init.jQuery.fn.ready (jquery.js:3496)
at eval (eval at globalEval (jquery.js:343), <anonymous>:1:18)
at eval (<anonymous>)
</code>```

Here is the code causing the error:

```<code>//TIMEPICKER PLUGIN DEFINITION
$.fn.timepicker = function (option) {
    var args = Array.apply(null, arguments);
    args.shift();
    return this.each(function () {
        var $this = $(this),
            data = $this.data('timepicker'),
            options = typeof option === 'object' && option;

        if (!data) {
            $this.data('timepicker', (data = new Timepicker(this, $.extend({}, $.fn.timepicker.defaults, options, $(this).data()))));
        }

        if (typeof option === 'string') {
            data[option].apply(data, args); // This is the line that causes problems
        }
    });
};
</code>```

Here is the PHP code for one of the widgets:

```<code><?= $form->field($model, 'TimeEntryStartTime',[
                'showLabels'=>false
                ])->widget(TimePicker::classname(),[
                    'options' => ['placeholder' => 'Enter time...'],
                ]); ?>
</code>```

Here is the javascript that launches the modals (similar for each):

```<code>// Modal view for Monday
$('#modalButtonMonday').click(function(){
// get the click of the create button
    $('#modalMonday').modal('show')
        .find('#modalContentMonday')
        .load($(this).attr('value'));
});
$('#modalMonday').on('hidden.bs.modal', function (e) {
  // reload page when modal closed
  location.reload(true);
});
</code>```

答:
try setting different names in the widget with

'name'=>timepickerName;

or in the 'option' html array insert an ids or class for each one, ex. 'id'=>'timepickerId'

and write another .fn.  with the correspondent name or id.

Body:
I have a page that launches modal windows that include two TimePicker widgets. When opening the first modal, everything works. It can be reopened as well. However, when opening another modal, I get a console error:

Uncaught TypeError: Cannot read property 'apply' of undefined
at HTMLInputElement.eval (eval at globalEval (jquery.js:343), <anonymous>:851:29)
at Function.each (jquery.js:365)
at jQuery.fn.init.each (jquery.js:137)
at jQuery.fn.init.$.fn.timepicker (eval at globalEval (jquery.js:343), <anonymous>:841:21)
at HTMLDocument.eval (eval at globalEval (jquery.js:343), <anonymous>:3:107)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at jQuery.fn.init.jQuery.fn.ready (jquery.js:3496)
at eval (eval at globalEval (jquery.js:343), <anonymous>:1:18)
at eval (<anonymous>)

Here is the code causing the error:

//TIMEPICKER PLUGIN DEFINITION
$.fn.timepicker = function (option) {
    var args = Array.apply(null, arguments);
    args.shift();
    return this.each(function () {
        var $this = $(this),
            data = $this.data('timepicker'),
            options = typeof option === 'object' && option;

        if (!data) {
            $this.data('timepicker', (data = new Timepicker(this, $.extend({}, $.fn.timepicker.defaults, options, $(this).data()))));
        }

        if (typeof option === 'string') {
            data[option].apply(data, args); // This is the line that causes problems
        }
    });
};

Here is the PHP code for one of the widgets:

<?= $form->field($model, 'TimeEntryStartTime',[
                'showLabels'=>false
                ])->widget(TimePicker::classname(),[
                    'options' => ['placeholder' => 'Enter time...'],
                ]); ?>

Here is the javascript that launches the modals (similar for each):

// Modal view for Monday
$('#modalButtonMonday').click(function(){
// get the click of the create button
    $('#modalMonday').modal('show')
        .find('#modalContentMonday')
        .load($(this).attr('value'));
});
$('#modalMonday').on('hidden.bs.modal', function (e) {
  // reload page when modal closed
  location.reload(true);
});


问:
Mutations queries graphql-java
I'm new to graphql specially graphql-java I have done queries with arguments successfully but when I try to send a mutation query the schema does not even execute the datafetcher is like not even been evaluated by the server. this is some snippets of my code.

```<code>DataFetcher nodeCreateDataFetcher = new DataFetcher(){
    public Object get(DataFetchingEnvironment environment) {

        Map source = (Map) environment.getSource();
        String alias = (String) source.get("alias");

        System.out.println(alias);
        //This statement adds a new node with a name on an alias class field
        Node node = getNodes.addNode(alias);
        return node;
    }
};

// Creates an InputobjectType
public GraphQLInputObjectType createNodeInputType(){
    return  newInputObject()
            .name("nodeInput")
            .field(newInputObjectField()
                    .name("alias")
                    .type(GraphQLString))
            .build();
}

//Creates the Mutation schema
public GraphQLObjectType createMutation(){
    return newObject()
            .name("Mutation")
            .field(newFieldDefinition()
                .name("create")
                .type(createNodeType())
                .argument(newArgument()
                        .name("node")
                        .type(createNodeInputType())
                        .defaultValue("{alias: \"node4\"}"))
                .dataFetcher(nodeCreateDataFetcher))
            .build();
}
</code>```

So I go to postman and write something like this {create(node:{alias:"anything"})} this seems to be wrongs I see people using variable most of the time in graphql queries but I'm trying to do the simples mutation query and then start from there. I would really appreciate you help.

答: I just overlooked one important part of the specification actually I had to write mutation before the query like mutation {create(node:{alias:"anything"})}

Title: Mutations queries graphql-java

Body:
I'm new to graphql specially graphql-java I have done queries with arguments successfully but when I try to send a mutation query the schema does not even execute the datafetcher is like not even been evaluated by the server. this is some snippets of my code.

DataFetcher nodeCreateDataFetcher = new DataFetcher(){
    public Object get(DataFetchingEnvironment environment) {

        Map source = (Map) environment.getSource();
        String alias = (String) source.get("alias");

        System.out.println(alias);
        //This statement adds a new node with a name on an alias class field
        Node node = getNodes.addNode(alias);
        return node;
    }
};

// Creates an InputobjectType
public GraphQLInputObjectType createNodeInputType(){
    return  newInputObject()
            .name("nodeInput")
            .field(newInputObjectField()
                    .name("alias")
                    .type(GraphQLString))
            .build();
}

//Creates the Mutation schema
public GraphQLObjectType createMutation(){
    return newObject()
            .name("Mutation")
            .field(newFieldDefinition()
                .name("create")
                .type(createNodeType())
                .argument(newArgument()
                        .name("node")
                        .type(createNodeInputType())
                        .defaultValue("{alias: \"node4\"}"))
                .dataFetcher(nodeCreateDataFetcher))
            .build();
}

So I go to postman and write something like this {create(node:{alias:"anything"})} this seems to be wrongs I see people using variable most of the time in graphql queries but I'm trying to do the simples mutation query and then start from there. I would really appreciate you help.


问:
Installing pyinstaller via pip leads to "failed to create process"
Does anyone know why pyinstaller immediately fails after installed via pip via anaconda 32bit?

I installed pyinstaller via pip install pyinstaller through the anaconda command prompt on Windows 64 bit using 32 bit anaconda (because I want to create 32 bit executables)

Yes I read pyinstaller --version failed to create a process and pip/easy_install failure: failed to create process and How to install pyinstaller using pip

I did not rename any files I installed anaconda 15 mins ago, pycharm 10 mins ago, and pyinstaller 5 mins ago. I uninstalled pyinstaller via pup uninstall and reinstalled in the anaconda scripts folder, this did nothing.

Any insight anyone? #windowsfrustrations
Path
C:\Users\me\Anaconda\Lib\site-packages>PyInstaller

答:
python -m pip install pip worked for me.

With Anaconda version of Python 3.5.2 and 3.6.0(Upgraded for this error, but the error appears to be the same with both versions), I had encountered the same error message with command pip install pip, or pip install whatever/ conda install whatever.

I had both Python 2.7 and 3.5, but pip install --upgrade pip had been working every day, until a few days ago.


问:
interpret this algorithm of discrete mathematics and its applications, Kenneth H. Rosen
Q. Describe an algorithm that inserts an integer x in the appropriate position into the list a_1, a_2, ... ,a_n of integers that are in increasing order.

A.

```<code>procedure insert(x,a_1,a_2,...,a_n :integers)
{the list is in order: a_1<=a_2<=...<=a_n}
a_(n+1) := x+1
i :=1
while x>a_i
i :=i+1
for j:=0 to n-i
a_(n-j+1) := a_(n-j)
a_i=x
{x has been inserted into correct position}
</code>```

my question. why a_(n+1) := x+1 ? and if the initial value i=n then j=0 to -1 ?
do i exclude j=-1?
sorry for bad speaking please interpret this algorithm

答:
why a_(n+1) := x+1 ?

This is sentinel node  approach.

Using this stop-element, one can use the same method for inserting x into any position of the list. Otherwise one have to look for whether list is finished and append x at the end with special piece of code

if the initial value i=n then j=0 to -1 ?

It is implied that operator for for j:=0 to -1 is not executed (some languages have special kinds of for loop for reverse direction like for ..downto in Pascal or step argument in some others)

Body:
Q. Describe an algorithm that inserts an integer x in the appropriate position into the list a_1, a_2, ... ,a_n of integers that are in increasing order.

A.

procedure insert(x,a_1,a_2,...,a_n :integers)
{the list is in order: a_1<=a_2<=...<=a_n}
a_(n+1) := x+1
i :=1
while x>a_i
i :=i+1
for j:=0 to n-i
a_(n-j+1) := a_(n-j)
a_i=x
{x has been inserted into correct position}

my question. why a_(n+1) := x+1 ? and if the initial value i=n then j=0 to -1 ?
do i exclude j=-1?
sorry for bad speaking please interpret this algorithm


问:
File size increase for pngquant output when using PIL
If I compress and image with pngquant, and then read and write out with PIL, I see file size increase significantly (sometimes by up to 2x). Anyone have any tips here? I suspect it may have to do with some PIL flags, but not familiar enough with it.</p>

答:
Unless you modify anything RGBA or save with different settings, reading and writing PNG has almost no affect on file size regardless of the library or application you use.

Proof of concept using pngquant generated image and PIL:

```<code>$ wget https://pngquant.org/Ducati_side_shadow-fs8.png
$ python
>>> from PIL import Image
>>> im = Image.open("Ducati_side_shadow-fs8.png")
>>> im.rotate(180).save("output.png")
$ stat -c "%s %n" *.png
23405 Ducati_side_shadow-fs8.png
23362 output.png
</code>```

In example above, output.png is even 43 bytes less than the original. We have rotated it upside down but didn't touch colors or alpha.

Body:
Unless you modify anything RGBA or save with different settings, reading and writing PNG has almost no affect on file size regardless of the library or application you use.

Proof of concept using pngquant generated image and PIL:

$ wget https://pngquant.org/Ducati_side_shadow-fs8.png
$ python
>>> from PIL import Image
>>> im = Image.open("Ducati_side_shadow-fs8.png")
>>> im.rotate(180).save("output.png")
$ stat -c "%s %n" *.png
23405 Ducati_side_shadow-fs8.png
23362 output.png

In example above, output.png is even 43 bytes less than the original. We have rotated it upside down but didn't touch colors or alpha.


问:
CognitiveService Face - AddPersonFaceAsync requires GUID (instead of people's name) as second param?
I'm trying out Microsoft Cognitive Services Face API now, looking at here as reference: https://www.microsoft.com/cognitive-services/en-us/face-api/documentation/face-api-how-to-topics/howtoidentifyfacesinimage

Now, I don't understand why the second parameter for AddPersonFaceAsync is taking in GUID. My logic tells me that you would want to add the groupId of the person, and the name of the person (the same name that is used when calling CreatePersonAsync). But the function requires that I pass in a GUID?

What GUID do I use here? Do I just generate anything? How is that GUID is going to be associated with the person's name?

答:
When you create a person that person is assigned an ID (a GUID) by the API on the server side, and that ID is returned from the CreatePerson method.  You can see this in step 2.1 in the returned friend1 variable.  In future calls interacting with that person you pass in the ID assigned to that person.

The name of the person is just metadata display name, not used to identify the person.  What if you had 2 friends with the same name?

It may help to look at the raw REST API to better understand the input and output of the APIs.  See https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523c.


问:
Conditional Display on Item Value
I have successfully created a form consisting of a couple of radio buttons and a drop-down select menu. I am trying to get the select menu to be visible only when a specific radio button is selected.

For my situation, I would like the select menu to only be visible when the No radio button is selected.

The select menu is set as a child LOV item for the radio buttons, so when the radio buttons' value is changed the select menu's values are updated. However, what I have discovered is the conditional display conditions are not re-evaluated, which prevents the select menu being hidden or shown as the radio buttons are changed.

My initial solution was to set the radio button to redirect and set the value on change, but this ended up conflicting with logic elsewhere in my actual form (a lot more complicated than the example given).

The issue is definitely that cascading LOV parent items are not re-evaluating their child elements' conditional display options, so I was wondering if anyone has found a way to solve this?

答:
Create a dynamic action on change of the radio group.

Set the client side condition for the item to = 'N', there should be a declarative way to do this, but the JavaScript expression would be

```<code>$v('P1_RADIO') === 'N'
</code>```

Add a true condition to Hide the select list item, and create an opposite action to Show it.

This implies >= APEX 4.x

Title: Conditional Display on Item Value

Body:
Create a dynamic action on change of the radio group.

Set the client side condition for the item to = 'N', there should be a declarative way to do this, but the JavaScript expression would be

$v('P1_RADIO') === 'N'

Add a true condition to Hide the select list item, and create an opposite action to Show it.

This implies >= APEX 4.x


问:
App Transport Security has blocked a cleartext HTTP resource

I am using Socket.IO library in swift and I keep getting this error:

App Transport Security has blocked a cleartext HTTP (http://) resource
  load since it is insecure. Temporary exceptions can be configured via
  your app's Info.plist file.

when I am trying to send an http request. I added the keys to plist according to the official apple documentation, but it did not help.

答:
I'm working in xCode 8.2. It's a little different, but editing the PLIST file you need to add this two Items in the App Transport Security Settings Line... :

Allow Arbitrary Loads and Allow Arbitrary Loads in Web Content... and give them both the key YES.

It worked for me, hope this work for you and sorry for my English.


问:
How to obtain a more accurate value for RPM
I am trying to build a rev counter using a Hall effect sensor and an Arduino Uno. I'm using Arduino software and I have wrote the following code:

#include <LiquidCrystal.h>

int sensorPin = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long previousmicros = 0;
long interval = 500000;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

void setup()
{
  // setup serial - diagnostics - port
  Serial.begin(115200);
  // setup pins
  pinMode(sensorPin, INPUT);
  // setup interrupt
  attachInterrupt(0, RPM, RISING);
}

void RPM()
{
  rpmcount++;
}

void loop()
{
  unsigned long currentmicros = micros();
  int sensorValue = digitalRead(sensorPin);        // sensor value is read
  if (currentmicros - previousmicros > interval)
  {
    previousmicros = currentmicros;

    detachInterrupt(0);
    revs=10.0/rpmcount;
    rpm =600.0/revs;
    Serial.print("rpmcount : ");
    Serial.print(rpmcount);
    Serial.print("  rpm : ");
    Serial.println(rpm);
    lcd.clear();
    lcd.begin(16, 2);
    lcd.print("RPM = ");
    lcd.setCursor(6,0);
    lcd.print(rpm,0);
    rpmcount=0;
    attachInterrupt(0, RPM, RISING);
  }
}
```

This works and measures the RPM correctly however the value is always a factor of 60. How can I change this so that it will measure the RPM more accurately, to say +-5 RPM? I tried playing about with my revs and rpm formulas but had little success.

答:
In the ISR instead of increment a count, compute the amount of time elapsed since the last ISR fire.

```<code>unsigned long someArray[2] = {0,0};
unsigned char rpmindex = 0;

void RPM_isr()
{
   rpmindex ^= 1;
   someArray[rpmindex] = micros();
}

// And then in the main body

{
   // Disable interrupts
   // Copy someArray to a localArray
   // reEnable interrupts
   // Compute the interval between ISR fires
   unsigned long interval = abs(localArray[0] - localArray[1]);
   // Compute RPM
   unsigned int rpm = (60*1000000)/interval;
}
</code>```

Pseudo code interpreted at your own risk.

Edit: For bad math on RPM computation.

Body:
I am trying to build a rev counter using a Hall effect sensor and an Arduino Uno. I'm using Arduino software and I have wrote the following code:

#include <LiquidCrystal.h>

int sensorPin = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long previousmicros = 0;
long interval = 500000;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

void setup()
{
  // setup serial - diagnostics - port
  Serial.begin(115200);
  // setup pins
  pinMode(sensorPin, INPUT);
  // setup interrupt
  attachInterrupt(0, RPM, RISING);
}

void RPM()
{
  rpmcount++;
}

void loop()
{
  unsigned long currentmicros = micros();
  int sensorValue = digitalRead(sensorPin);        // sensor value is read
  if (currentmicros - previousmicros > interval)
  {
    previousmicros = currentmicros;

    detachInterrupt(0);
    revs=10.0/rpmcount;
    rpm =600.0/revs;
    Serial.print("rpmcount : ");
    Serial.print(rpmcount);
    Serial.print("  rpm : ");
    Serial.println(rpm);
    lcd.clear();
    lcd.begin(16, 2);
    lcd.print("RPM = ");
    lcd.setCursor(6,0);
    lcd.print(rpm,0);
    rpmcount=0;
    attachInterrupt(0, RPM, RISING);
  }
}

This works and measures the RPM correctly however the value is always a factor of 60. How can I change this so that it will measure the RPM more accurately, to say +-5 RPM? I tried playing about with my revs and rpm formulas but had little success.

Body:
In the ISR instead of increment a count, compute the amount of time elapsed since the last ISR fire.

unsigned long someArray[2] = {0,0};
unsigned char rpmindex = 0;

void RPM_isr()
{
   rpmindex ^= 1;
   someArray[rpmindex] = micros();
}

// And then in the main body

{
   // Disable interrupts
   // Copy someArray to a localArray
   // reEnable interrupts
   // Compute the interval between ISR fires
   unsigned long interval = abs(localArray[0] - localArray[1]);
   // Compute RPM
   unsigned int rpm = (60*1000000)/interval;
}

Pseudo code interpreted at your own risk.

Edit: For bad math on RPM computation.


问:
Programmatically go to a site and click a button using Javascript?
I want to create a link, and this link will automatically refer to google.com and click their HTML button

Google Search Button code:

```<code><input value="Google Search" aria-label="Google Search" name="btnK" type="submit" jsaction="sf.chk">
</code>```

How can such be done in a link using javascript?

答:
Here's something in JQuery, from here:</p>

```<code><script type="text/javascript">
    $(document).ready(function() {
        $(function() {
            $("button[aria-label='Google Search']").click();
        });
    });
</script>
</code>```

Body:
I want to create a link, and this link will automatically refer to google.com and click their HTML button

Google Search Button code:

<input value="Google Search" aria-label="Google Search" name="btnK" type="submit" jsaction="sf.chk">

How can such be done in a link using javascript?

Body:
Here's something in JQuery, from here:

<script type="text/javascript">
    $(document).ready(function() {
        $(function() {
            $("button[aria-label='Google Search']").click();
        });
    });
</script>


问:
How to call kartik gridview REFRESH function inside ajax success function
I want to refresh the kartik gridview in an ajax success function so that I can see the changes I made after a  successful UPDATE, but I don't know how to call the refresh function in kartik gridview in order to reflect the updates.

```<code> $.ajax({
         type: 'POST',
         url:'',
         dataType: 'html',
         data: {key:keys},
              success: function(data){
                       $.pjax.reload({container:'#pjax_id'});
           },
         });
</code>```

Below is the Kartik Gridview

```<code> echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' =>  $gridColumns,
    'containerOptions'=>['style'=>'overflow: auto'],
    'headerRowOptions'=>['class'=>'kartik-sheet-style'],
    'filterRowOptions'=>['class'=>'kartik-sheet-style'],
    'id' =>'dempcc_grid_id',
    **'pjax'=>true, // pjax is set to always true for this demo
    'pjaxSettings' =>[
        'neverTimeout'=>true,
        'options'=>[
                'id'=>'pjax_id',
            ]
        ],**
    'toolbar'=> [
     ['content'=>
       Html::a('<i class="glyphicon glyphicon-repeat"></i> Refresh', [''], ['data-pjax'=>1, 'class'=>'btn btn-default', 'title'=>'Reset Grid','id'=>'refresh'])

     ],
        '{export}',
        '{toggleData}',
        ],
    'panel'=>[
        'type'=>GridView::TYPE_PRIMARY,
        'heading'=>'REMITTANCE - DEMPCC',
    ],
      'persistResize'=>false,
]);
</code>```

答:
```<code><?php \yii\widgets\Pjax::begin(); ?>
<?= GridView::widget([
// ... configuration here
]);
<?php \yii\widgets\Pjax::end(); ?>
</code>```

And update:
$.pjax.reload({container:'#idofyourpjaxwidget'});

http://www.yiiframework.com/wiki/655/how-to-use-gridview-with-ajax/

Body:
I want to refresh the kartik gridview in an ajax success function so that I can see the changes I made after a  successful UPDATE, but I don't know how to call the refresh function in kartik gridview in order to reflect the updates.

 $.ajax({
         type: 'POST',
         url:'',
         dataType: 'html',
         data: {key:keys},
              success: function(data){
                       $.pjax.reload({container:'#pjax_id'});
           },
         });

Below is the Kartik Gridview

 echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' =>  $gridColumns,
    'containerOptions'=>['style'=>'overflow: auto'],
    'headerRowOptions'=>['class'=>'kartik-sheet-style'],
    'filterRowOptions'=>['class'=>'kartik-sheet-style'],
    'id' =>'dempcc_grid_id',
    **'pjax'=>true, // pjax is set to always true for this demo
    'pjaxSettings' =>[
        'neverTimeout'=>true,
        'options'=>[
                'id'=>'pjax_id',
            ]
        ],**
    'toolbar'=> [
     ['content'=>
       Html::a(' Refresh', [''], ['data-pjax'=>1, 'class'=>'btn btn-default', 'title'=>'Reset Grid','id'=>'refresh'])

     ],
        '{export}',
        '{toggleData}',
        ],
    'panel'=>[
        'type'=>GridView::TYPE_PRIMARY,
        'heading'=>'REMITTANCE - DEMPCC',
    ],
      'persistResize'=>false,
]);

Body:
<?php \yii\widgets\Pjax::begin(); ?>
<?= GridView::widget([
// ... configuration here
]);
<?php \yii\widgets\Pjax::end(); ?>

And update:
$.pjax.reload({container:'#idofyourpjaxwidget'});

http://www.yiiframework.com/wiki/655/how-to-use-gridview-with-ajax/


问:
Service fabric deploy failure in secure cluster
I got following error when I try to use VSTS to deploy application to Azure secure cluster

An error occurred attempting to import the certificate. Ensure that your service endpoint is configured properly with a correct certificate value and, if the certificate is password-protected, a valid password. Error message: Exception calling "Import" with "3" argument(s): "Cannot find the requested object.

I copied certificate base64 string and password to Services Endpoint config. Should I do other option to let it work?

答: Found the problem, the url in service endpoint should use https</p>


问:
How to add placeholder to joomla contact form
I am designing a template, however, I want my contact form to have placeholders. I tried overriding the contact component form file components/com_contact/views/contact/tmpl/default_form.php but it seems to use joomla JForm or something that doesn't give me the ability to add placeholder directly.

```<code>$this->form->getInput('contact_name');
$this->form->getInput('contact_email');
...
</code>```

How can I add placeholde to the contacts? I definitely don't want to replace those pieces of code with naive html code. Neither I want to add a javascript code to do that (I know it's hard but I want it to be done using Joomla core).

答:
You can add hint="Placeholder name" in components/com_contact/models/forms/contact.xml

```<code><field
    name="contact_name"
    type="text"
    label="COM_CONTACT_CONTACT_EMAIL_NAME_LABEL"
    description="COM_CONTACT_CONTACT_EMAIL_NAME_DESC"
    id="contact-name"
    size="30"
    filter="string"
    required="true"
    hint="Placeholder name"
/>
</code>```

Body:
I am designing a template, however, I want my contact form to have placeholders. I tried overriding the contact component form file components/com_contact/views/contact/tmpl/default_form.php but it seems to use joomla JForm or something that doesn't give me the ability to add placeholder directly.

$this->form->getInput('contact_name');
$this->form->getInput('contact_email');
...

How can I add placeholde to the contacts? I definitely don't want to replace those pieces of code with naive html code. Neither I want to add a javascript code to do that (I know it's hard but I want it to be done using Joomla core).

Body:
You can add hint="Placeholder name" in components/com_contact/models/forms/contact.xml

<field
    name="contact_name"
    type="text"
    label="COM_CONTACT_CONTACT_EMAIL_NAME_LABEL"
    description="COM_CONTACT_CONTACT_EMAIL_NAME_DESC"
    id="contact-name"
    size="30"
    filter="string"
    required="true"
    hint="Placeholder name"
/>


问:
Codeigniter Ajax Post: Always Return Same Data
I'm new in codeigniter and using such as javascript, jQuery, Ajax, etc.
Just now, i'm trying to build an application like visitor management system, that usually takes barcode.

Here's my table on database:

tbl_vin

Here's my model:

```<code>public function selectX($tbl, $where)
{
    return $this->db->get_where($tbl, $where);
}
</code>```

Here's my controller:

```<code>public function check_av_vin(){
  $vin = $this->input->post('f1');
  $where = array('Vin'=>$vin);
  $result = $this->crud_m->selectX('tbl_vin', $where);
  if($result->num_rows() > 0){
    echo "1";
  }else{
    echo "0";
  }
}
</code>```

Here's my view:

```<code><input class="form-control" type="text" name="f1" id="barcode" autofocus></input>
</code>```

Here's my JS (on the same view):

```<code>$(document).ready(function() {
$("#barcode").on('keydown', function(event) {
  if (event.keyCode == 13) {
    var bc = $("#barcode").val();
    $.ajax({
      url: "<?php echo site_url('Lobby/check_av_vin')?>",
      data: {Vin : bc},
      type: 'POST',
      success: function(data){
        if(data == '1'){
          alert("VIN Already Exist!");
          $("#barcode").val("");
          $("#barcode").focus();
        }
        else if(data == '0'){
          alert("VIN available!");
          $("#barcode").val("");
          $("#barcode").focus();
        }
        else{
          alert("Error");
          $("#barcode").val("");
          $("#barcode").focus();
        }
      }
    });
    $("#name").focus();
    return false;
  }
});
</code>```

The question is:
Whatever i'm inserting the correct barcode like 'VIN00001' or wrong barcode or not inserting any text and hit enter, its always get data with string '0' and always get alert 'VIN available'. I dont know where's the problem.
Please help me.

答:
you're sending data via Ajax, and the data youre sending is { Vin : whatever }
 so to get this in your function check_av_vin() you need :
 $vin = $this->input->post('Vin'); instead of $vin = $this->input->post('f1');

Body:
I'm new in codeigniter and using such as javascript, jQuery, Ajax, etc.
Just now, i'm trying to build an application like visitor management system, that usually takes barcode.

Here's my table on database:

tbl_vin

Here's my model:

public function selectX($tbl, $where)
{
    return $this->db->get_where($tbl, $where);
}

Here's my controller:

public function check_av_vin(){
  $vin = $this->input->post('f1');
  $where = array('Vin'=>$vin);
  $result = $this->crud_m->selectX('tbl_vin', $where);
  if($result->num_rows() > 0){
    echo "1";
  }else{
    echo "0";
  }
}

Here's my view:

<input class="form-control" type="text" name="f1" id="barcode" autofocus></input>

Here's my JS (on the same view):

$(document).ready(function() {
$("#barcode").on('keydown', function(event) {
  if (event.keyCode == 13) {
    var bc = $("#barcode").val();
    $.ajax({
      url: "<?php echo site_url('Lobby/check_av_vin')?>",
      data: {Vin : bc},
      type: 'POST',
      success: function(data){
        if(data == '1'){
          alert("VIN Already Exist!");
          $("#barcode").val("");
          $("#barcode").focus();
        }
        else if(data == '0'){
          alert("VIN available!");
          $("#barcode").val("");
          $("#barcode").focus();
        }
        else{
          alert("Error");
          $("#barcode").val("");
          $("#barcode").focus();
        }
      }
    });
    $("#name").focus();
    return false;
  }
});

The question is:
Whatever i'm inserting the correct barcode like 'VIN00001' or wrong barcode or not inserting any text and hit enter, its always get data with string '0' and always get alert 'VIN available'. I dont know where's the problem.
Please help me.


问:
Difficulty using Protobuf 3.2 in C++
I'm trying to use Protobuf in C++, but having trouble getting it to do anything meaningful.  I'm using Visual Studio 2015.

I built the protobuf library.  I'm using the latest version from github.

I have created a .proto file as such:

```<code>syntax = "proto3";
package Networking;

message Robot{

message KinematicLinkProto {
    string name = 1;
    float x_pos = 2;
    float y_pos = 3;
    float z_pos = 4;
    float roll = 5;
    float pitch = 6;
    float yaw = 7;
    float x_scale = 8;
    float y_scale = 9;
    float z_scale = 10;
}

repeated KinematicLinkProto links = 1;

}
</code>```

I compile this, and try to add it to a project:

```<code>#include "Robot.pb.h"

int  main(int argc, char **argv)
{

    Networking::Robot robot_message;

    return 0;

}
</code>```

My linker links libprotobuf.lib.  I am building it as /MD and libprotobuf is built as /MD.

For some reason, this simple program has the following two linker errors:

```<code>Error   LNK2019 unresolved external symbol "private: static bool google::protobuf::io::CodedOutputStream::default_serialization_deterministic_" (?default_serialization_deterministic_@CodedOutputStream@io@protobuf@google@@0_NA) referenced in function "public: virtual unsigned char * __cdecl Networking::Robot::SerializeWithCachedSizesToArray(unsigned char *)const " (?SerializeWithCachedSizesToArray@Robot@Networking@@UEBAPEAEPEAE@Z)

Error   LNK2019 unresolved external symbol "class google::protobuf::internal::ExplicitlyConstructed<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > google::protobuf::internal::fixed_address_empty_string" (?fixed_address_empty_string@internal@protobuf@google@@3V?$ExplicitlyConstructed@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@123@A) referenced in function "protected: void __cdecl google::protobuf::internal::RepeatedPtrFieldBase::Clear<class google::protobuf::RepeatedPtrField<class Networking::Robot_KinematicLinkProto>::TypeHandler>(void)" (??$Clear@VTypeHandler@?$RepeatedPtrField@VRobot_KinematicLinkProto@Networking@@@protobuf@google@@@RepeatedPtrFieldBase@internal@protobuf@google@@IEAAXXZ)
</code>```

I'm very confused - this is a very simple program.  What could I possibly be doing wrong?

EDIT:  A colleague compiled proto 3001000. This version does seem to work. I'm curious as to what about 3002000 breaks everything.

答:
If you are using DLL, use</p>

```<code>#define PROTOBUF_USE_DLLS
</code>```

Title: Difficulty using Protobuf 3.2 in C++

Body:
I'm trying to use Protobuf in C++, but having trouble getting it to do anything meaningful.  I'm using Visual Studio 2015.

I built the protobuf library.  I'm using the latest version from github.

I have created a .proto file as such:

syntax = "proto3";
package Networking;

message Robot{

message KinematicLinkProto {
    string name = 1;
    float x_pos = 2;
    float y_pos = 3;
    float z_pos = 4;
    float roll = 5;
    float pitch = 6;
    float yaw = 7;
    float x_scale = 8;
    float y_scale = 9;
    float z_scale = 10;
}

repeated KinematicLinkProto links = 1;

}

I compile this, and try to add it to a project:

#include "Robot.pb.h"

int  main(int argc, char **argv)
{

    Networking::Robot robot_message;

    return 0;

}

My linker links libprotobuf.lib.  I am building it as /MD and libprotobuf is built as /MD.

For some reason, this simple program has the following two linker errors:

Error   LNK2019 unresolved external symbol "private: static bool google::protobuf::io::CodedOutputStream::default_serialization_deterministic_" (?default_serialization_deterministic_@CodedOutputStream@io@protobuf@google@@0_NA) referenced in function "public: virtual unsigned char * __cdecl Networking::Robot::SerializeWithCachedSizesToArray(unsigned char *)const " (?SerializeWithCachedSizesToArray@Robot@Networking@@UEBAPEAEPEAE@Z)

Error   LNK2019 unresolved external symbol "class google::protobuf::internal::ExplicitlyConstructed<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > google::protobuf::internal::fixed_address_empty_string" (?fixed_address_empty_string@internal@protobuf@google@@3V?$ExplicitlyConstructed@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@123@A) referenced in function "protected: void __cdecl google::protobuf::internal::RepeatedPtrFieldBase::Clear<class google::protobuf::RepeatedPtrField<class Networking::Robot_KinematicLinkProto>::TypeHandler>(void)" (??$Clear@VTypeHandler@?$RepeatedPtrField@VRobot_KinematicLinkProto@Networking@@@protobuf@google@@@RepeatedPtrFieldBase@internal@protobuf@google@@IEAAXXZ)

I'm very confused - this is a very simple program.  What could I possibly be doing wrong?

EDIT:  A colleague compiled proto 3001000. This version does seem to work. I'm curious as to what about 3002000 breaks everything.

Body:
If you are using DLL, use

#define PROTOBUF_USE_DLLS


问:
Run Command line via VBS with parameters
Having a hard time with this one. I can run the following command from a command prompt successfully, but can't get it working with a VB script.

From CMD:

Change directory to C:\Program Files (x86)\VMware\VMware Workstation\

then run: vmrun.exe -T ws start "C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx" nogui

What I've tried in VBS:

```<code>Dim objShell, strPath1, strAttr, strPath2
Set objShell = CreateObject ("WScript.Shell")

strPath1 = "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"
strAttr1 = " -T ws start "
strAttr2 = "C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx"
strAttr3 = " nogui"

'WScript.Echo strPath1 & strAttr1 & """" & strAttr2 & """" & strAttr3

objShell.Run strPath1 & strAttr1 & """" & strAttr2 & """" & strAttr3
</code>```

The error I get is: The system cannot find the file specified.

答:
Working Code ended up being:</p>

```<code>Dim objShell, strPath1, strAttr1, strAttr2, strAttr3
Set objShell = CreateObject ("WScript.Shell")

strPath1 = """C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"""
strAttr1 = " -T ws start "
strAttr2 = """C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx"""
strAttr3 = " nogui"

objShell.Run strPath1 & strAttr1 & strAttr2 & strAttr3
</code>```

Body:
Having a hard time with this one. I can run the following command from a command prompt successfully, but can't get it working with a VB script.

From CMD:

Change directory to C:\Program Files (x86)\VMware\VMware Workstation\

then run: vmrun.exe -T ws start "C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx" nogui

What I've tried in VBS:

Dim objShell, strPath1, strAttr, strPath2
Set objShell = CreateObject ("WScript.Shell")

strPath1 = "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"
strAttr1 = " -T ws start "
strAttr2 = "C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx"
strAttr3 = " nogui"

'WScript.Echo strPath1 & strAttr1 & """" & strAttr2 & """" & strAttr3

objShell.Run strPath1 & strAttr1 & """" & strAttr2 & """" & strAttr3

The error I get is: The system cannot find the file specified.

Body:
Working Code ended up being:

Dim objShell, strPath1, strAttr1, strAttr2, strAttr3
Set objShell = CreateObject ("WScript.Shell")

strPath1 = """C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"""
strAttr1 = " -T ws start "
strAttr2 = """C:\Users\Office\Documents\Virtual Machines\Windows 7\Windows 7.vmx"""
strAttr3 = " nogui"

objShell.Run strPath1 & strAttr1 & strAttr2 & strAttr3


问:
How to target a specific line of text from a list in Python
I'm using selenium with python2.7 and I have a css selector setup to get an element's text and its corresponding link. Im getting each users name that is on a shared account, and a link to their individual info. It prints out each name line by line, and I want to be able to reference to the persons name and use a .click() function to go to the users profile link. How would I automatically assign a class to the full element by only using the printed text? Here's my code.

```<code>elem = driver.find_elements_by_css_selector(".profile_Link .profile_Name")
  for span in elem:
     print span.text
</code>```

It will print out the list of Names like this

```<code>Josh Parker
Amy Doe
Parker Johns
...etc
</code>```

I want to automatically assign a class to each element by using only their profile name. So each time i'm getting data from a complete new list of name, I can simply just look at the printed profile names and do something like this

```<code>  elem = driver.find_elements_by_css_selector(".profile_Link .profile_Name")
  for span in elem:
     print span.text

 ("Josh Parker").click()
</code>```

and it will take me to Josh Parker's Link

答:
Maybe a dictionary of your classes?

```<code>class_dict = {span.text: MyClass( ... args ... ) for span in elem}
</code>```

Then

```<code>class_dict["Josh Parker"].click()
</code>```

Will invoke the click attribute of MyClass, as desired.

Body:
I'm using selenium with python2.7 and I have a css selector setup to get an element's text and its corresponding link. Im getting each users name that is on a shared account, and a link to their individual info. It prints out each name line by line, and I want to be able to reference to the persons name and use a .click() function to go to the users profile link. How would I automatically assign a class to the full element by only using the printed text? Here's my code.

elem = driver.find_elements_by_css_selector(".profile_Link .profile_Name")
  for span in elem:
     print span.text

It will print out the list of Names like this

Josh Parker
Amy Doe
Parker Johns
...etc

I want to automatically assign a class to each element by using only their profile name. So each time i'm getting data from a complete new list of name, I can simply just look at the printed profile names and do something like this

  elem = driver.find_elements_by_css_selector(".profile_Link .profile_Name")
  for span in elem:
     print span.text

 ("Josh Parker").click()

and it will take me to Josh Parker's Link

Body:
Maybe a dictionary of your classes?

class_dict = {span.text: MyClass( ... args ... ) for span in elem}

Then

class_dict["Josh Parker"].click()

Will invoke the click attribute of MyClass, as desired.


答:
You have wrong variable name in your code.

in check_av_vin() function you used

```<code>$this->input->post('f1');
</code>```

though in form the input name is f1, when you send your ajax request you put

```<code>data: {Vin : bc},
</code>```

just put following will solve your problem.

```<code>$this->input->post('Vin');
</code>```

Title: Codeigniter Ajax Post: Always Return Same Data

Body:
You have wrong variable name in your code.

in check_av_vin() function you used

$this->input->post('f1');

though in form the input name is f1, when you send your ajax request you put

data: {Vin : bc},

just put following will solve your problem.

$this->input->post('Vin');


问:
Create accordion table in PHP with unsorted array by unix timestamp
I have this array in PHP that looks something like this:

```<code>$arras = array(
  '0'=>array('dt_transaction'=>232352),
  '1'=>array('dt_transaction'=>1234),
  '2'=>array('dt_transaction'=>1235),
  '3'=>array('dt_transaction'=>123456),
  '4'=>array('dt_transaction'=>1));
</code>```

(dt_transaction is a UNIX timestamp)

But a lot bigger. I have to create a HTML table with this data, but the table must be an accordion jQuery table that groups the data by month.
The array is completely unsorted, I tried to use usort() but the array is too big and slow.

Heres the method i tried:

```<code>usort($arras, function ($a, $b) { return $a['dt_transaction'] - $b['dt_transaction']; });
</code>```

So, i tried to make it in frontend with jQuery append but it's also way too slow. Is there something that allows me to just do a foreach and add the rows then automatically sort by date and group by month? Or something simpler.

答:
Use array_multisort(). Example 3 in the PHP documentation gives you the pattern you're looking for. Not super efficient as you need to loop over the array, but it should do the trick.

```<code><?php
$arras = array(
    '0'=>array('dt_transaction'=>232352),
    '1'=>array('dt_transaction'=>1234),
    '2'=>array('dt_transaction'=>1235),
    '3'=>array('dt_transaction'=>123456),
    '4'=>array('dt_transaction'=>1)
);
foreach ($arras as $k=>$v) {
    $trans[$k] = $v["dt_transaction"];
}

array_multisort($trans, SORT_ASC, $arras);

print_r($arras);
</code>```

Body:
I have this array in PHP that looks something like this:

$arras = array(
  '0'=>array('dt_transaction'=>232352),
  '1'=>array('dt_transaction'=>1234),
  '2'=>array('dt_transaction'=>1235),
  '3'=>array('dt_transaction'=>123456),
  '4'=>array('dt_transaction'=>1));

(dt_transaction is a UNIX timestamp)

But a lot bigger. I have to create a HTML table with this data, but the table must be an accordion jQuery table that groups the data by month.
The array is completely unsorted, I tried to use usort() but the array is too big and slow.

Heres the method i tried:

usort($arras, function ($a, $b) { return $a['dt_transaction'] - $b['dt_transaction']; });

So, i tried to make it in frontend with jQuery append but it's also way too slow. Is there something that allows me to just do a foreach and add the rows then automatically sort by date and group by month? Or something simpler.

Body:
Use array_multisort(). Example 3 in the PHP documentation gives you the pattern you're looking for. Not super efficient as you need to loop over the array, but it should do the trick.

<?php
$arras = array(
    '0'=>array('dt_transaction'=>232352),
    '1'=>array('dt_transaction'=>1234),
    '2'=>array('dt_transaction'=>1235),
    '3'=>array('dt_transaction'=>123456),
    '4'=>array('dt_transaction'=>1)
);
foreach ($arras as $k=>$v) {
    $trans[$k] = $v["dt_transaction"];
}

array_multisort($trans, SORT_ASC, $arras);

print_r($arras);


问:
Flex vertical alignment issue
I had a row of inline-block elements which wrapped nicely on a new line if did not fit:

.buttons div {
  display: inline-block;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="buttons">
    <div>Some text here</div>
    <div><span></span>Some text here</div>
    <div>Some text here</div>
    <div><span></span>Some text here</div>
    <div>Some text here</div>
    <div><span></span>Some text here</div>
    <div>Some text here</div>
    <div><span></span>Some text here</div>
    <div>Some text here</div>
    <div><span></span>Some text here</div>
  </div></code>```

JSFiddle link #1

Now I'm changing the layout to flex like that:

.buttons div {
  display: inline-flex;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}```

And the elements are not longer vertically aligned:

JSFiddle link #2

How to get the row of div elements shown in the HTML snippet above to look like on my first image, but with flex?

答:
In a flex formatting context with display: inline-flex you need to reset the vertical-align property. Add this to your code:

```<code>.buttons div {
    vertical-align: top;
}
</code>```

.buttons div {
  display: inline-flex;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
  vertical-align: top;  /* NEW */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
</div></code>```

The default value for vertical-align is baseline. Because some of your flex containers have a single anonymous flex item (the text) while others have an anonymous flex item and a span, this is apparently generating two different baselines for the parent. By changing the vertical-align value to top, middle, bottom or something else the problem should be solved.

Alternatively, if using display: inline-flex is not essential, a better solution is to simply apply display: flex with flex-wrap: wrap to the primary container.

.buttons {
  display: flex;
  flex-wrap: wrap;
}

.buttons div {
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
</div></code>```

This will eliminate the vertical-align issue altogether.

Title: Flex vertical alignment issue

Body:
I had a row of inline-block elements which wrapped nicely on a new line if did not fit:

.buttons div {
  display: inline-block;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

JSFiddle link #1

Now I'm changing the layout to flex like that:

.buttons div {
  display: inline-flex;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}

And the elements are not longer vertically aligned:

JSFiddle link #2

How to get the row of div elements shown in the HTML snippet above to look like on my first image, but with flex?

Body:
In a flex formatting context with display: inline-flex you need to reset the vertical-align property. Add this to your code:

.buttons div {
    vertical-align: top;
}

.buttons div {
  display: inline-flex;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
  vertical-align: top;  /* NEW */
}

<div class="buttons">
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
</div>

The default value for vertical-align is baseline. Because some of your flex containers have a single anonymous flex item (the text) while others have an anonymous flex item and a span, this is apparently generating two different baselines for the parent. By changing the vertical-align value to top, middle, bottom or something else the problem should be solved.

Alternatively, if using display: inline-flex is not essential, a better solution is to simply apply display: flex with flex-wrap: wrap to the primary container.

.buttons {
  display: flex;
  flex-wrap: wrap;
}

.buttons div {
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}

<div class="buttons">
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
  <div>Some text here</div>
  <div><span></span>Some text here</div>
</div>

This will eliminate the vertical-align issue altogether.


问:
Python 3.4 :ImportError: no module named win32api
I am using python 3.4 on windows 7. In order to open a doc file I am using this code:

```<code>import sys
import win32com.client as win32

word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument
</code>```

I'M not sure why is this error popping up every time:

```<code>ImportError: no module named win32api
</code>```

Although I have installed pywin32 from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
and I have also checked the path from where I am importing. I have tried reinstalling pywin32 as well but that doesn't remove the error.

答: I encountered the same error yestoday with Python 3.6.1 on Windows 7, and resolved it by "pip install pypiwin32".</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using python 3.4 on windows 7. In order to open a doc file I am using this code:

import sys
import win32com.client as win32

word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument

I'M not sure why is this error popping up every time:

ImportError: no module named win32api

Although I have installed pywin32 from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
and I have also checked the path from where I am importing. I have tried reinstalling pywin32 as well but that doesn't remove the error.


问:
I want to add all the values that user inputted in the loop together to let the use know what their total sum is
I want to make a code that asks the user for different values and then adds them all up together. The sum would then be displayed to them to see. I have so far been able to make a loop where it make multiple text boxes, the amount of text boxes depends on the number of values they want to add. But I do not know how to add up all their values and display it for them.</p>

```<code> Scanner myInput = new Scanner(System.in);

 int addNumber, total;
 int num = 0;

 System.out.println("Please input how many values you wish to add up together");
 addNumber = myInput.nextInt();

  for (int numValue =1; numValue <= addNumber; numValue++)
  {
    int value;
    total = num + numValue;

    System.out.println("Please input your " + total + " value.");
    value = myInput.nextInt();
  }
</code>```

答:
you are almost there

First of all initialise total

```<code>int total = 0;

for (int numValue =1; numValue <= addNumber; numValue++)
  {

    System.out.println("Please input your " + numValue + " value.");
    total += myInput.nextInt();
  }

System.out.println ("The total is " + total);
</code>```

In this code

```<code>total = num + numValue;
</code>```

you are simply setting the value of total to numValue as num is always 0

In my code I am using total to store the final answer, by adding the entered value to the running total

Body:
I want to make a code that asks the user for different values and then adds them all up together. The sum would then be displayed to them to see. I have so far been able to make a loop where it make multiple text boxes, the amount of text boxes depends on the number of values they want to add. But I do not know how to add up all their values and display it for them.

 Scanner myInput = new Scanner(System.in);

 int addNumber, total;
 int num = 0;

 System.out.println("Please input how many values you wish to add up together");
 addNumber = myInput.nextInt();

  for (int numValue =1; numValue <= addNumber; numValue++)
  {
    int value;
    total = num + numValue;

    System.out.println("Please input your " + total + " value.");
    value = myInput.nextInt();
  }

Body:
you are almost there

First of all initialise total

int total = 0;

for (int numValue =1; numValue <= addNumber; numValue++)
  {

    System.out.println("Please input your " + numValue + " value.");
    total += myInput.nextInt();
  }

System.out.println ("The total is " + total);

In this code

total = num + numValue;

you are simply setting the value of total to numValue as num is always 0

In my code I am using total to store the final answer, by adding the entered value to the running total


问:
How do I plot two countplot graphs side by side?
I am trying to plot two countplots showing the counts of batting and bowling. I tried the following code:

```<code>l=['batting_team','bowling_team']
for i in l:
    sns.countplot(high_scores[i])
    mlt.show()
</code>```

But by using this , I am getting two plots one below the other. How can i make them order side by side?

答:
Something like this:

```<code>import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

batData = ['a','b','c','a','c']
bowlData = ['b','a','d','d','a']

df=pd.DataFrame()
df['batting']=batData
df['bowling']=bowlData

fig, ax =plt.subplots(1,2)
sns.countplot(df['batting'], ax=ax[0])
sns.countplot(df['bowling'], ax=ax[1])
fig.show()
</code>```

The idea is to specify the subplots in the figure - there are numerous ways to do this but the above will work fine.

Body:
I am trying to plot two countplots showing the counts of batting and bowling. I tried the following code:

l=['batting_team','bowling_team']
for i in l:
    sns.countplot(high_scores[i])
    mlt.show()

But by using this , I am getting two plots one below the other. How can i make them order side by side?

Body:
Something like this:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

batData = ['a','b','c','a','c']
bowlData = ['b','a','d','d','a']

df=pd.DataFrame()
df['batting']=batData
df['bowling']=bowlData

fig, ax =plt.subplots(1,2)
sns.countplot(df['batting'], ax=ax[0])
sns.countplot(df['bowling'], ax=ax[1])
fig.show()

The idea is to specify the subplots in the figure - there are numerous ways to do this but the above will work fine.


问:
Calling Swift code in a C testing suite
I am currently working on a library in Swift that has a version already written in C. As the version in C already has a large testing suite, I would like to just run the Swift code through the C tests.

Is it possible to call Swift in C?

答:
To call Swift from C one can wrap Swift code in Objective-C functions callable from C.  A trivial contrived example follows.

Swift code:

```<code>import Foundation

@objc public class ClassSwift : NSObject {
    public func addIntegers(int1:Int32, int2:Int32) -> Int32 {
        return int1 + int2;
    }
}
</code>```

Objective-C wrapper:

```<code>// Mixed 1a is the name of my sample target
// You can see the name of your Swift header in
// Objective-C Generated Interface Header Name under Build Settings.
#import "Mixed_1a-Swift.h"

// This function is callable from C, even though it calls Swift code!
int addIntsC(int i1, int i2)
{
    ClassSwift * cs = [[ClassSwift alloc] init];
    return [cs addIntegersWithInt1:i1 int2:i2];
}
</code>```

And, finally, here's the C code:

```<code>#include <stdio.h>

int addIntsC(int, int);

int main(int argc, const char * argv[]) {
    int result = addIntsC(3, 7);
    if (result == 10) puts("Test passed!");
    else puts("Failed... :(");
    return 0;
}
</code>```

Title: Calling Swift code in a C testing suite

Body:
To call Swift from C one can wrap Swift code in Objective-C functions callable from C.  A trivial contrived example follows.

Swift code:

import Foundation

@objc public class ClassSwift : NSObject {
    public func addIntegers(int1:Int32, int2:Int32) -> Int32 {
        return int1 + int2;
    }
}

Objective-C wrapper:

// Mixed 1a is the name of my sample target
// You can see the name of your Swift header in
// Objective-C Generated Interface Header Name under Build Settings.
#import "Mixed_1a-Swift.h"

// This function is callable from C, even though it calls Swift code!
int addIntsC(int i1, int i2)
{
    ClassSwift * cs = [[ClassSwift alloc] init];
    return [cs addIntegersWithInt1:i1 int2:i2];
}

And, finally, here's the C code:

#include <stdio.h>

int addIntsC(int, int);

int main(int argc, const char * argv[]) {
    int result = addIntsC(3, 7);
    if (result == 10) puts("Test passed!");
    else puts("Failed... :(");
    return 0;
}


问:
Hibernate, Spring & HSQL: Table not Found Exception
we're using spring, hibernate and hsql to persist a simple user entity. We always get the error "table not found". Do you have any idea what this could be? It seems like the table is not generated or the hsql database is not running at all.

Regards,
G.

```<code>@Entity
@Table (name="USER")
public class User {

 @Id
 @GeneratedValue(strategy= GenerationType.AUTO)
 @Column(name="ID")
 private Long id;

 @Column(name="NAME", length = 100, nullable = false)
 private String name;

 public User(){}

        //getters and setters ...
</code>```

by this dao class:

```<code>package de.hsrm.mediathek;

import java.util.List;

public class UserDao implements IUserDao{

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(final HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    @Transactional
    public void store(final User user){
        hibernateTemplate.saveOrUpdate(user);
    }

    @Transactional
    public void delete(final Long userId){
        final User user = (User) hibernateTemplate.get(User.class, userId);
        hibernateTemplate.delete(user);
    }

    @Transactional(readOnly = true)
    public User findById(final Long userId){
        return (User) hibernateTemplate.get(User.class, userId);
    }

    @Transactional(readOnly = true)
    public List<User> findAll(){
        return hibernateTemplate.find("from User");
    }

}
</code>```

Configuration XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <tx:annotation-driven/>

 <bean id="dataSource"
   class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
  <property name="url" value="jdbc:hsqldb:mem:mediathekdb" />
  <property name="username" value="sa" />
  <property name="password" value="" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>de.hsrm.mediathek.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
    <prop key="hibernate.hbm2dll.auto">create-drop</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop
     key="hibernate.cache.provider_class">
     org.hibernate.cache.HashtableCacheProvider</prop>
   </props>
  </property>

 </bean>

 <bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>

 <bean id="userDao" class="de.hsrm.mediathek.UserDao">
  <property name="hibernateTemplate" ref="hibernateTemplate" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <!-- Interceptor for hibernate calls to be able to create and close sessions
 <bean id="hibernateInterceptor"
  class="org.springframework.orm.hibernate3.HibernateInterceptor">
  <property name="sessionFactory"><ref local="sessionFactory"/></property>
 </bean>
-->
</beans>
</code>```

Error LOG:

```<code>Caused by: java.sql.SQLException: Table not found in statement [insert into User (ID, NAME) values (null, ?)]
 at org.hsqldb.jdbc.Util.throwError(Unknown Source)
 at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
 at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
 at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:528)
 at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:95)
 at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30)
 ... 63 more
</code>```

答:
The problem is that the property "hbm2dll" is wrongly spelled. It should be "hbm2ddl":

It is:

```<code><prop key="hibernate.hbm2dll.auto">create-drop</prop>
</code>```

It should be:

```<code><prop key="hibernate.hbm2ddl.auto">create-drop</prop>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
we're using spring, hibernate and hsql to persist a simple user entity. We always get the error "table not found". Do you have any idea what this could be? It seems like the table is not generated or the hsql database is not running at all.

Regards,
G.

@Entity
@Table (name="USER")
public class User {

 @Id
 @GeneratedValue(strategy= GenerationType.AUTO)
 @Column(name="ID")
 private Long id;

 @Column(name="NAME", length = 100, nullable = false)
 private String name;

 public User(){}

        //getters and setters ...

by this dao class:

package de.hsrm.mediathek;

import java.util.List;

public class UserDao implements IUserDao{

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(final HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    @Transactional
    public void store(final User user){
        hibernateTemplate.saveOrUpdate(user);
    }

    @Transactional
    public void delete(final Long userId){
        final User user = (User) hibernateTemplate.get(User.class, userId);
        hibernateTemplate.delete(user);
    }

    @Transactional(readOnly = true)
    public User findById(final Long userId){
        return (User) hibernateTemplate.get(User.class, userId);
    }

    @Transactional(readOnly = true)
    public List<User> findAll(){
        return hibernateTemplate.find("from User");
    }

}

Configuration XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <tx:annotation-driven/>

 <bean id="dataSource"
   class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
  <property name="url" value="jdbc:hsqldb:mem:mediathekdb" />
  <property name="username" value="sa" />
  <property name="password" value="" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>de.hsrm.mediathek.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
    <prop key="hibernate.hbm2dll.auto">create-drop</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop
     key="hibernate.cache.provider_class">
     org.hibernate.cache.HashtableCacheProvider</prop>
   </props>
  </property>

 </bean>

 <bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>

 <bean id="userDao" class="de.hsrm.mediathek.UserDao">
  <property name="hibernateTemplate" ref="hibernateTemplate" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

</beans>

Error LOG:

Caused by: java.sql.SQLException: Table not found in statement [insert into User (ID, NAME) values (null, ?)]
 at org.hsqldb.jdbc.Util.throwError(Unknown Source)
 at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
 at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
 at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:528)
 at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:95)
 at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30)
 ... 63 more

Body:
The problem is that the property "hbm2dll" is wrongly spelled. It should be "hbm2ddl":

It is:

<prop key="hibernate.hbm2dll.auto">create-drop</prop>

It should be:

<prop key="hibernate.hbm2ddl.auto">create-drop</prop>


问:
How to Change Oracle Encoding to AL32UTF8 in SQLPlus in Windows
Iused the following command to test my Oracle current encoding

```<code>select userenv('language') from dual;
select * from v$nls_parameters where parameter='NLS_CHARACTERSET';
select * from nls_database_parameters
select * from nls_instance_parameters
select * from nls_session_parameters
</code>```

But what I want is AL32UTF8. How to change the encoding to AL32UTF8. Thanks~

答:
Open your console</p>

```<code>sqlplus "/ as sysdba"

SQL> shutdown immediate;
SQL> startup mount;
SQL> alter session set sql_trace=true;
SQL> alter system enable restricted session;
SQL> alter system set job_queue_processes=0;
SQL> alter system set aq_tm_processes=0;
SQL> alter database open;

//For version before oracle 9i like 8i, using these two lines
SQL> alter database character set internal_use UTF8;
SQL> alter database national character set internal_use UTF8;
//For version after oracle 9i, using these two lines
SQL> alter database character set internal_use AL32UTF8;
SQL> alter database national character set internal_use AL32UTF8;

SQL> alter session set sql_trace=false;
SQL> shutdown immediate;
SQL> startup;
</code>```

Body:
Iused the following command to test my Oracle current encoding

select userenv('language') from dual;
select * from v$nls_parameters where parameter='NLS_CHARACTERSET';
select * from nls_database_parameters
select * from nls_instance_parameters
select * from nls_session_parameters

But what I want is AL32UTF8. How to change the encoding to AL32UTF8. Thanks~

Body:
Open your console

sqlplus "/ as sysdba"

SQL> shutdown immediate;
SQL> startup mount;
SQL> alter session set sql_trace=true;
SQL> alter system enable restricted session;
SQL> alter system set job_queue_processes=0;
SQL> alter system set aq_tm_processes=0;
SQL> alter database open;

//For version before oracle 9i like 8i, using these two lines
SQL> alter database character set internal_use UTF8;
SQL> alter database national character set internal_use UTF8;
//For version after oracle 9i, using these two lines
SQL> alter database character set internal_use AL32UTF8;
SQL> alter database national character set internal_use AL32UTF8;

SQL> alter session set sql_trace=false;
SQL> shutdown immediate;
SQL> startup;


问:
JQuery matchMedia .scroll not working?
I'm trying to get the logo on my website to fade when I scroll but only when it is at the media query for mid-width: 992px. This code works on load, but not on resize of the window and I can't quite figure out where I'm going wrong.</p>

```<code>$(document).ready(function(){
});

//Large Screen Check Scroll Event
var screenSize = window.matchMedia("(min-width: 992px)");
scrollFade(screenSize);
scrollFade.addListener(screenSize);

function scrollFade(screenSize){
   if (screenSize.matches){ // if media query matches
     $(window).scroll(function(){
       $(".logo").css("opacity", 1 - $(window).scrollTop() / 600);
     });//do the thing
  }
}
</code>```

答:
The addListener() is backwards. Instead, the function should be attached to the matchMedia variable like:

screenSize.addListener(scrollFade);

JS Fiddle

You also may want to stop the scroll event if the user changes window size so it no longer matches when it previously did. To do so, you can add an else statement and add:

$(window).off('scroll');

JS Fiddle - off()

Title: JQuery matchMedia .scroll not working?

Body:
I'm trying to get the logo on my website to fade when I scroll but only when it is at the media query for mid-width: 992px. This code works on load, but not on resize of the window and I can't quite figure out where I'm going wrong.

$(document).ready(function(){
});

//Large Screen Check Scroll Event
var screenSize = window.matchMedia("(min-width: 992px)");
scrollFade(screenSize);
scrollFade.addListener(screenSize);

function scrollFade(screenSize){
   if (screenSize.matches){ // if media query matches
     $(window).scroll(function(){
       $(".logo").css("opacity", 1 - $(window).scrollTop() / 600);
     });//do the thing
  }
}


问:
How to call to LinkedList with generic type
I'm using several LinkedList each one from different type, for example :

```<code> LinkedList<A> typeA = new LinkedList<>();
 LinkedList<B> typeB = new LinkedList<>();
 LinkedList<C> typeC = new LinkedList<>();
</code>```

and then i want to print them according to the type, so for each type I call to the appropriate function.

```<code>void funcA(LinkedList<A> ls)
void funcB(LinkedList<B> ls)
void funcC(LinkedList<C> ls)
</code>```

and I wonder if the is any option of calling one function and inside that function to check the type.
Thank for those who help! Have a nice day :)

答:
I'd use another generic parameter to the function to indicate how the list is to be printed based on the type.

See http://www.functionaljava.org/javadoc/4.7/functionaljava/fj/Show.html

Example:

```<code>void func<A>(LinkedList<A> list, Show<A> aShow) {
  listShow(aShow).printLn(list)
}
</code>```

If you were using Scala you would make Show[A] an implicit parameter.

Body:
I'm using several LinkedList each one from different type, for example :

 LinkedList typeA = new LinkedList<>();
 LinkedList typeB = new LinkedList<>();
 LinkedList<C> typeC = new LinkedList<>();

and then i want to print them according to the type, so for each type I call to the appropriate function.

void funcA(LinkedList ls)
void funcB(LinkedList ls)
void funcC(LinkedList<C> ls)

and I wonder if the is any option of calling one function and inside that function to check the type.
Thank for those who help! Have a nice day :)

Body:
I'd use another generic parameter to the function to indicate how the list is to be printed based on the type.

See http://www.functionaljava.org/javadoc/4.7/functionaljava/fj/Show.html

Example:

void func<A>(LinkedList<A> list, Show<A> aShow) {
  listShow(aShow).printLn(list)
}

If you were using Scala you would make Show[A] an implicit parameter.


问:
how to sort numerical arraylist in ascending order
I have an ArrayList which I have sorted using Collections.sort.
But the outcome looks like down below. How do I get it to be ascending order?

[0, 1, 11, 12, 12, 13, 13, 14, 14, 16, 16, 16, 17, 17, 17, 18, 18, 19, 2, 2, 20, 20, 20, 21, 21, 22, 4, 7, 7, 7, 8, 9, 9, 9, 9, 9]

答:
Collections.sort method works fine if you don't mixed numeric and string types;
 Here's an example:

```<code>       import java.util.*;
       public class ArrayListOfIntegers  {

        public static void main(String args[]){
        ArrayList<Integer> arraylist = new ArrayList<>();
        arraylist.add(12);
        arraylist.add(0);
        arraylist.add(12);
        arraylist.add(1);
        arraylist.add(12);
        arraylist.add(11);
       /* ArrayList before the sorting*/
        System.out.println("Before Sorting:");
        for(int counter: arraylist){
             System.out.println(counter);
         }

        /* Sorting of arraylist using Collections.sort*/
           Collections.sort(arraylist);

        /* ArrayList after sorting*/
         System.out.println("After Sorting:");
         for(int counter: arraylist){
             System.out.println(counter);
         }
      }
   }
</code>```

Output :

Good luck;

Body:
Collections.sort method works fine if you don't mixed numeric and string types;
 Here's an example:

       import java.util.*;
       public class ArrayListOfIntegers  {

        public static void main(String args[]){
        ArrayList<Integer> arraylist = new ArrayList<>();
        arraylist.add(12);
        arraylist.add(0);
        arraylist.add(12);
        arraylist.add(1);
        arraylist.add(12);
        arraylist.add(11);
       /* ArrayList before the sorting*/
        System.out.println("Before Sorting:");
        for(int counter: arraylist){
             System.out.println(counter);
         }

        /* Sorting of arraylist using Collections.sort*/
           Collections.sort(arraylist);

        /* ArrayList after sorting*/
         System.out.println("After Sorting:");
         for(int counter: arraylist){
             System.out.println(counter);
         }
      }
   }

Output :

Good luck;


问:
Two different ways of create a delegate instance?
```<code>using System;

delegate void D(int x);

class C
{
   public static void M1(int i) {
    Console.WriteLine("C.M1: " + i);
   }
}

  D cd1 = new D(C.M1);
  D cd2 = C.M1;
</code>```

Delegate instances cd1 and cd2  are created differently above.

Are they equivalent?

If not, what differences are between them?

Thanks.

答:
If you look at the IL generated via a tool like LinqPad, you would find that in this case both blocks compile to the exact same thing:

```<code>void Main()
{
    D cd1 = new D(C.M1);
    D cd2 = C.M1;
}
</code>```

becomes

```<code>IL_0000:  nop
IL_0001:  ldnull
IL_0002:  ldftn       UserQuery+C.M1
IL_0008:  newobj      UserQuery+D..ctor
IL_000D:  stloc.0     // cd1
IL_000E:  ldnull
IL_000F:  ldftn       UserQuery+C.M1
IL_0015:  newobj      UserQuery+D..ctor
IL_001A:  stloc.1     // cd2
IL_001B:  ret
</code>```

Note that instructions are 2-5 are repeated in 6-9, with a different stloc since a new instance is created.

Body:
using System;

delegate void D(int x);

class C
{
   public static void M1(int i) {
    Console.WriteLine("C.M1: " + i);
   }
}

  D cd1 = new D(C.M1);
  D cd2 = C.M1;

Delegate instances cd1 and cd2  are created differently above.

Are they equivalent?

If not, what differences are between them?

Thanks.

Body:
If you look at the IL generated via a tool like LinqPad, you would find that in this case both blocks compile to the exact same thing:

void Main()
{
    D cd1 = new D(C.M1);
    D cd2 = C.M1;
}

becomes

IL_0000:  nop
IL_0001:  ldnull
IL_0002:  ldftn       UserQuery+C.M1
IL_0008:  newobj      UserQuery+D..ctor
IL_000D:  stloc.0     // cd1
IL_000E:  ldnull
IL_000F:  ldftn       UserQuery+C.M1
IL_0015:  newobj      UserQuery+D..ctor
IL_001A:  stloc.1     // cd2
IL_001B:  ret

Note that instructions are 2-5 are repeated in 6-9, with a different stloc since a new instance is created.


答:
display: flex should actually be a property of the container, not the items in the flexbox. You will also need to set some other properties to get the same behavior as the original.

```<code>.buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

// Remove display property from .buttons div
</code>```

More info

Title: Flex vertical alignment issue

Body:
I had a row of inline-block elements which wrapped nicely on a new line if did not fit:

.buttons div {
  display: inline-block;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

Some text here

JSFiddle link #1

Now I'm changing the layout to flex like that:

.buttons div {
  display: inline-flex;
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
}

And the elements are not longer vertically aligned:

JSFiddle link #2

How to get the row of div elements shown in the HTML snippet above to look like on my first image, but with flex?

Body:
display: flex should actually be a property of the container, not the items in the flexbox. You will also need to set some other properties to get the same behavior as the original.

.buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

// Remove display property from .buttons div

More info


答:
This should help
http://codepen.io/flurrd/pen/dvwpPp</p>

```<code> <div class="btn-group">
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
</div>

.btn-group {
  display: flex;
  flex-wrap: wrap;
}
.btn {
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
  display: inline-block;
}
</code>```

Title: Flex vertical alignment issue

Body:
This should help
http://codepen.io/flurrd/pen/dvwpPp

 <div class="btn-group">
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
    <div class="btn">Some text here</div>
    <div class="btn"><span></span>Some text here</div>
</div>

.btn-group {
  display: flex;
  flex-wrap: wrap;
}
.btn {
  padding: 0.3em;
  margin: 0.3em;
  border: 1px dotted red;
  display: inline-block;
}


问:
Displaying nodes inside a node with Drupal 6
I have a custom content type in Drupal 6 and one of it's fields is a node reference field. This field contains node ID's for a few nodes and i want to display those selected nodes after my node content. Any ideas how i can do that in the theme?</p>

答: Again without any custom coding you can use the Node Displays module to further customise the layout of a node independently of the admin form layout - http://drupal.org/project/nd</p>


答:
Are they equivalent?

Yes. Delegates created explicitly and delegates created using the Method Group Syntax are equivalent to each other.

Method Group Conversion has been introduced in C# 2.0. In the first version of C# the syntax that you used for cd1 was the only choice available for creating a delegate.

Title: Two different ways of create a delegate instance?


问:
Firebase data received on simulator ok, but is not received on some iOS real devices
We are seeing a really weird issue on iOS with Firebase. Some users iPhones are receiving data/sending data to Firebase fine. Our testing on sims is fine.

However some users, are not able to receive or send any data with Firebase. We confirmed that the listeners are triggered and 'waiting' on those devices but no data is being received.

Has anyone had this same issue and resolved it?

答:
Thanks for getting back on this, the question was initially just to see if others had come across the same scenario, before we posted any code etc.

Anyway the long and short of it after much testing and debugging is that these problems we're NOT related to Firebase's own APIs but rather the Firestack lib which is a React Native bridge. Should have made that (Firestack) clearer in original post. We have thrown out the Firestack lib completely and are using Firebase's own JS APIs - and this particular strange issue, is gone (fixed) with no adjustment to our code necessary other than swapping out the API calls.