问:
Laravel Eloquent One-To-Many
I'm new to Laravel and I'm trying to make a simple CMS system.
I made the following models which are one-to-many related:

Page (id, name, blocks)

```<code>public function blocks() {
    return $this->hasMany('App\Block');
}
</code>```

Block (id, name, displayName, content)

```<code>public function page() {
    return $this->belongsTo('App\Page');
}
</code>```

Now I want to create a page and set the blocks right away.
I'm getting a $request object looking like this:

```<code>{
   "name": "Page name",
   "blocks": [
      {
         "name": "block name",
         "displayName": "Display Name",
         "content": "Some HTML content"
      }
   ]
}
</code>```

Now, I'm trying to save these all to the database, but I'm running in a lot of errors.

So far, I concluded I have to iterate over every 'block' and actually create a new Block. But I'm not exactly sure how to save it to the database.

Do I save the page first, then add the Blocks or first the blocks and then the page. I'm getting a bit confused.

答:
First, make sure you have a page_id column in the blocks table and the foreign key constraint like this :

```<code>public function up()
{
    Schema::create('blocks', function (Blueprint $table) {
        $table->increments('id');
        // your fields here
        $table->integer('page_id')->unsigned();
        $table->timestamps();

        $table->foreign('page_id')
            ->references('id')
            ->on('pages')
            ->onDelete('cascade');
    });
}
</code>```

Second, you have to save the page first to the database, and then add to blocks to the page. Because you need the page_id when you create the blocks.

Finally,

You may use the createMany method to create multiple related models.
  See Laravel docs

Example:

```<code>$page = App\Page::create([
    'name' => 'name',
]);

$blocks = $page->blocks()->createMany([
    [
        'name' => 'name1',
        'displayName' => 'displayName1',
        'content' => 'content1'
    ],
    [
        'name' => 'name2',
        'displayName' => 'displayName2',
        'content' => 'content2'
    ],
]);

// to get all blocks from the request
$blocks = $page->blocks()->createMany(request('blocks'));
</code>```

Title: Laravel Eloquent One-To-Many

Body:
I'm new to Laravel and I'm trying to make a simple CMS system.
I made the following models which are one-to-many related:

Page (id, name, blocks)

public function blocks() {
    return $this->hasMany('App\Block');
}

Block (id, name, displayName, content)

public function page() {
    return $this->belongsTo('App\Page');
}

Now I want to create a page and set the blocks right away.
I'm getting a $request object looking like this:

{
   "name": "Page name",
   "blocks": [
      {
         "name": "block name",
         "displayName": "Display Name",
         "content": "Some HTML content"
      }
   ]
}

Now, I'm trying to save these all to the database, but I'm running in a lot of errors.

So far, I concluded I have to iterate over every 'block' and actually create a new Block. But I'm not exactly sure how to save it to the database.

Do I save the page first, then add the Blocks or first the blocks and then the page. I'm getting a bit confused.

Body:
First, make sure you have a page_id column in the blocks table and the foreign key constraint like this :

public function up()
{
    Schema::create('blocks', function (Blueprint $table) {
        $table->increments('id');
        // your fields here
        $table->integer('page_id')->unsigned();
        $table->timestamps();

        $table->foreign('page_id')
            ->references('id')
            ->on('pages')
            ->onDelete('cascade');
    });
}

Second, you have to save the page first to the database, and then add to blocks to the page. Because you need the page_id when you create the blocks.

Finally,

You may use the createMany method to create multiple related models.
  See Laravel docs

Example:

$page = App\Page::create([
    'name' => 'name',
]);

$blocks = $page->blocks()->createMany([
    [
        'name' => 'name1',
        'displayName' => 'displayName1',
        'content' => 'content1'
    ],
    [
        'name' => 'name2',
        'displayName' => 'displayName2',
        'content' => 'content2'
    ],
]);

// to get all blocks from the request
$blocks = $page->blocks()->createMany(request('blocks'));


来源: stackexchange

问:
PromiseKit go back one step
I have a series of UIViewControllers (popups) in my app that I use to gather information from the end user. I managed to chain them with promises like this:

```<code>firstly {
        return showFirstPopup()
    }
    .then { info1 -> Promise<Info2> in
        dismissFirstPopup()
        //Do sth with info1...
        return showSecondPopup()
    }
    .then { info2 -> Promise<Info3> in
        dismissSecondPopup()
        //Do sth with info2...
        return showThirdPopup()
    }
    .then { info3 -> Promise<Info4> in
        dismissThirdPopup()
        //Do sth with info3...
        return showForthPopup()
    }
    ...
    .catch { error in
        //Handle any error or cancellation...
     }
</code>```

If, for example, the user presses back in the third popup I need to go back to the previous "then" and not cancel the whole flow.

Basically I need to be able to go back one step, let the user edit the data, then continue the flow.

Is there a way to do this with PromiseKit?

答:
Here is what I found about PromiseKit :

PromiseKit has the concept of cancellation baked in. If the user cancels something then typically you don’t want to continue a promise chain, but you don’t want to show an error message either. So what is cancellation? It’s not success and it’s not failure, but it should handle more like an error, ie. it should skip all the subsequent then handlers. PromiseKit embodies cancellation as a special kind of error.

According to this you are going to skip all the subsequent then handlers.
Here is the link where I found this information : Promise Kit

ContentLicense: CC BY-SA 3.0

Title: PromiseKit go back one step

Body:
I have a series of UIViewControllers (popups) in my app that I use to gather information from the end user. I managed to chain them with promises like this:

firstly {
        return showFirstPopup()
    }
    .then { info1 -> Promise<Info2> in
        dismissFirstPopup()
        //Do sth with info1...
        return showSecondPopup()
    }
    .then { info2 -> Promise<Info3> in
        dismissSecondPopup()
        //Do sth with info2...
        return showThirdPopup()
    }
    .then { info3 -> Promise<Info4> in
        dismissThirdPopup()
        //Do sth with info3...
        return showForthPopup()
    }
    ...
    .catch { error in
        //Handle any error or cancellation...
     }

If, for example, the user presses back in the third popup I need to go back to the previous "then" and not cancel the whole flow.

Basically I need to be able to go back one step, let the user edit the data, then continue the flow.

Is there a way to do this with PromiseKit?


问:
Why can't I access array inside forEach() in javascript
I'm not sure why i can't access the allSubIABs array inside forEach.
I can access the string newCheckState fine.

```<code>const newIABs = { ...this.state.iabs }
let allSubIABs = []
let newCheckState = 'asdasdasd'

console.log(typeof allSubIABs, allSubIABs)
Object.keys(newIABs).forEach(firstLevelIABCode => {
  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  let allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})
</code>```

Output:

```<code>object []
asdasdasd
undefined undefined
Uncaught TypeError: Cannot read property 'concat' of undefined
</code>```

答:
Your let allSubIABs declaration declares a new variable whose default value is undefined, and this new variable shadows access to the outer allSubIABs with the same name.

You can see how hoisting affects your function. This code is equivalent to your own:

```<code>Object.keys(newIABs).forEach(firstLevelIABCode => {
  let allSubIABs;

  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})
</code>```

As you can see, variable declarations happen first (this is what "hoisting" means) and newly-declared variables hold the value undefined until assigned a value.

Consider analogously var a = a.foo; which produces the error Cannot read property 'foo' of undefined because a does exists as a variable, but it has never been given a value.

Since you actually want to access the outer allSubIABs variable, do not declare a new variable with let. This will cause allSubIABs variable tokens to refer to the nearest outer-scope variable of that name, which is what you want.

Body:
I'm not sure why i can't access the allSubIABs array inside forEach.
I can access the string newCheckState fine.

const newIABs = { ...this.state.iabs }
let allSubIABs = []
let newCheckState = 'asdasdasd'

console.log(typeof allSubIABs, allSubIABs)
Object.keys(newIABs).forEach(firstLevelIABCode => {
  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  let allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})

Output:

object []
asdasdasd
undefined undefined
Uncaught TypeError: Cannot read property 'concat' of undefined

Body:
Your let allSubIABs declaration declares a new variable whose default value is undefined, and this new variable shadows access to the outer allSubIABs with the same name.

You can see how hoisting affects your function. This code is equivalent to your own:

Object.keys(newIABs).forEach(firstLevelIABCode => {
  let allSubIABs;

  console.log(newCheckState)
  console.log(typeof allSubIABs, allSubIABs)
  allSubIABs = allSubIABs.concat(newIABs[firstLevelIABCode].children)
})

As you can see, variable declarations happen first (this is what "hoisting" means) and newly-declared variables hold the value undefined until assigned a value.

Consider analogously var a = a.foo; which produces the error Cannot read property 'foo' of undefined because a does exists as a variable, but it has never been given a value.

Since you actually want to access the outer allSubIABs variable, do not declare a new variable with let. This will cause allSubIABs variable tokens to refer to the nearest outer-scope variable of that name, which is what you want.


问:
Installing Django when Python is already installed through Anaconda?
I am having the common issue when trying to run:

```<code>django-admin startproject hellodjango
</code>```

that I am getting the error:

```<code>'django-admin' is not recognized as an internal or external command, operable program or batch file.
</code>```

I have run:

```<code>pip install Django
</code>```

Which ran successfully. However, when I navigate to my C:\Python 3\Scripts folder, I don't see any djangoadmin.py or related files in there.

Python 3 is added as a PATH environmental variable.

When I run:

```<code>python --version
</code>```

I get the following:

```<code>Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39)
</code>```

Could my issue potentially be that my version of python is actually within the Anaconda package, rather than an explicit standalone python installation? (Just a guess as i'm not sure where i'm going wrong).

答:
Django-admin is probably missing from your path in that case...

You could try running with the full path. C:\Python 3\site-packages\django\bin\django-admin

To fix, edit your path to include the path above.

Body:
I am having the common issue when trying to run:

django-admin startproject hellodjango

that I am getting the error:

'django-admin' is not recognized as an internal or external command, operable program or batch file.

I have run:

pip install Django

Which ran successfully. However, when I navigate to my C:\Python 3\Scripts folder, I don't see any djangoadmin.py or related files in there.

Python 3 is added as a PATH environmental variable.

When I run:

python --version

I get the following:

Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39)

Could my issue potentially be that my version of python is actually within the Anaconda package, rather than an explicit standalone python installation? (Just a guess as i'm not sure where i'm going wrong).


问:
onclick not firing if element is reinserted into DOM mid-click
I made a simple popup manager, which used the dom to decide which popup should be in front, without any z-index rule : when I click on a popup, it's moved in first position, so it is on top of the other popup. Unfortunately : this dom movement breaks the onclick event in my popup.

I made a simple case of the issue : the following code should output the three click events : mousedown, mouseup and click, it works on Firefox, and I think it used to work in previous versions of Chrome, but it doesn't anymore.

Click

```

Do you know how can I fix this issue, and get back my onclick event ?

答:
If reinserting an element into the DOM stops its click event from firing, then the other option would be to move its siblings.

This seems to work (I recommend viewing in full page mode because the console output will interrupt the events if it covers up a div you've just clicked):

function moveToFront(el) {
  var parent = el.parentElement;

  while (el.nextSibling) {
    parent.insertBefore(el.nextSibling, el);
  }
}

[].slice.call(document.getElementsByClassName('moveable')).forEach(function(el) {
  el.addEventListener('mousedown', function() {
    console.log('mousedown', this.id);
    moveToFront(this);
  });
  el.addEventListener('mouseup', function() {
    console.log('mouseup', this.id);
  });
  el.addEventListener('click', function() {
    console.log('click', this.id);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.moveable {
  width: 100px;
  height: 100px;
  position: absolute;
}

#div1 {
  background-color: green;
  top: 10px;
  left: 10px;
}

#div2 {
  background-color: red;
  top: 40px;
  left: 40px;
}

#div3 {
  background-color: yellow;
  top: 20px;
  left: 70px;
}</code>```

Click

Click

Click

```

Body:
I made a simple popup manager, which used the dom to decide which popup should be in front, without any z-index rule : when I click on a popup, it's moved in first position, so it is on top of the other popup. Unfortunately : this dom movement breaks the onclick event in my popup.

I made a simple case of the issue : the following code should output the three click events : mousedown, mouseup and click, it works on Firefox, and I think it used to work in previous versions of Chrome, but it doesn't anymore.

Click

Do you know how can I fix this issue, and get back my onclick event ?

Body:
If reinserting an element into the DOM stops its click event from firing, then the other option would be to move its siblings.

This seems to work (I recommend viewing in full page mode because the console output will interrupt the events if it covers up a div you've just clicked):

function moveToFront(el) {
  var parent = el.parentElement;

  while (el.nextSibling) {
    parent.insertBefore(el.nextSibling, el);
  }
}

[].slice.call(document.getElementsByClassName('moveable')).forEach(function(el) {
  el.addEventListener('mousedown', function() {
    console.log('mousedown', this.id);
    moveToFront(this);
  });
  el.addEventListener('mouseup', function() {
    console.log('mouseup', this.id);
  });
  el.addEventListener('click', function() {
    console.log('click', this.id);
  });
});

.moveable {
  width: 100px;
  height: 100px;
  position: absolute;
}

#div1 {
  background-color: green;
  top: 10px;
  left: 10px;
}

#div2 {
  background-color: red;
  top: 40px;
  left: 40px;
}

#div3 {
  background-color: yellow;
  top: 20px;
  left: 70px;
}

<div>
  <div id="div1" class="moveable">Click</div>
  <div id="div2" class="moveable">Click</div>
  <div id="div3" class="moveable">Click</div>
</div>


问:
Creating a graph based on specific conditions
I have a question that asks me to make a graph such that the BFS and DFS trees from the graph is not a minimum spanning tree and the order of the adjacency list does not matter, I know the properties of BFS DFS and MST but I'm a confused by the question. How should I be approaching the problem? (not looking for the solution)</p>

答:
My suggestion would be to look at an algorithm for finding the MST from a graph, and think about why it is not just a BFS or DFS search.

For any algorithm, finding an edge case that actually tests the tricky parts is an important part of implementation. You could start with a simple example, and try adding new edges or altering the input in a way that would make a simple BFS/DFS search fail.

The condition that it should be independent of the adjacency list order is to ensure that your test graph has a truly hard structure, not just that you have artificially fed the edges to the algorithm in a way that makes it fail.


问:
Why is `exec()` not working in a script but working interactively?
I'm reading in a credentials file to a string and then running exec() on that string to make the various credentials available as variables. The credentials file contains text like the following:

```<code>customer_number = "9999999999"
PIN             = "9999999999"
passcode        = "9999999999"
account_code    = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
</code>```

This works in interactive Python (with the variables becoming available) but fails in a script. Why is this and how can I get it to work?

```<code>with open(filepath_credentials, "r") as file_credentials:
    credentials = file_credentials.read()
    exec(credentials)
print(customer_number)
</code>```

答:
You need to pass the globals() (and possibly also locals()) collection to exec():

```<code>exec(credentials, globals())
</code>```

This allows exec() to modify your script's global variables. The Python interactive interpreter works slightly differently here.

Body:
I'm reading in a credentials file to a string and then running exec() on that string to make the various credentials available as variables. The credentials file contains text like the following:

customer_number = "9999999999"
PIN             = "9999999999"
passcode        = "9999999999"
account_code    = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

This works in interactive Python (with the variables becoming available) but fails in a script. Why is this and how can I get it to work?

with open(filepath_credentials, "r") as file_credentials:
    credentials = file_credentials.read()
    exec(credentials)
print(customer_number)

Body:
You need to pass the globals() (and possibly also locals()) collection to exec():

exec(credentials, globals())

This allows exec() to modify your script's global variables. The Python interactive interpreter works slightly differently here.


问:
How to use redis store in express session using connect-redis?
I am trying to look for a tutorial that explains your how to setup user session in redis store using express session. I know how to set it up, but I could not find out how to access redis store and how to store and retrieve values from that redis store?</p>

答:
I'm assuming you want to store and read values from the session (using the express-session module) and not use redis directly. For this you'll want to use the req.session object in a request.

Checkout the functions here in the documentation - https://github.com/expressjs/session#reqsession

If you're trying to store some values directly into redis (perhaps using redis for multiple things) then checkout https://www.npmjs.com/package/redis


问:
Bad output - array(1) { ["description"]=> string(0) "" }
how can i get good output of this script:
Source JSON: https://ufile.io/sn0hu

I need get values into array and in the next step take into variables.
Values is result->data->tab->unified_content->item (type->text if header = title and if text = description)

Script:

```<code>function getContent($data) {
    $tabs = $data->result->data->tab;
    foreach($tabs as $tab){
        $content = [];
        if(isset($tab->unified_content->item)) {
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr = [];
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
            return $content;
        }
    }
}

$test = getContent($data);
foreach ($test as $lol) {
    var_dump($lol);
}
</code>```

Now is output this: array(1) { ["description"]=> string(0) "" }

答:
Please next time make it clear what it is you're looking for (what is a "good output"?).

Use json_decode($json_file ,true).
Ie:

```<code><?php

$json_file = file_get_contents("testing.json");
$json_decode = json_decode($json_file, true); //Sets it as an array

print_r($json_decode['result']['status']); //Will print out "done" in this case

?>
</code>```

Again, this might not be the answer you're looking for since it  wasn't exactly clear what it was you're looking for in the OP.

Body:
how can i get good output of this script:
Source JSON: https://ufile.io/sn0hu

I need get values into array and in the next step take into variables.
Values is result->data->tab->unified_content->item (type->text if header = title and if text = description)

Script:

function getContent($data) {
    $tabs = $data->result->data->tab;
    foreach($tabs as $tab){
        $content = [];
        if(isset($tab->unified_content->item)) {
            foreach($tab->unified_content->item as $item) {
                if($item->type->name == 'header') {
                    $arr = [];
                    $arr['title'] = $item->text;
                } else {
                    $arr['description'] = $item->text;
                    $content[] = $arr;
                }
            }
            return $content;
        }
    }
}

$test = getContent($data);
foreach ($test as $lol) {
    var_dump($lol);
}

Now is output this: array(1) { ["description"]=> string(0) "" }

Body:
Please next time make it clear what it is you're looking for (what is a "good output"?).

Use json_decode($json_file ,true).
Ie:

<?php

$json_file = file_get_contents("testing.json");
$json_decode = json_decode($json_file, true); //Sets it as an array

print_r($json_decode['result']['status']); //Will print out "done" in this case

?>

Again, this might not be the answer you're looking for since it  wasn't exactly clear what it was you're looking for in the OP.


答:
Try using createMany method. Do it like this. You can refer docs.</p>

```<code>$page = Page::create($request->only('name'));

$page->blocks()->createMany($request->get('blocks'));
</code>```

Title: Laravel Eloquent One-To-Many

Body:
Try using createMany method. Do it like this. You can refer docs.

$page = Page::create($request->only('name'));

$page->blocks()->createMany($request->get('blocks'));


问:
Testing with Firesbase in Android Studio JUnit Test
Firebase totally works fine in my Android Studio, but it crashes when I try to test it with it.

```<code>public class ExampleUnitTest {

    DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
    DatabaseReference tournamentReference = rootReference.child("Tournaments");
    DatabaseReference matchReference = tournamentReference.child("Test Tournament").child("Matches");

    @Test
    public void addition_isCorrect() throws Exception {

        DatabaseReference testReference = matchReference.child("Nov 13, 2017 Team Eagles vs Team Tigers");

        testReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    assertEquals(snapshot.child("fieldName").getValue().toString(), "UIUC Sixpack Field");
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

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

In this test case, it gives me an error :

```<code>java.lang.ExceptionInInitializerError
    at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
    at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
</code>```

Is there a way to solve make it work?

答: This is happening because the json file does not exists in the right place. Redownload google-services.json file from Project Settings in the Firebase console and put it in the right place in your project.

Body:
Firebase totally works fine in my Android Studio, but it crashes when I try to test it with it.

public class ExampleUnitTest {

    DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
    DatabaseReference tournamentReference = rootReference.child("Tournaments");
    DatabaseReference matchReference = tournamentReference.child("Test Tournament").child("Matches");

    @Test
    public void addition_isCorrect() throws Exception {

        DatabaseReference testReference = matchReference.child("Nov 13, 2017 Team Eagles vs Team Tigers");

        testReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    assertEquals(snapshot.child("fieldName").getValue().toString(), "UIUC Sixpack Field");
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

In this test case, it gives me an error :

java.lang.ExceptionInInitializerError
    at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
    at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)

Is there a way to solve make it work?


问:
Laravel Accessing data from Redis set with Pipeline
I have stored some data using using Redis in my Laravel project. It used a foreach loop to store each array row, and then I used Redis Pipeline store the each row as well. pipeline example My question is: how do I use a  foreach Loop to access all the data in Redis? My example just shows how to access one. </p>

```<code>$devicename_for_single_key = Redis::get('device_name:12345');
</code>```

答:
okay I think I found my answer for my Laravel project. this will return an array.</p>

```<code>        $redis = Redis::connection();
        $allKeys = $redis->keys('*');
</code>```

Body:
I have stored some data using using Redis in my Laravel project. It used a foreach loop to store each array row, and then I used Redis Pipeline store the each row as well. pipeline example My question is: how do I use a  foreach Loop to access all the data in Redis? My example just shows how to access one.

$devicename_for_single_key = Redis::get('device_name:12345');

Body:
okay I think I found my answer for my Laravel project. this will return an array.

        $redis = Redis::connection();
        $allKeys = $redis->keys('*');


问:
php7 display document stored in mongodb 3.4
I am very new to php and mongodb. I have installed php7.0 and mongo 3.4.10 on Ubuntu 16.04.3 LTS.

I can display desired document by entering mongo cli command:
    db.testcollection.find({_id:'superid'}).pretty()

It gives me this result:

{ "_id" : "superid", "record" : "whatever" }

But I am tryig to display document from mongodb collection with this php script:

```<code>    <?php

    $mongo = new \MongoDB\Driver\Manager();
    $filter = ['_id' => 'superid'];
    $options = [];
    $query = new \MongoDB\Driver\Query($filter, $options);
    $rows = $mongo->executeQuery('db.testcollection', $query);
    foreach ($rows as $document) {
      print_($document);
      var_dump($document);
      echo $document;
    }

    echo "The END"
    ?>
</code>```

This only display "The END".

What I am missing in my php script to display mongo query result similarly as cli command?

答:
The problem was:
I have created new databse called test using this commands in mongo shell:

```<code>use test;
db.createCollection("testcollection");
db.testcollection.insert({ "_id" : "superid", "record" : "whatever"});
</code>```

So path to db was test.testcollection not db.testcollection.

When I correct appropriate line like this:

```<code> $rows = $mongo->executeQuery('test.testcollection', $query);
</code>```

It works as expected.

I was confused by mongo shell (cli) that gives me right result without need to specify database name (even after logoff mongo shell and login again).

On the other hand you must specify dbname.collectionname in php (what makes sense) :)

Body:
I am very new to php and mongodb. I have installed php7.0 and mongo 3.4.10 on Ubuntu 16.04.3 LTS.

I can display desired document by entering mongo cli command:
    db.testcollection.find({_id:'superid'}).pretty()

It gives me this result:

{ "_id" : "superid", "record" : "whatever" }

But I am tryig to display document from mongodb collection with this php script:

    <?php

    $mongo = new \MongoDB\Driver\Manager();
    $filter = ['_id' => 'superid'];
    $options = [];
    $query = new \MongoDB\Driver\Query($filter, $options);
    $rows = $mongo->executeQuery('db.testcollection', $query);
    foreach ($rows as $document) {
      print_($document);
      var_dump($document);
      echo $document;
    }

    echo "The END"
    ?>

This only display "The END".

What I am missing in my php script to display mongo query result similarly as cli command?

Body:
The problem was:
I have created new databse called test using this commands in mongo shell:

use test;
db.createCollection("testcollection");
db.testcollection.insert({ "_id" : "superid", "record" : "whatever"});

So path to db was test.testcollection not db.testcollection.

When I correct appropriate line like this:

 $rows = $mongo->executeQuery('test.testcollection', $query);

It works as expected.

I was confused by mongo shell (cli) that gives me right result without need to specify database name (even after logoff mongo shell and login again).

On the other hand you must specify dbname.collectionname in php (what makes sense) :)


问:
Need to create a queue to run process for one person at a time
I lack the knowledge to even know where to start researching this topic (such as keywords to use) so I'm hoping somebody can help point me in the right direction.

I have an .NET MVC application. In this application, the user uploads a zip file with a data layer and that data layer is used as input in a python script the application calls. Due to the nature of the database cursors (it's an ArcGIS Enterprise geodatabase if anyone is familiar) only one person can run the python script at a time as the cursors make exclusive locks on the database (there is no way around this). In the extremely rare chance that two people are trying to use this web application at the same time, I need to put the people in a queue so the python script completes for the first person and then starts on the next person's dataset. Where do I get started with this, or what words can you give me to start formulating some search queries on this topic?

答:
Maybe there are more technology specific solutions will come, but from my first view, you can use priority queue style processing.

It can be as simple as creating a table and enqueue (insert) new requests over there and process as it comes (dequeue). Or, use higher level framework like RabbitMQ

So, every time when new zip file comes,

Upload in repository

Insert new record in the queue

Get first item from queue

Process

If second person uploads new file, you will check queue table, there will be flag last item is getting processed, then you can let client know, script is queued and will be processed.

Obviously it will be worth to generate unique id of client, then you will not mix priorities and scripts, if there are multiple uploads at the same time.


问:
super.super.func()? - Java polymorphism
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?

I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().

Edit:
Thanks everyone; 'Skeen is back at the drawing board'.

答:
Why don't you have func() be not inherited (call it funcBase() or whatever) and then add a wrapper func() function that calls it?

```<code>class A{
    public void funcBase() {
        // Base implementation
        }
    public void func() {
        funcBase();
    }
}

class B extends A{
    public void func(){
         super.func();
 }
}

class C extends B{
    public void foo(){
         super.func();   // Call B's func
         funcBase();     // Call A's func
    }
}
</code>```

I have no idea what you're trying to do, but it sounds like your class design is not appropriate for what you want, so you may want separate functions in A instead of trying to sneak your way up the ladder.

ContentLicense: CC BY-SA 2.5

Title: super.super.func()? - Java polymorphism

Body:
Why don't you have func() be not inherited (call it funcBase() or whatever) and then add a wrapper func() function that calls it?

class A{
    public void funcBase() {
        // Base implementation
        }
    public void func() {
        funcBase();
    }
}

class B extends A{
    public void func(){
         super.func();
 }
}

class C extends B{
    public void foo(){
         super.func();   // Call B's func
         funcBase();     // Call A's func
    }
}

I have no idea what you're trying to do, but it sounds like your class design is not appropriate for what you want, so you may want separate functions in A instead of trying to sneak your way up the ladder.


问:
VBA For Each with nested For Each
I have written a For each loop that I want to go through the range and test for the first condition and add the value to a combobox. ONLY If it cannot find that condition then I want it to execute the second for each loop and add all the values that match the condition.

I have written the below code and it says

Else without If

even though there is an IF

```<code> Dim Keys As Range, cell As Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Else
      For Each cell In Keys
      If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Next cell

 Next cell
 Set Keys = Nothing
</code>```

答:
For anyone that's interested I fixed this by adding a do while loop to the beginning that tested for the 1st condition this populated the combobox exited the sub if found or ran the for each loop and adds all the matched values.</p>

```<code>    Dim Keys As Range, cell As Range, userName As Variant

userName = WindowsUserName

ThisWorkbook.Worksheets("keyHistory").Range("A2").Select

Do While ActiveCell.Value <> ""
        If ActiveCell.Value = userName And ActiveCell.Offset(0, 2) <> "" And ActiveCell.Offset(0, 4) = 1 Then
        Me.ComboBox1.AddItem ActiveCell.Value
        Set userName = Nothing
        Exit Sub

        Else
        ActiveCell.Offset(1, 0).Select
        End If
Loop

Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

For Each cell In Keys
If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
Next cell

 Set Keys = Nothing

 Set userName = Nothing

 Set cell = Nothing
</code>```

Title: VBA For Each with nested For Each

Body:
I have written a For each loop that I want to go through the range and test for the first condition and add the value to a combobox. ONLY If it cannot find that condition then I want it to execute the second for each loop and add all the values that match the condition.

I have written the below code and it says

Else without If

even though there is an IF

 Dim Keys As Range, cell As Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Else
      For Each cell In Keys
      If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Next cell

 Next cell
 Set Keys = Nothing

Body:
For anyone that's interested I fixed this by adding a do while loop to the beginning that tested for the 1st condition this populated the combobox exited the sub if found or ran the for each loop and adds all the matched values.

    Dim Keys As Range, cell As Range, userName As Variant

userName = WindowsUserName

ThisWorkbook.Worksheets("keyHistory").Range("A2").Select

Do While ActiveCell.Value <> ""
        If ActiveCell.Value = userName And ActiveCell.Offset(0, 2) <> "" And ActiveCell.Offset(0, 4) = 1 Then
        Me.ComboBox1.AddItem ActiveCell.Value
        Set userName = Nothing
        Exit Sub

        Else
        ActiveCell.Offset(1, 0).Select
        End If
Loop

Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

For Each cell In Keys
If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
Next cell

 Set Keys = Nothing

 Set userName = Nothing

 Set cell = Nothing


问:
how to create a singular model and table in laravel
I am an absolute beginner in laravel now I undertsand the concept that laravel creates singular model and plural table name e.g

```<code>php artisan make:model Admin -m

php artisan migrate
</code>```

now this will create a model named Admin and a database named admins now logically I don't have a issue with that but it doesn't look clean if there is only one admin why need to have the table name as admins? Shouldn't it be admin? Is there any workaround for that or do I have to just stick with admins?

答:
If you don't want to use the default name for the table, you can overwrite it in your model:</p>

```<code>class Admin extends Model {
    protected $table = 'admin';
}
</code>```

Body:
I am an absolute beginner in laravel now I undertsand the concept that laravel creates singular model and plural table name e.g

php artisan make:model Admin -m

php artisan migrate

now this will create a model named Admin and a database named admins now logically I don't have a issue with that but it doesn't look clean if there is only one admin why need to have the table name as admins? Shouldn't it be admin? Is there any workaround for that or do I have to just stick with admins?

Body:
If you don't want to use the default name for the table, you can overwrite it in your model:

class Admin extends Model {
    protected $table = 'admin';
}


问:
Split Excel worksheet using Python
I have excel files (hundreds of them) that look like this (sensor output):

```<code>Column1          Column2    Column3

Serial Number:
10004
Ref. Temp:
25C
Ref. Pressure:
1KPa
Time              Temp.     Pres.
1                 21        1
2                 22        1.1
3                 23        1.2
.                 .         .
.                 .         .
.                 .         .
</code>```

I want to split this into two parts, the information section (top part) and data section (the rest), something like this:

Information section

```<code>Column1          Column2    Column3

Serial Number:
10004
Ref. Temp:
25C
Ref. Pressure:
1KPa
</code>```

Data section:

```<code>Column1      Column2    Column3
Time          Temp.     Pres.
1              21       1
2              22       1.1
3              23       1.2
.              .            .
.              .            .
.              .            .
</code>```

if it converts to data frame I don't want the first row and column become header and index of the data frame. I am using python 2.7 and numpy.

答:
Make two copies of the worksheet.

In copy A, start a loop, going on the first column looking for the word Time. Once it finds it, let it delete anything before it.

Remember the row in a variable.

In copy B, delete anything after the remembered row to row number 2^20.

Title: Split Excel worksheet using Python

Body:
I have excel files (hundreds of them) that look like this (sensor output):

Column1          Column2    Column3

Serial Number:
10004
Ref. Temp:
25C
Ref. Pressure:
1KPa
Time              Temp.     Pres.
1                 21        1
2                 22        1.1
3                 23        1.2
.                 .         .
.                 .         .
.                 .         .

I want to split this into two parts, the information section (top part) and data section (the rest), something like this:

Information section

Column1          Column2    Column3

Serial Number:
10004
Ref. Temp:
25C
Ref. Pressure:
1KPa

Data section:

Column1      Column2    Column3
Time          Temp.     Pres.
1              21       1
2              22       1.1
3              23       1.2
.              .            .
.              .            .
.              .            .

if it converts to data frame I don't want the first row and column become header and index of the data frame. I am using python 2.7 and numpy.


问:
How to check in PHP 5.4 if an access path exists in a multidimensional JSON array?
I want to access elements in an array generated by json_encode and want to be sure the element exists. To suppress a warning if it does not exist I use a @ prior:

1) When access path in array exists all works as expected

```<code>$test = @$obj['tag']
// result is "ABCD" if "ABCD" set, "" if "" and NULL if NULL => as
</code>```

expected

2) When access path in array only partial exists Strings cause a problem

```<code>$test = @$obj['tag']['dddd']
// = "A" when ['tag'] = "ABCD", I understand that 'dddd' becomes an index of 0 in the array representing the string.
</code>```

Any way to avoid this?

答:
After trying out isset / is_scalar / is_null / empty I came to the followig conclusion for multidimensional arrays generated out of JSON data:

1) isset() does not distinguish between the value "null" with an existing key and a not existing key (I used @ for the access path to suppress warnings). "" strings are handled fine.

2) There is one anomaly if an access path contains a string. In this case the first character of the string will be the result. It does not matter how many dimensions come after the string. Will always reference the 0 index of the string array.

To avoid any problems I do now:
1) Use no null in JSON, what is a good idea anyway.
2) Avoid strings with a single char. If needed instead of Y/N using a boolean true/false could be used.

Test data:

isset is_scalar is_null empty access path                  value
TRUE  TRUE      FALSE   FALSE @$obj['tag']['dddd']['wwww'] A (not existing)
TRUE  TRUE      FALSE   FALSE @$obj['tag']['dddd']         A (not existing)
TRUE  TRUE      FALSE   FALSE @$obj['tag']                 ABCD
TRUE  TRUE      FALSE   FALSE @$obj['tagf']                ABCD
TRUE  TRUE      FALSE   FALSE @$obj['user']['name']        Broemm
TRUE  TRUE      FALSE   FALSE @$obj['user']['num']         1234
FALSE FALSE     TRUE    TRUE  @$obj['user']['num']['dddd’] (not existing)
TRUE  TRUE      FALSE   TRUE  @$obj['time']['b']['b’]      “"
FALSE FALSE     TRUE    TRUE  @$obj['time']['c']['b’]      null
FALSE FALSE     TRUE    TRUE  @$obj['tttt’]                (not existing)
TRUE  TRUE      FALSE   FALSE @$obj['boo']                 1
FALSE FALSE     TRUE    TRUE  @$obj['boo']['qq']           (not existing)
FALSE FALSE     TRUE    TRUE  @$obj['boo']['qq']['ee’]     (not existing)

Body:
I want to access elements in an array generated by json_encode and want to be sure the element exists. To suppress a warning if it does not exist I use a @ prior:

1) When access path in array exists all works as expected

$test = @$obj['tag']
// result is "ABCD" if "ABCD" set, "" if "" and NULL if NULL => as

expected

2) When access path in array only partial exists Strings cause a problem

$test = @$obj['tag']['dddd']
// = "A" when ['tag'] = "ABCD", I understand that 'dddd' becomes an index of 0 in the array representing the string.

Any way to avoid this?


问:
Coordinates in Blend 4 Layouts?
I'm new to Blend 4 and I'm wondering why the Grid layout seems to have it's (0, 0) position in the lower-right corner instead of the upper-left corner ? Can I change it ? Because I want to set Rows/Cols height/width relative to the upper-left corner</p>

答:
The Grid Panel's row/columns do pertain to the upper-left corner.  Here's a short tutorial on layout controls in Silverlight by Scott Gu:

http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-2-using-layout-management.aspx

Sometimes when working with Blend it will set crazy margins on controls which make them appear to be in different columns.  I would look at the xaml and ensure there's no other properties (margin, padding, transforms) that are making the control appear to be somewhere else in the layout.

Title: Coordinates in Blend 4 Layouts?


问:
Scheme :Why am i getting this error -assertion-violation: argument of wrong type [car] (car '())
my function in scheme is trying to get the province details:

```<code>(define (getProvincesHelper sales provincesList)

  (if (null? sales)

      provincesList

      ( getProvincesHelper (cdr sales) (append  (list (cadr(cadddr sales))) provincesList))

  )
)

(define (getProvinces sales)

 (getProvincesHelper sales '())

)
</code>```

The list of data is in this format

```<code>;(orderNum (orderDate shipDate) (grossSale discount profit unitPrice) (deliveryMethod province) product)

(3 ("10/13/2010" "10/20/2010") (261.54 0.04 -213.25 38.94) ("Regular Air" "Nunavut") "Eldon Base for stackable storage shelf, platinum")
</code>```

I get the error:

```<code>assertion-violation: argument of wrong type [car]
                     (car '())
</code>```

答:
If you have bigger list or tree like structures, you can use list-ref. It takes a list and returns the nth element starting with 0.

If you want to get "Nunavut" from your example list, you have to take the 4th element, which is again a list. And the car of the cdr of this element is the result.

Example:

```<code>;;        (orderNum (orderDate    shipDate)     (grossSale discount profit  unitPrice) (deliveryMethod province)  product)
(let ((l '(3        ("10/13/2010" "10/20/2010") (261.54    0.04     -213.25 38.94)     ("Regular Air"  "Nunavut") "Eldon Base for stackable storage shelf, platinum")))
  (cadr (list-ref l 3)))
</code>```

Body:
my function in scheme is trying to get the province details:

(define (getProvincesHelper sales provincesList)

  (if (null? sales)

      provincesList

      ( getProvincesHelper (cdr sales) (append  (list (cadr(cadddr sales))) provincesList))

  )
)

(define (getProvinces sales)

 (getProvincesHelper sales '())

)

The list of data is in this format

;(orderNum (orderDate shipDate) (grossSale discount profit unitPrice) (deliveryMethod province) product)

(3 ("10/13/2010" "10/20/2010") (261.54 0.04 -213.25 38.94) ("Regular Air" "Nunavut") "Eldon Base for stackable storage shelf, platinum")

I get the error:

assertion-violation: argument of wrong type [car]
                     (car '())

Body:
If you have bigger list or tree like structures, you can use list-ref. It takes a list and returns the nth element starting with 0.

If you want to get "Nunavut" from your example list, you have to take the 4th element, which is again a list. And the car of the cdr of this element is the result.

Example:

;;        (orderNum (orderDate    shipDate)     (grossSale discount profit  unitPrice) (deliveryMethod province)  product)
(let ((l '(3        ("10/13/2010" "10/20/2010") (261.54    0.04     -213.25 38.94)     ("Regular Air"  "Nunavut") "Eldon Base for stackable storage shelf, platinum")))
  (cadr (list-ref l 3)))


问:
Is there a way to tell if the soft-keyboard is shown?
is there a way to tell if the softkeyboard is shown in an activity or not?

I tried

```<code>InputMethodManager manager = (InputMethodManager)
getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
manager.isActive(v)
</code>```

but isActive returns false only before the first time the keyboard is shown, but if the kb appears and then dismissed, isActive returns true also.

so is there any other method to check for this issue.

thanks

答:
This is my idea. It is untested.</p>

```<code>@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks whether a keyboard is available which is not hard keyboard
        if ((newConfig.keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)&&(newConfig.keyboardHidden != Configuration.KEYBOARDHIDDEN_NO)) {
            Toast.makeText(this, "soft keyboard visible", Toast.LENGTH_SHORT).show();
        } else if (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "soft keyboard hidden", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

Body:
is there a way to tell if the softkeyboard is shown in an activity or not?

I tried

InputMethodManager manager = (InputMethodManager)
getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
manager.isActive(v)

but isActive returns false only before the first time the keyboard is shown, but if the kb appears and then dismissed, isActive returns true also.

so is there any other method to check for this issue.

thanks

Body:
This is my idea. It is untested.

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks whether a keyboard is available which is not hard keyboard
        if ((newConfig.keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)&&(newConfig.keyboardHidden != Configuration.KEYBOARDHIDDEN_NO)) {
            Toast.makeText(this, "soft keyboard visible", Toast.LENGTH_SHORT).show();
        } else if (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "soft keyboard hidden", Toast.LENGTH_SHORT).show();
        }
    }

ContentLicense: CC BY-SA 4.0


问:
How to center text in a row using Bootstrap 4
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

```<code><div class="container">
  <div class="row" id="appSummary">
    <h1>Why This App Is Awesome</h1>
    <p class="lead">Summary, once again, of your app's awesomeness</p>
  </div>
</div>
</code>```

CSS

```<code>#appSummary{
  text-align:center;
}
</code>```

答:
Since you're using Bootstrap 4 which uses the flex model, change your CSS rule to:

```<code>#appSummary{
    justify-content:center;
}
</code>```

Bootply example

Body:
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

Why This App Is Awesome

Summary, once again, of your app's awesomeness

CSS

#appSummary{
  text-align:center;
}

Body:
Since you're using Bootstrap 4 which uses the flex model, change your CSS rule to:

#appSummary{
    justify-content:center;
}

Bootply example


问:
How to center image in a uiimageview/uiscrollview (pre and post zooming)
I am trying to center an image (with respect to the iphone screen) such that when the view is loaded the image is center width/height... In my case my view is loaded at pixel points 0,0 of the image itself and if I zoom out the image appears in the top left corner as opposed to mid-center of the screen/view. Here is what I have so far:

```<code>UIImage *image = [UIImage imageNamed: @"t.bmp"];
self.view.backgroundColor = [UIColor blackColor];
self.mi.frame = CGRectMake(0, 0, image.size.width, image.size.height);
self.mi.contentMode = (UIViewContentModeCenter);
self.mi.backgroundColor = [UIColor blackColor];
[self.mi setImage:image];

/* Draw a line here!!
UIGraphicsBeginImageContext(self.mi.frame.size);
[self.mi.image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 20.0);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0,0);
CGContextAddLineToPoint(context, 200, 200);
CGContextMoveToPoint(context, 200,0);
CGContextAddLineToPoint(context, 0, 200);
CGContextStrokePath(context);
self.mi.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
*/

self.expimg.maximumZoomScale = 2.0;
self.expimg.minimumZoomScale = 0.1;
self.expimg.clipsToBounds = YES;
self.expimg.delegate = self;
[self.expimg setContentSize:self.mi.frame.size];

[self.expimg addSubview: self.mi];
[self.view addSubview: self.expimg];
</code>```

Thanks!

Edit: mi is a UIImageView and expimg is a UIScrollView (used interface builder). Also, viewForZoomingInScrollView is defined.

答:
Step 1: You create an image view property then init it at viewDidLoad and add to scrollView:

```<code>self.pictureImage = [[UIImageView alloc]initWithImage:self.picture];
[_scrollView addSubview:_pictureImage];
self.pictureImage.alpha = 0;
_scrollView.delegate = self;
</code>```

Step 2: Create adjustZoomScale function to get minimum scale

```<code>- (CGFloat)adjustZoomScale{
CGFloat scale = self.scrollView.bounds.size.width / self.pictureImage.bounds.size.width;
CGFloat h = scale * self.pictureImage.bounds.size.height;
if (h > self.scrollView.bounds.size.height) {
    scale = self.scrollView.bounds.size.height / self.pictureImage.bounds.size.height;
}
return scale;
}
</code>```

Step 3: Because frame of scroll view will be updated at viewDidAppear so we need to adjust zoom scale here. And set alpha to make image appear smoother:

```<code>- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear: animated];
_scrollView.maximumZoomScale = 1.0;
_scrollView.minimumZoomScale = [self adjustZoomScale];
[_scrollView setZoomScale:_scrollView.minimumZoomScale];
self.pictureImage.alpha = 1;
}
</code>```

Step 4: Implement viewForZoomingInScrollView (scroll delegate method) and return image view

```<code>- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return self.pictureImage;
}
</code>```

Step 5: Implement scrollViewDidZoom (scroll delegate method) and adjust point for image view

```<code>- (void)scrollViewDidZoom: (UIScrollView*) scrollView {
CGSize boundsSize = scrollView.bounds.size;
CGRect contentsFrame = _pictureImage.frame;

if (contentsFrame.size.width < boundsSize.width) {
    contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0;
} else {
    contentsFrame.origin.x = 0.0;
}

if (contentsFrame.size.height < boundsSize.height) {
    contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0;
} else {
    contentsFrame.origin.y = 0.0;
}
_pictureImage.frame = contentsFrame;
}
</code>```

Thank shawhu at this post for point adjusting for image view while zooming

Body:
I am trying to center an image (with respect to the iphone screen) such that when the view is loaded the image is center width/height... In my case my view is loaded at pixel points 0,0 of the image itself and if I zoom out the image appears in the top left corner as opposed to mid-center of the screen/view. Here is what I have so far:

UIImage *image = [UIImage imageNamed: @"t.bmp"];
self.view.backgroundColor = [UIColor blackColor];
self.mi.frame = CGRectMake(0, 0, image.size.width, image.size.height);
self.mi.contentMode = (UIViewContentModeCenter);
self.mi.backgroundColor = [UIColor blackColor];
[self.mi setImage:image];

/* Draw a line here!!
UIGraphicsBeginImageContext(self.mi.frame.size);
[self.mi.image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 20.0);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0,0);
CGContextAddLineToPoint(context, 200, 200);
CGContextMoveToPoint(context, 200,0);
CGContextAddLineToPoint(context, 0, 200);
CGContextStrokePath(context);
self.mi.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
*/

self.expimg.maximumZoomScale = 2.0;
self.expimg.minimumZoomScale = 0.1;
self.expimg.clipsToBounds = YES;
self.expimg.delegate = self;
[self.expimg setContentSize:self.mi.frame.size];

[self.expimg addSubview: self.mi];
[self.view addSubview: self.expimg];

Thanks!

Edit: mi is a UIImageView and expimg is a UIScrollView (used interface builder). Also, viewForZoomingInScrollView is defined.

Body:
Step 1: You create an image view property then init it at viewDidLoad and add to scrollView:

self.pictureImage = [[UIImageView alloc]initWithImage:self.picture];
[_scrollView addSubview:_pictureImage];
self.pictureImage.alpha = 0;
_scrollView.delegate = self;

Step 2: Create adjustZoomScale function to get minimum scale

- (CGFloat)adjustZoomScale{
CGFloat scale = self.scrollView.bounds.size.width / self.pictureImage.bounds.size.width;
CGFloat h = scale * self.pictureImage.bounds.size.height;
if (h > self.scrollView.bounds.size.height) {
    scale = self.scrollView.bounds.size.height / self.pictureImage.bounds.size.height;
}
return scale;
}

Step 3: Because frame of scroll view will be updated at viewDidAppear so we need to adjust zoom scale here. And set alpha to make image appear smoother:

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear: animated];
_scrollView.maximumZoomScale = 1.0;
_scrollView.minimumZoomScale = [self adjustZoomScale];
[_scrollView setZoomScale:_scrollView.minimumZoomScale];
self.pictureImage.alpha = 1;
}

Step 4: Implement viewForZoomingInScrollView (scroll delegate method) and return image view

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return self.pictureImage;
}

Step 5: Implement scrollViewDidZoom (scroll delegate method) and adjust point for image view

- (void)scrollViewDidZoom: (UIScrollView*) scrollView {
CGSize boundsSize = scrollView.bounds.size;
CGRect contentsFrame = _pictureImage.frame;

if (contentsFrame.size.width < boundsSize.width) {
    contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0;
} else {
    contentsFrame.origin.x = 0.0;
}

if (contentsFrame.size.height < boundsSize.height) {
    contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0;
} else {
    contentsFrame.origin.y = 0.0;
}
_pictureImage.frame = contentsFrame;
}

Thank shawhu at this post for point adjusting for image view while zooming


问:
How come div block is moved down when there is enough space?
I have a rather simple problem. For some reason, div.actionBar is moved down even when there should be enough space in the parent div:

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div></code>```

If the widths are subtracted:

venueInfoSection is 960px wide

topVenueSection has 20px padding

mainIconWrapper is 88px wide + 20px margin

primaryInfo is 512px wide

actionBar is 285px wide + 15px margin

So 960-20-20-88-20-512-285-15=0

How come actionBar is moved down even when there should be enough space? It seems to be inlined with the other two blocks only if the width is set to 277px.

答:
It is whitespace that is messing with your layout. line-height:0 does not suffice.

Try setting the font-size to zero:

div {font-size:0;}
h1,span{font-size:initial;}

Consider using a flex-layout instead.

div {font-size:0;}
h1,span{font-size:initial;}
.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div></code>```

Body:
I have a rather simple problem. For some reason, div.actionBar is moved down even when there should be enough space in the parent div:

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}

Title

 Surf Spot

 38 Bourke St

 Save

 Share

If the widths are subtracted:

venueInfoSection is 960px wide

topVenueSection has 20px padding

mainIconWrapper is 88px wide + 20px margin

primaryInfo is 512px wide

actionBar is 285px wide + 15px margin

So 960-20-20-88-20-512-285-15=0

How come actionBar is moved down even when there should be enough space? It seems to be inlined with the other two blocks only if the width is set to 277px.

Body:
It is whitespace that is messing with your layout. line-height:0 does not suffice.

Try setting the font-size to zero:

div {font-size:0;}
h1,span{font-size:initial;}

Consider using a flex-layout instead.

div {font-size:0;}
h1,span{font-size:initial;}
.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}

<div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div>


问:
Test statistic (e.g. chisquare test) inside latex table using the tables-package in R/Knitr/Rstudio
I would like to use the tabular()-function from the tables-package to do a cross-tabulation of two variables (e.g. v1 and v2), and present the p-value of the chisq-test in the table. It is easy to get the crosstabulation, but I cant get the p-value inside the table. This is what I've been trying, without any luck:

```<code>\documentclass{article}

\begin{document}

<<echo=TRUE,message=FALSE>>=
library(Hmisc)
library(tables)
v1 <- sample(letters[1:2],200,replace=TRUE)
v2 <- sample(month.name[1:3],200,replace=TRUE)
df <- data.frame(v1,v2)
@

It is straight forward to get the crosstabulation:
<<results='asis'>>=
latex(   tabular(    Factor(v1)   ~   Factor(v2)      , data=df)  )
@

But I cant get the p-value inside the table:

<<results='asis'>>=
latex(   tabular(    Factor(v1)*chisq.test(v1,v2)$p.value   ~   Factor(v2)      , data=df)  )
@

\end{document}
</code>```

答:
You can also paste text from a chi-squared statistic into a caption via xtable(). For example: </p>

```<code>#sample data
var1<-sample(c('A', 'B'), 10, replace=T)
var2<-sample(c('Red', 'Blue'), 10, replace=T)
#join in frequency table
tab<-table(var1, var2)
#conduct chisq.test
test<-chisq.test(tab)
#show values of chisq.test()
name(test)
#Use xtable, use print.xtable for further manipulations
out<-xtable(tab, caption=paste('Important table, chi-squared =', test$statistic, ', p=', test$p.value,',' ,test$parameter, 'df', sep=' '))
#print
out
</code>```

Body:
I would like to use the tabular()-function from the tables-package to do a cross-tabulation of two variables (e.g. v1 and v2), and present the p-value of the chisq-test in the table. It is easy to get the crosstabulation, but I cant get the p-value inside the table. This is what I've been trying, without any luck:

\documentclass{article}

\begin{document}

<<echo=TRUE,message=FALSE>>=
library(Hmisc)
library(tables)
v1 <- sample(letters[1:2],200,replace=TRUE)
v2 <- sample(month.name[1:3],200,replace=TRUE)
df <- data.frame(v1,v2)
@

It is straight forward to get the crosstabulation:
<<results='asis'>>=
latex(   tabular(    Factor(v1)   ~   Factor(v2)      , data=df)  )
@

But I cant get the p-value inside the table:

<<results='asis'>>=
latex(   tabular(    Factor(v1)*chisq.test(v1,v2)$p.value   ~   Factor(v2)      , data=df)  )
@

\end{document}

Body:
You can also paste text from a chi-squared statistic into a caption via xtable(). For example:

#sample data
var1<-sample(c('A', 'B'), 10, replace=T)
var2<-sample(c('Red', 'Blue'), 10, replace=T)
#join in frequency table
tab<-table(var1, var2)
#conduct chisq.test
test<-chisq.test(tab)
#show values of chisq.test()
name(test)
#Use xtable, use print.xtable for further manipulations
out<-xtable(tab, caption=paste('Important table, chi-squared =', test$statistic, ', p=', test$p.value,',' ,test$parameter, 'df', sep=' '))
#print
out


问:
Anaconda Python in Visual Studio Code PyQt5 import error
I'm trying to use VSCode as my main IDE for Anaconda Custom Python 2.7.13 on MacOS High Sierra.  I'm trying to make a file open dialogue box appear using PyQt5.  In Spider the following works fine, but not in VS Code:

from PyQt5 import QtWidgets
files = QtWidgets.QFileDialog.getOpenFileNames()

The error I get in the VSC console is simply Not Available whereas in the context of a larger program I get
E1101:Module 'PyQt5.QtWidgets' has no 'QFileDialog' member.

I was wondering whether anyone had any idea where this issue is arising from?

Oli

答: I ran another QT5 program I was working on that I already knew worked in VSC and added a dialog box.  This worked fine, so I created a UI using QT Designer to add it to.  It seems that QFileDialog needs an instance of class Ui_Frame() to instantiate.  The fact that it worked in Spyder and not VSC may be related to the fact that the UI of Spyder is built on QT.


问:
I need help in this query mongodb with nodejs
The query is returning double value, can you help me with this?
the problem stay in unwind ?

is a consultation that consolidates the debits and credits of the db...

with aggregate...

Code:

My DAO ( MongoDB + NodeJS ) :

```<code>ListarDebitosDAO.prototype.consolidado = function(usuario,res,req){

this._connection.open(function(err, mongoclient){
    mongoclient.collection("contas", function(err, collection){
        collection.aggregate([{
            $match : {usuario : usuario}},{
            $unwind: "$debitos"
        },{
            $unwind: "$creditos"
        }, {
            $group: {
                "_id" : usuario,
                "debitos": {
                    $sum: "$debitos.debito"
                },
                "creditos" : {
                    $sum: "$creditos.credito"
                }

            }
        }])
        .toArray(function(error, results){

            console.log(results)

            var debitoConsolidado = results[0].debitos;
            var creditoConsolidado = results[0].creditos;

            res.render('dashboard', {debitoConsolidado,nome_usuario: req.session.nome,creditoConsolidado})

        });
        // mongoclient.close();
    });
});
</code>```

}

My collection ( exemple ) :

```<code>{
"_id" : ObjectId("5a09113b42e54fb49230fa37"),
"usuario" : "sara",
"creditos" : [
    {
        "nome_do_credito" : "credito inicial",
        "credito" : 0
    },
    {
        "nome_do_credito" : "salario",
        "credito" : 1200
    }
],
"debitos" : [
    {
        "nome_do_debito" : "debito inicial",
        "debito" : 0
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 200
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 600
    }
]
</code>```

}

My atual output:

```<code>{ "_id" : null, "debitos" : 1600, "creditos" : 3600 }
</code>```

I need :

```<code>{ "_id" : null, "debitos" : 800, "creditos" : 1200 }
enter code here
</code>```

答:
It can be as simple as this:

```<code>    db.contas.aggregate([
     {
       $project: {
         _id: 1,
         usario: 1,
         debitos: {
           $reduce: {
             input: "$debitos",
             initialValue: 0,
             in: { $add: [ "$$value", "$$this.debito" ] }
           }
         },
         creditos: {
           $reduce: {
             input: "$creditos",
             initialValue: 0,
             in: { $add: [ "$$value", "$$this.credito" ] }
           }
         }
       }
     }
    ]);
</code>```

You can use just one projection and reduce the arrays by summing their members.

Body:
The query is returning double value, can you help me with this?
the problem stay in unwind ?

is a consultation that consolidates the debits and credits of the db...

with aggregate...

Code:

My DAO ( MongoDB + NodeJS ) :

ListarDebitosDAO.prototype.consolidado = function(usuario,res,req){

this._connection.open(function(err, mongoclient){
    mongoclient.collection("contas", function(err, collection){
        collection.aggregate([{
            $match : {usuario : usuario}},{
            $unwind: "$debitos"
        },{
            $unwind: "$creditos"
        }, {
            $group: {
                "_id" : usuario,
                "debitos": {
                    $sum: "$debitos.debito"
                },
                "creditos" : {
                    $sum: "$creditos.credito"
                }

            }
        }])
        .toArray(function(error, results){

            console.log(results)

            var debitoConsolidado = results[0].debitos;
            var creditoConsolidado = results[0].creditos;

            res.render('dashboard', {debitoConsolidado,nome_usuario: req.session.nome,creditoConsolidado})

        });
        // mongoclient.close();
    });
});

}

My collection ( exemple ) :

{
"_id" : ObjectId("5a09113b42e54fb49230fa37"),
"usuario" : "sara",
"creditos" : [
    {
        "nome_do_credito" : "credito inicial",
        "credito" : 0
    },
    {
        "nome_do_credito" : "salario",
        "credito" : 1200
    }
],
"debitos" : [
    {
        "nome_do_debito" : "debito inicial",
        "debito" : 0
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 200
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 600
    }
]

}

My atual output:

{ "_id" : null, "debitos" : 1600, "creditos" : 3600 }

I need :

{ "_id" : null, "debitos" : 800, "creditos" : 1200 }
enter code here

Body:
It can be as simple as this:

    db.contas.aggregate([
     {
       $project: {
         _id: 1,
         usario: 1,
         debitos: {
           $reduce: {
             input: "$debitos",
             initialValue: 0,
             in: { $add: [ "$$value", "$$this.debito" ] }
           }
         },
         creditos: {
           $reduce: {
             input: "$creditos",
             initialValue: 0,
             in: { $add: [ "$$value", "$$this.credito" ] }
           }
         }
       }
     }
    ]);

You can use just one projection and reduce the arrays by summing their members.


问:
Schedule Notification with specified date
I want to implement scheduled notification(in iOS 10) using UNTimeIntervalNotificationTrigger or UNCalendarNotificationTrigger with repeat parameter as true for 2-3 consecutive days. Later on I can update or delete notification for upcoming days. e.g I scheduled notification on 13 Nov 2017 and I wanted to repeat this till 17 Nov 2017 at 10AM in morning and on 15 Nov 2017 I wanted to change the schedule time of notification for next 2days i.e (16 Nov and 17 Nov).

So can you please suggest me what are the alternatives or how this can be achieved?

答:
I think you can use a trigger for that.

```<code>let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
</code>```

To create the dateComponents to match your needs you have to do for example:

```<code>// Matching specific minute and hour
let unitFlags = Set<Calendar.Component>([.hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)

// Matching specific weekday, hour and minute
let unitFlags = Set<Calendar.Component>([.weekday, .hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)

// Matching specific day, hour and minute
let unitFlags = Set<Calendar.Component>([.day, .hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)
</code>```

Body:
I think you can use a trigger for that.

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

To create the dateComponents to match your needs you have to do for example:

// Matching specific minute and hour
let unitFlags = Set<Calendar.Component>([.hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)

// Matching specific weekday, hour and minute
let unitFlags = Set<Calendar.Component>([.weekday, .hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)

// Matching specific day, hour and minute
let unitFlags = Set<Calendar.Component>([.day, .hour, .minute])
dateComponents = NSCalendar.current.dateComponents(unitFlags, from: givenDate)


问:
String encryption - generate unique pattern like Spotify codes
Yesterday I've read the question Algorithm to create costum Template/Code from String. Because the question was not formulated that well it was downvoted just instantly. However, the question itself was in my opinion not that bad, so I decided to ask a hopefully better version of this question again.

Ok, Im wondering how's the string encryption e.g. of the new Spotify codes is working. See the image below:

I would be super interested in the extent to which it is possible to implement something like this pattern-encryption in javascript.

The Spotify codes - I've already mentioned above - are structured in a row that is divided into different sized bars.

So let's say there is a row that is divided into 24 bars and all of the bars can have the size '3', '5', '7' or '9'.

```<code> string = 'hello'   -->  pattern = '3,3,5,7,9,3,7,9,9,3,3,5,3,9,5,3,3,7,5,9,3,9,3,9'
</code>```

What's a good method / easy way to translate a string (lets say 5 characters) into a unique pattern, that afterwards is also convertible back and read as a string?

This is my code I've developed till now, but in this code I used a key-array that includes 10 different possibilities (--> bar sizes) , but I just like to us 4 different sizes.

Explanation:

I' converting my string 'hello' to binary format and splitting the string up into groups of maximum 3 to get something like this: ['001', '110', '0'].

Afterwards I'm using the result array above and find the matches in my Key-array below and get the indexes (10 different indexed --> 10 different possibilities) and use them as bar-sizes.

But, There MUST BE a way more efficient method to translate a string into a unique pattern. I hope somebody can help me improve my small algorithm. Thanks a million in advance.

var key = ['0', '1', '000','001','010','100','110','101','011','111']

String.prototype.encode = function() {
  var code = this, result = [],encryped_string=[]
  for (var i=0; i<code.length;i++) result.push(code[i].charCodeAt(0).toString(2).match(/.{1,3}/g));
  for (var i=0; i<result.length; i++) for (var j=0; j<result[i].length; j++) encryped_string.push(key.indexOf(result[i][j]))
  return encryped_string
}

var code = 'hello';
console.log(code.encode())```

答:
It appears that you're making the assumption that there is a direct mapping from the string "Coffee" to the graphic that's shown. That assumption is almost certainly incorrect.

First, consider what would happen if there are two different songs called "Coffee." Your proposed algorithm would assign them both the same code. That seems unreasonable. You want the code to uniquely identify the song.

Second, song names can be arbitrarily long. For example, there's a song by Pink Floyd called "Several Species of Small Furry Animals Gathered Together in a Cave and Grooving with a Pict." Your encoding algorithm probably won't be able to fit that into 24 bars. Even if it can, I can always find a longer song title.

Given the letters a-z, there are 11,881,376 possible 5-character strings. If you just want to uniquely encode all possible, you can do that with just 23 bits. Just treat the string as a base-26 number and do the conversion.

Most likely, Spotify is assigning a unique number to each song, and then encoding that number. There is no direct mapping between the string "Coffee" and the graphical code you see on your screen.

Body:
Yesterday I've read the question Algorithm to create costum Template/Code from String. Because the question was not formulated that well it was downvoted just instantly. However, the question itself was in my opinion not that bad, so I decided to ask a hopefully better version of this question again.

Ok, Im wondering how's the string encryption e.g. of the new Spotify codes is working. See the image below:

I would be super interested in the extent to which it is possible to implement something like this pattern-encryption in javascript.

The Spotify codes - I've already mentioned above - are structured in a row that is divided into different sized bars.

So let's say there is a row that is divided into 24 bars and all of the bars can have the size '3', '5', '7' or '9'.

 string = 'hello'   -->  pattern = '3,3,5,7,9,3,7,9,9,3,3,5,3,9,5,3,3,7,5,9,3,9,3,9'

What's a good method / easy way to translate a string (lets say 5 characters) into a unique pattern, that afterwards is also convertible back and read as a string?

This is my code I've developed till now, but in this code I used a key-array that includes 10 different possibilities (--> bar sizes) , but I just like to us 4 different sizes.

Explanation:

I' converting my string 'hello' to binary format and splitting the string up into groups of maximum 3 to get something like this: ['001', '110', '0'].

Afterwards I'm using the result array above and find the matches in my Key-array below and get the indexes (10 different indexed --> 10 different possibilities) and use them as bar-sizes.

But, There MUST BE a way more efficient method to translate a string into a unique pattern. I hope somebody can help me improve my small algorithm. Thanks a million in advance.

var key = ['0', '1', '000','001','010','100','110','101','011','111']

String.prototype.encode = function() {
  var code = this, result = [],encryped_string=[]
  for (var i=0; i<code.length;i++) result.push(code[i].charCodeAt(0).toString(2).match(/.{1,3}/g));
  for (var i=0; i<result.length; i++) for (var j=0; j<result[i].length; j++) encryped_string.push(key.indexOf(result[i][j]))
  return encryped_string
}

var code = 'hello';
console.log(code.encode())


问:
Hyperledger Fabric: peer chaincode instantiate error

Error starting container: Failed to generate platform-specific docker
  build: Error returned from build: 1 "can't load package: package
  ../../bin/github.com/hyperledger/fabric/chaincode/marbles: open
  /bin/github.com/hyperledger/fabric/chaincode/marbles: no such file or
  directory.

I see it is looking for a relative directory. relative to what? chaincode install was fine. If the chaincode is installed, why can it not be found for instantiate? 1 peer. 1 solo orderer. channel joined fine.

答:
There's a "hidden" expectation in the path mapping. It expects there to be a /src directory under gopath that caused me some trouble until I figured it out.

Here's my solution fwiw:

In your compose yaml for the peer you would set the env variable :

- GOPATH=/opt/gopath

Then in the CLI you can install and instantiate thus:

```<code>SIGNED_CHAINCODE_LOCATION=/opt/gopath/src/chaincode/<cc_dir>/<signed_cc>.out

peer chaincode install /${SIGNED_CHAINCODE_LOCATION}
</code>```

And instantiate as normal.
Just use the directory instead of the .out file if you don't need to package and sign.

In my case I added a working dir in the peer that set the chain code to a relative directory to my base blockchain directory: - ./chaincode/:/opt/gopath/src/chaincode/ and dumped the go folder into there.

Body:
There's a "hidden" expectation in the path mapping. It expects there to be a /src directory under gopath that caused me some trouble until I figured it out.

Here's my solution fwiw:

In your compose yaml for the peer you would set the env variable :

- GOPATH=/opt/gopath

Then in the CLI you can install and instantiate thus:

SIGNED_CHAINCODE_LOCATION=/opt/gopath/src/chaincode/<cc_dir>/<signed_cc>.out

peer chaincode install /${SIGNED_CHAINCODE_LOCATION}

And instantiate as normal.
Just use the directory instead of the .out file if you don't need to package and sign.

In my case I added a working dir in the peer that set the chain code to a relative directory to my base blockchain directory: - ./chaincode/:/opt/gopath/src/chaincode/ and dumped the go folder into there.


问:
How can I read the content of a data matrix into multiple cells in excel
I want to use a barcode-scanner (+ data matrix) to perform an input in an existing excel file (*.xlsx). The content of the scanned code should be devidied into two cells, split accoring to a tabulator symbol.

I have generated the following data matrix with the content Hans<tab>Müller where <tab> equals the decimal character code of 9 in ASCII.

Scanning the matrix in Notepad++ (focus in Notepad, scanning the matrix) results in the correct result. But if I try the procedure in excel (selecting a cell, scanning the matrix), the input is HansMüller. I expected "Hans" in the selected cell and "Müller" in the cell next to the selected one. So, what am I doing wrong?

How can I read the content of a data matrix into multiple cells in excel?

Update:
I am using the scanner ElmiScan ECR14 from elmicron. The website http://codecorp.com/ConfigGuide/?product=CR1400 provides a list of all configuration "codes" (CR1400 equalls ECR14).

If I enable Control Character Input - Ctrl + Character as suggested by Brian, Excel reads HansMÄller and still ignores the tab.

答:
I am getting "Hans<tab>Mller" in plain old Notepad, and HansMller in Excel indicating that Excel is interpreting the <CTRL-I> as a "let's start typing
in italics now". My system is probably dropping the "ü" because of my U.S. keyboard.

When I copy from Notepad into Excel, however the embedded tab character has the desired result and advances to the next cell. This indicates to me that the scanner is in the default state of "Disable Function Key Mapping" and has interpreted the <CTRL-I> you have in the Datamatrix barcode as the keystroke
<CTRL-I> instead of the <TAB> key.

The solution is to place the scanner into "Enable Function Key Mapping" mode, which is not the default mode by scanning the Function Key Mapping barcodes in your scanner manual.

EDIT: So, I've reviewed the website and 1400 Configuration Guide and needless to say, they disagree. So it looks like there are a few different options for setting keyboard language support, which is where I think the problem lies.

I would start with the Config Guide and test modes B4, D3, D2, C3, B2, and B3 in that order.

Then I would move onto the website based guide and check out each of the following modes just to be sure.

The fact that after your previous experiment the "ü" turns into a "Ä" tells me we are on the right track. One of these settings should produce an ASCII <TAB> keyboard character for Excel. If none of these works, I would contact technical support at Elmicron.


问:
Javascript code for Drop Down List not working properly
I have written the following code for creating drop-down lists. The list for Research Area is working fine but corresponding to that research area, the second list viz Choose Professor which should show options like X, Y etc. is not appearing. What is the bug in my code?

```<code><!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    function populate(s1, s2) {
      var s1 = document.getElementbyId(s1);
      var s2 = document.getElementbyId(s2);
      s2.innerHTML = "";
      if (s1.value == "Deep Learning") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Big Data") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Cryptography") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Algorithms") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Embedded Systems") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Graphic Design") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Computer Architecture") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      if (s1.value == "Robotics") {
        var optionArray = ["|", "X|X", "Y|Y", "Z|Z", "A|A"];
      }
      for (var option in optionArray) {
        var pair = optionArray[option].split("|")
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        s2.options.add(newOption);
      }
    }
  </script>

</head>

<body>
  <h2>Choose Accordingly</h2>
  <hr/> Choose Research Area:
  <select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Deep Learning">Deep Learning</option>
    <option value="Big Data">Big Data</option>
    <option value="Cryptography">Cryptography</option>
    <option value="Algorithms">Algorithms</option>
    <option value="Embedded Systems">Embedded Systems</option>
    <option value="Graphic Design">Graphic Design</option>
    <option value="Computer Architecture">Computer Architecture</option>
    <option value="Robotics">Robotics</option>
    </select>
  <hr/> Choose Professor:
  <select id="slct2" name="slct2"></select>
  <hr />

</body>

</html>
</code>```

答:
Use...
        s2.appendChild(newOption);
Instead of
        s2.options.add(newOption);</p>

Body:
I have written the following code for creating drop-down lists. The list for Research Area is working fine but corresponding to that research area, the second list viz Choose Professor which should show options like X, Y etc. is not appearing. What is the bug in my code?

<!DOCTYPE html>

Choose Accordingly

 Choose Research Area:
  <select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Deep Learning">Deep Learning</option>
    <option value="Big Data">Big Data</option>
    <option value="Cryptography">Cryptography</option>
    <option value="Algorithms">Algorithms</option>
    <option value="Embedded Systems">Embedded Systems</option>
    <option value="Graphic Design">Graphic Design</option>
    <option value="Computer Architecture">Computer Architecture</option>
    <option value="Robotics">Robotics</option>
    </select>

 Choose Professor:
  <select id="slct2" name="slct2"></select>


问:
How to create tree based query from same table in mysql?
Hey guys i want to create one tree based data in my html view from mysql.
I have one table salary_slip there 2 columns pay_month and pay_year.

data is like this:

```<code>pay_month      pay_year

February         2014
march            2014
January          2015
February         2015
April            2015
may              2015
June             2015
January          2016
march            2016
December         2016
</code>```

So now i want to create tree view for the same.so, if user will click on 2016(pay_year) onclick this all data in pay_month in front of 2016 should be display in tree format and same for the all.

My current query is:

```<code>select
    PAY_MONTH,
    PAY_YEAR
from
    india_salary_slip_details
where
    EMPLOYEE_ID = 34
group by
    pay_year
</code>```

By this i got my data:
but i can only see each year's first month only.
please provide me with better query so i can get my result.

image for the same:current data from my query

答:
The problem is your group by, you just want to order by year :</p>

```<code>SELECT PAY_MONTH, PAY_YEAR, FROM india_salary_slip_details WHERE EMPLOYEE_ID = 34
ORDER BY PAY_YEAR
</code>```

Body:
Hey guys i want to create one tree based data in my html view from mysql.
I have one table salary_slip there 2 columns pay_month and pay_year.

data is like this:

pay_month      pay_year

February         2014
march            2014
January          2015
February         2015
April            2015
may              2015
June             2015
January          2016
march            2016
December         2016

So now i want to create tree view for the same.so, if user will click on 2016(pay_year) onclick this all data in pay_month in front of 2016 should be display in tree format and same for the all.

My current query is:

select
    PAY_MONTH,
    PAY_YEAR
from
    india_salary_slip_details
where
    EMPLOYEE_ID = 34
group by
    pay_year

By this i got my data:
but i can only see each year's first month only.
please provide me with better query so i can get my result.

image for the same:current data from my query

Body:
The problem is your group by, you just want to order by year :

SELECT PAY_MONTH, PAY_YEAR, FROM india_salary_slip_details WHERE EMPLOYEE_ID = 34
ORDER BY PAY_YEAR


问:
Cannot call the animate function of the html graph onclick again and again
I have done a column graph which animates on windows load.Now I want to animate the graph on click as well as the animation will appear on windows load..the code in published in github</p>

答:
You should just stick to using jQuery if you have already added it to the page before any of your code will run.

Since graphanimate is a function you can reference it multiple times to run during both events

```<code>$(graphanimate) // fire on dom content loaded
$('.some-selector').on('click', graphanimate) // fire on click
</code>```

Body:
You should just stick to using jQuery if you have already added it to the page before any of your code will run.

Since graphanimate is a function you can reference it multiple times to run during both events

$(graphanimate) // fire on dom content loaded
$('.some-selector').on('click', graphanimate) // fire on click


问:
How to preserve previous ngbTab content when switching between tabs in ng-bootstrap Angular 2 typescript
I have a UI where I am using ngb-tabset and ngb-tab to render the following:

The user enters something above in the form and obtains a graphical visualization under Graph Navigation Tab as follows:

The user could now click on Semantic Query tab and obtain information from the child component.

However when the user clicks back on the Graph Navigation tab I get the following error:

```<code> myDiagram is undefined
</code>```

where myDiagram is a go.Diagram instance which gets information from the parent component and renders the diagram.(GoJS)

Code

parent.component.html

```<code><ngb-tabset>
    <ngb-tab title="Graph Navigation">
        <template ngbTabContent>
        <explore-search-details [config]="visData" [lang]="language"></explore-search-details>
        </template>
    </ngb-tab>
    <ngb-tab title="Semantic Query">
        <template ngbTabContent>
            <explore-search-semantic></explore-search-semantic>
        </template>
    </ngb-tab>

</ngb-tabset>
</code>```

explore-search-details is a child component which takes visData and language as input variables from the parent component.

within the explore-search-details.component.html there is a div as follows which takes care of rendering

```<code>  <div #myDiagramDiv></div>
</code>```

Versions

angular 2.4.0, ng-bootstrap 1.0.0-alpha.21

Edit

there was a mistake in my addressing myDiagram is a go.Diagram type variable which is used within ngOnChanges() and ngAfterViewInit() lifecycle hook which goes undefined after the tab is switched back.

答:
For the first issue, Try to use LocalStorage to preserve tab states.

there was a mistake in my addressing myDiagram is a go.Diagram type variable which is used within ngOnChanges() and ngAfterViewInit() lifecycle hook which goes undefined after the tab is switched back.

Try putting your reInit code in setTimeout, so you set up your dom elem in the next cycle instead of the current one.

Body:
I have a UI where I am using ngb-tabset and ngb-tab to render the following:

The user enters something above in the form and obtains a graphical visualization under Graph Navigation Tab as follows:

The user could now click on Semantic Query tab and obtain information from the child component.

However when the user clicks back on the Graph Navigation tab I get the following error:

 myDiagram is undefined

where myDiagram is a go.Diagram instance which gets information from the parent component and renders the diagram.(GoJS)

Code

parent.component.html

<ngb-tabset>
    <ngb-tab title="Graph Navigation">
        <template ngbTabContent>
        <explore-search-details [config]="visData" [lang]="language"></explore-search-details>
        </template>
    </ngb-tab>
    <ngb-tab title="Semantic Query">
        <template ngbTabContent>
            <explore-search-semantic></explore-search-semantic>
        </template>
    </ngb-tab>

</ngb-tabset>

explore-search-details is a child component which takes visData and language as input variables from the parent component.

within the explore-search-details.component.html there is a div as follows which takes care of rendering

Versions

angular 2.4.0, ng-bootstrap 1.0.0-alpha.21

Edit

there was a mistake in my addressing myDiagram is a go.Diagram type variable which is used within ngOnChanges() and ngAfterViewInit() lifecycle hook which goes undefined after the tab is switched back.