问:
Concerning Struct Constructor and Destructor behavior - C++
I don't understand why the output of this program is as follows. Why isn't there a compilation error? I thought when trying to construct B, the compiler would find no function called foo() and report an error.

```<code>#include <iostream>
using namespace std;

struct A{
    int a;
    A(int i=0) : a(i) { cout << "A" << endl; }
    ~A() { cout << "Bye A" << endl; }
    int foo() { return a; }
};
struct B{
    int b;
    B(int i=0) : b(i) { cout << "B" << endl; }
    ~B() { cout << "Bye B" << endl; }
    int bar() { return b; }
};
struct C : B, A {
    C(int i=0) : B(foo()), A(i) {}
};

int main() {
    cout << C(10).bar() << endl;
    return 0;
}
</code>```

The output:

```<code>B
A
0
Bye A
Bye B
</code>```

In general, I would like to know when there is multiple inheritance, what is the order in which the parent structs are constructed and initialized? Can I expect a similar behavior in classes too?

Any explanation regarding the order of constructor and destructor calls is much appreciated.

Note: This is not homework. And, I have researched similar topics but nothing came up regarding this issue.

答:
I wanted to see what was actually happening.  Since I have the results, here they are for you.

```<code>#include <iostream>
using namespace std;

/*** Structures ***/
struct A{
    int a;
#warning a integer declared in struct A

    A(int i=0) : a(i)
#warning A constuctor declared
#warning A constructor creates variable i, sets it to 0
#warning then assigns i to a
    {
        cout << "inside constructor A" << endl;
        cout << "i = " << i << endl;
        cout << "a = " << a << endl;
        cout << "leaving constructor A" << endl;
    }
#warning A constructor definition provided
    ~A()
#warning A destructor declared
    {
        cout << "inside destructor A" << endl;
        cout << "leaving destructor A" << endl;
    }
#warning A destructor definition provided
    int foo()
#warning foo function declared in struct A
    {
        cout << "inside foo, inside A" << endl;
        cout << "foo will return a = " << a << " then leave foo" << endl;
        return a;
    }
#warning foo function defined in struct A
};

struct B{
    int b;
#warning b integer declared in struct B
    B(int i=0) : b(i)
#warning B constructor declared
#warning B creates int i and initializes it to 0
#warning b is assigned the value of i
    {
        cout << "inside constructor B" << endl;
        cout << "i = " << i << endl;
        cout << "b = " << b << endl;
        cout << "leaving constructor B" << endl;
    }
#warning B constructor defined
    ~B()
#warning B destructor declared
    {
        cout << "inside destructor B" << endl;
        cout << "leaving destructor B" << endl;
    }
#warning B destructor defined
    int bar()
#warning bar function declared in struct B
    {
        cout << "inside bar, inside B" << endl;
        cout << "bar will return b = " << b << " then leave bar" << endl;
        return b;
    }
#warning bar function defined in struct B
};

struct C : B, A
#warning C structure declared derived from B and A
{
    C(int i=0) : B(foo()), A(i)
#warning C constructor declared
#warning C constructor creates int i and assigns value 0
#warning C constructor instantiates B and calls foo from A to assign value?
#warning C constructor instantiates A by assigning i to it
    {
        cout << "inside constructor C" << endl;
        cout << "i = " << i << endl;
        cout << "leaving constructor C" << endl;
    }
#warning C constructor defined with no implementation
};

int main() {
    cout << "command is: print the value of C(10).bar()" << endl;
    cout << C(10).bar() << endl;
#warning initialize C with a value of 10
#warning then call the bar function extended from B

#warning declare struct C blah, initialized with C(12)
    cout << endl << "creating struct blah with definition C(12)" << endl;
    struct C blah = C(12);
    cout << "calling blah.foo" << endl;
    cout << blah.foo() << endl;
    cout << "calling blah.bar" << endl;
    cout << blah.bar() << endl;
#warning  printing and then returning 0
    cout << endl << "Some random output before returning 0" << endl;
    return 0;
}
</code>```

Gives the following during compilation results (cleaned up a little):

```<code>>make
test.cpp:7:2:  warning: #warning a integer declared in struct A [-Wcpp]
test.cpp:10:2: warning: #warning A constuctor declared [-Wcpp]
test.cpp:11:2: warning: #warning A constructor creates variable i, sets it to 0 [-Wcpp]
test.cpp:12:2: warning: #warning then assigns i to a [-Wcpp]
test.cpp:19:2: warning: #warning A constructor definition provided [-Wcpp]
test.cpp:21:2: warning: #warning A destructor declared [-Wcpp]
test.cpp:26:2: warning: #warning A destructor definition provided [-Wcpp]
test.cpp:28:2: warning: #warning foo function declared in struct A [-Wcpp]
test.cpp:34:2: warning: #warning foo function defined in struct A [-Wcpp]
test.cpp:39:2: warning: #warning b integer declared in struct B [-Wcpp]
test.cpp:41:2: warning: #warning B constructor declared [-Wcpp]
test.cpp:42:2: warning: #warning B creates int i and initializes it to 0 [-Wcpp]
test.cpp:43:2: warning: #warning b is assigned the value of i [-Wcpp]
test.cpp:50:2: warning: #warning B constructor defined [-Wcpp]
test.cpp:52:2: warning: #warning B destructor declared [-Wcpp]
test.cpp:57:2: warning: #warning B destructor defined [-Wcpp]
test.cpp:59:2: warning: #warning bar function declared in struct B [-Wcpp]
test.cpp:65:2: warning: #warning bar function defined in struct B [-Wcpp]
test.cpp:70:2: warning: #warning C structure declared derived from B and A [-Wcpp]
test.cpp:73:2: warning: #warning C constructor declared [-Wcpp]
test.cpp:74:2: warning: #warning C constructor creates int i and assigns value 0 [-Wcpp]
test.cpp:75:2: warning: #warning C constructor instantiates B and calls foo from A to assign value? [-Wcpp]
test.cpp:76:2: warning: #warning C constructor instantiates A by assigning i to it [-Wcpp]
test.cpp:82:2: warning: #warning C constructor defined with no implementation [-Wcpp]
test.cpp:88:2: warning: #warning initialize C with a value of 10 [-Wcpp]
test.cpp:89:2: warning: #warning then call the bar function extended from B [-Wcpp]
test.cpp:91:2: warning: #warning declare struct C blah, initialized with C(12) [-Wcpp]
test.cpp:98:2: warning: #warning printing and then returning 0 [-Wcpp]
</code>```

And gives the following output:

```<code>>test
command is: print the value of C(10).bar()
inside foo, inside A
foo will return a = 4201198 then leave foo
inside constructor B
i = 4201198
b = 4201198
leaving constructor B
inside constructor A
i = 10
a = 10
leaving constructor A
inside constructor C
i = 10
leaving constructor C
inside bar, inside B
bar will return b = 4201198 then leave bar
4201198
inside destructor A
leaving destructor A
inside destructor B
leaving destructor B

creating struct blah with definition C(12)
inside foo, inside A
foo will return a = 4201104 then leave foo
inside constructor B
i = 4201104
b = 4201104
leaving constructor B
inside constructor A
i = 12
a = 12
leaving constructor A
inside constructor C
i = 12
leaving constructor C
calling blah.foo
inside foo, inside A
foo will return a = 12 then leave foo
12
calling blah.bar
inside bar, inside B
bar will return b = 4201104 then leave bar
4201104

Some random output before returning 0
inside destructor A
leaving destructor A
inside destructor B
leaving destructor B
</code>```

Body:
I don't understand why the output of this program is as follows. Why isn't there a compilation error? I thought when trying to construct B, the compiler would find no function called foo() and report an error.

#include <iostream>
using namespace std;

struct A{
    int a;
    A(int i=0) : a(i) { cout << "A" << endl; }
    ~A() { cout << "Bye A" << endl; }
    int foo() { return a; }
};
struct B{
    int b;
    B(int i=0) : b(i) { cout << "B" << endl; }
    ~B() { cout << "Bye B" << endl; }
    int bar() { return b; }
};
struct C : B, A {
    C(int i=0) : B(foo()), A(i) {}
};

int main() {
    cout << C(10).bar() << endl;
    return 0;
}

The output:

B
A
0
Bye A
Bye B

In general, I would like to know when there is multiple inheritance, what is the order in which the parent structs are constructed and initialized? Can I expect a similar behavior in classes too?

Any explanation regarding the order of constructor and destructor calls is much appreciated.

Note: This is not homework. And, I have researched similar topics but nothing came up regarding this issue.

Body:
I wanted to see what was actually happening.  Since I have the results, here they are for you.

#include <iostream>
using namespace std;

/*** Structures ***/
struct A{
    int a;
#warning a integer declared in struct A

    A(int i=0) : a(i)
#warning A constuctor declared
#warning A constructor creates variable i, sets it to 0
#warning then assigns i to a
    {
        cout << "inside constructor A" << endl;
        cout << "i = " << i << endl;
        cout << "a = " << a << endl;
        cout << "leaving constructor A" << endl;
    }
#warning A constructor definition provided
    ~A()
#warning A destructor declared
    {
        cout << "inside destructor A" << endl;
        cout << "leaving destructor A" << endl;
    }
#warning A destructor definition provided
    int foo()
#warning foo function declared in struct A
    {
        cout << "inside foo, inside A" << endl;
        cout << "foo will return a = " << a << " then leave foo" << endl;
        return a;
    }
#warning foo function defined in struct A
};

struct B{
    int b;
#warning b integer declared in struct B
    B(int i=0) : b(i)
#warning B constructor declared
#warning B creates int i and initializes it to 0
#warning b is assigned the value of i
    {
        cout << "inside constructor B" << endl;
        cout << "i = " << i << endl;
        cout << "b = " << b << endl;
        cout << "leaving constructor B" << endl;
    }
#warning B constructor defined
    ~B()
#warning B destructor declared
    {
        cout << "inside destructor B" << endl;
        cout << "leaving destructor B" << endl;
    }
#warning B destructor defined
    int bar()
#warning bar function declared in struct B
    {
        cout << "inside bar, inside B" << endl;
        cout << "bar will return b = " << b << " then leave bar" << endl;
        return b;
    }
#warning bar function defined in struct B
};

struct C : B, A
#warning C structure declared derived from B and A
{
    C(int i=0) : B(foo()), A(i)
#warning C constructor declared
#warning C constructor creates int i and assigns value 0
#warning C constructor instantiates B and calls foo from A to assign value?
#warning C constructor instantiates A by assigning i to it
    {
        cout << "inside constructor C" << endl;
        cout << "i = " << i << endl;
        cout << "leaving constructor C" << endl;
    }
#warning C constructor defined with no implementation
};

int main() {
    cout << "command is: print the value of C(10).bar()" << endl;
    cout << C(10).bar() << endl;
#warning initialize C with a value of 10
#warning then call the bar function extended from B

#warning declare struct C blah, initialized with C(12)
    cout << endl << "creating struct blah with definition C(12)" << endl;
    struct C blah = C(12);
    cout << "calling blah.foo" << endl;
    cout << blah.foo() << endl;
    cout << "calling blah.bar" << endl;
    cout << blah.bar() << endl;
#warning  printing and then returning 0
    cout << endl << "Some random output before returning 0" << endl;
    return 0;
}

Gives the following during compilation results (cleaned up a little):

>make
test.cpp:7:2:  warning: #warning a integer declared in struct A [-Wcpp]
test.cpp:10:2: warning: #warning A constuctor declared [-Wcpp]
test.cpp:11:2: warning: #warning A constructor creates variable i, sets it to 0 [-Wcpp]
test.cpp:12:2: warning: #warning then assigns i to a [-Wcpp]
test.cpp:19:2: warning: #warning A constructor definition provided [-Wcpp]
test.cpp:21:2: warning: #warning A destructor declared [-Wcpp]
test.cpp:26:2: warning: #warning A destructor definition provided [-Wcpp]
test.cpp:28:2: warning: #warning foo function declared in struct A [-Wcpp]
test.cpp:34:2: warning: #warning foo function defined in struct A [-Wcpp]
test.cpp:39:2: warning: #warning b integer declared in struct B [-Wcpp]
test.cpp:41:2: warning: #warning B constructor declared [-Wcpp]
test.cpp:42:2: warning: #warning B creates int i and initializes it to 0 [-Wcpp]
test.cpp:43:2: warning: #warning b is assigned the value of i [-Wcpp]
test.cpp:50:2: warning: #warning B constructor defined [-Wcpp]
test.cpp:52:2: warning: #warning B destructor declared [-Wcpp]
test.cpp:57:2: warning: #warning B destructor defined [-Wcpp]
test.cpp:59:2: warning: #warning bar function declared in struct B [-Wcpp]
test.cpp:65:2: warning: #warning bar function defined in struct B [-Wcpp]
test.cpp:70:2: warning: #warning C structure declared derived from B and A [-Wcpp]
test.cpp:73:2: warning: #warning C constructor declared [-Wcpp]
test.cpp:74:2: warning: #warning C constructor creates int i and assigns value 0 [-Wcpp]
test.cpp:75:2: warning: #warning C constructor instantiates B and calls foo from A to assign value? [-Wcpp]
test.cpp:76:2: warning: #warning C constructor instantiates A by assigning i to it [-Wcpp]
test.cpp:82:2: warning: #warning C constructor defined with no implementation [-Wcpp]
test.cpp:88:2: warning: #warning initialize C with a value of 10 [-Wcpp]
test.cpp:89:2: warning: #warning then call the bar function extended from B [-Wcpp]
test.cpp:91:2: warning: #warning declare struct C blah, initialized with C(12) [-Wcpp]
test.cpp:98:2: warning: #warning printing and then returning 0 [-Wcpp]

And gives the following output:

>test
command is: print the value of C(10).bar()
inside foo, inside A
foo will return a = 4201198 then leave foo
inside constructor B
i = 4201198
b = 4201198
leaving constructor B
inside constructor A
i = 10
a = 10
leaving constructor A
inside constructor C
i = 10
leaving constructor C
inside bar, inside B
bar will return b = 4201198 then leave bar
4201198
inside destructor A
leaving destructor A
inside destructor B
leaving destructor B

creating struct blah with definition C(12)
inside foo, inside A
foo will return a = 4201104 then leave foo
inside constructor B
i = 4201104
b = 4201104
leaving constructor B
inside constructor A
i = 12
a = 12
leaving constructor A
inside constructor C
i = 12
leaving constructor C
calling blah.foo
inside foo, inside A
foo will return a = 12 then leave foo
12
calling blah.bar
inside bar, inside B
bar will return b = 4201104 then leave bar
4201104

Some random output before returning 0
inside destructor A
leaving destructor A
inside destructor B
leaving destructor B


来源: stackexchange

问:
Slicing a dictionary's value isn't working properly
So I have a json file which contains role ids (a dictionary named roles),with a key (which is the name of the role) and each key has the role's id as it's value

Looks something like this:

{"Ban": ["694175790639743076"], "Muted": ["692863646543380590"]}

I mostly just need the ids from the json

using something like roles['Muted'] or roles.get('Muted') gives me ['692863646543380590']:
Muted=roles.get('Muted')
print(Muted)

the functions take integers,so I have to remove [' from the output and get this: 692863646543380590

slicing just gives me [] no matter what slicing I use:
work=boost1[2:20] *or any other slice*
print(work)
gives out "[]"

why is slicing just not working here? and how do I fix this??

答:
first of all roles['Muted'] is a list, if you want just first element then get it with 0 index then try using int() for converting it to Integer:

```<code>Muted=int(roles.get('Muted')[0]) # or Muted=int(roles['Muted'][0])
</code>```

Muted will be:

```<code>692863646543380590
</code>```

ContentLicense: CC BY-SA 4.0

Body:
first of all roles['Muted'] is a list, if you want just first element then get it with 0 index then try using int() for converting it to Integer:

Muted=int(roles.get('Muted')[0]) # or Muted=int(roles['Muted'][0])

Muted will be:

692863646543380590


问:
fs.open does not open desired file in nodejs
I am just a beginner to nodejs and I came across the fs module. I tried to write a few lines of code.

```<code>var fs = require('fs');

// Open file demo.txt in read mode
fs.open('/users/Upwn/desktop/ashok_pant.txt', 'r+', function (err, f) {
  if(err) throw err;
   console.log('Opened!');
});
</code>```

The output was "Opened!" but nothing was opened from my local file system. What may be wrong with this?

答:
If you want to read file content, please use readFileSync.
Following is my code that I used before.</p>

```<code>const fs = require('fs')
const path = require('path');
let content = JSON.parse(fs.readFileSync(path.join(__dirname, 'products.json')))
for (let line in content) {
    // do something
}
</code>```

Body:
I am just a beginner to nodejs and I came across the fs module. I tried to write a few lines of code.

var fs = require('fs');

// Open file demo.txt in read mode
fs.open('/users/Upwn/desktop/ashok_pant.txt', 'r+', function (err, f) {
  if(err) throw err;
   console.log('Opened!');
});

The output was "Opened!" but nothing was opened from my local file system. What may be wrong with this?

Body:
If you want to read file content, please use readFileSync.
Following is my code that I used before.

const fs = require('fs')
const path = require('path');
let content = JSON.parse(fs.readFileSync(path.join(__dirname, 'products.json')))
for (let line in content) {
    // do something
}


问:
Sum a field only on specific conditions in Oracle SQL
I'm trying to get the amounts from a table where I want to sum some amounts that satisfies a specific condition while retaining the un-summed amount of others if it did not meet the condition.

I was trying this solution but it still doesn't sum up even if it meets the condition.

```<code>SELECT
  price_type,
  CASE trim(price_type)
    WHEN 'TYPE1' THEN sum(bill_amt)
    ELSE bill_amt
  END bill_amt
FROM (
  SELECT
    price_type,
    bill_amt
  FROM price_val_tbl
)
GROUP BY price_type, bill_amt
</code>```

Expected Output:

```<code>PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        50
TYPE2        100
TYPE2        200
</code>```

Actual Output

```<code>PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        100
TYPE1        -50
TYPE2        100
TYPE2        200
</code>```

答:
This is a case where you want UNION ALL:

```<code>SELECT price_type, SUM(bill_amt)
FROM price_val_tbl
WHERE trim(price_type) = 'TYPE1'
GROUP BY price_type
UNION ALL
SELECT price_type, bill_amt
FROM price_val_tbl
WHERE trim(price_type) <> 'TYPE1';
</code>```

The reason you need UNION ALL is because you have no unique identifier on each row.  You could use a subquery and aggregation like this:

```<code>SELECT MIN(price_type) as price_type,
       SUM(bill_amt) as billL_amt
FROM (SELECT pv.*, rownum as rn
      FROM price_val_tbl pv
     ) pv
GROUP BY (CASE WHEN trim(price_type) = 'TYPE1' THEN -1 ELSE rn END) ;
</code>```

However, this is less clear on what it is doing.

Body:
I'm trying to get the amounts from a table where I want to sum some amounts that satisfies a specific condition while retaining the un-summed amount of others if it did not meet the condition.

I was trying this solution but it still doesn't sum up even if it meets the condition.

SELECT
  price_type,
  CASE trim(price_type)
    WHEN 'TYPE1' THEN sum(bill_amt)
    ELSE bill_amt
  END bill_amt
FROM (
  SELECT
    price_type,
    bill_amt
  FROM price_val_tbl
)
GROUP BY price_type, bill_amt

Expected Output:

PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        50
TYPE2        100
TYPE2        200

Actual Output

PRICE_TYPE   BILL_AMT
==========   ========
TYPE1        100
TYPE1        -50
TYPE2        100
TYPE2        200

Body:
This is a case where you want UNION ALL:

SELECT price_type, SUM(bill_amt)
FROM price_val_tbl
WHERE trim(price_type) = 'TYPE1'
GROUP BY price_type
UNION ALL
SELECT price_type, bill_amt
FROM price_val_tbl
WHERE trim(price_type) <> 'TYPE1';

The reason you need UNION ALL is because you have no unique identifier on each row.  You could use a subquery and aggregation like this:

SELECT MIN(price_type) as price_type,
       SUM(bill_amt) as billL_amt
FROM (SELECT pv.*, rownum as rn
      FROM price_val_tbl pv
     ) pv
GROUP BY (CASE WHEN trim(price_type) = 'TYPE1' THEN -1 ELSE rn END) ;

However, this is less clear on what it is doing.


问:
ng-if runs before the time
This is a custom Soundcloud player made with Plangular: a directive that uses AngularJS and Soundcloud API.
Since a lot of Soundcloud tracks are not streamable by third part apps (the GET request returns nothing) and basically they don't work over this player, I'm trying to check with a ng-if="track" and ng-if="!track" if the track is correctly loaded or not, and show a different content.
This is working great, however when you load the page, even if the track is streamable (like the one in my example) it is not loaded on the DOM yet, so for just a couple of seconds I see the content of the negative condition (ng-if="!track"). Is there any trick I can do to avoid this? Maybe is possible to slow down the check of ng-if?

Here is my html code, the {{loading}} is declared in the controller:

```<code><body ng-app="player" ng-controller="SearchBar">
  <div plangular="https://soundcloud.com/ghostbeach/fickle-friends-for-you-ghost-beach-remix-1" ng-cloak>
    <div ng-if="!track"  class="flex flex-center" ng-cloak>
      <i class="fa fa-cog fa-spin fa-1x fa-fw mr1" ng-cloak></i>
      <div class="mr1" ng-cloak>{{loading}}</div>
    </div>
    <!-- close ng-if not streamable -->
    <div class="flex flex-center" ng-if="track">
      <div  class="mr1">
        <img ng-src="{{track.artwork_url}}" alt="{{track.title}}" style="height:60px; width: 60px;" ng-cloak/>
      </div>
      <div ng-click="playPause()"
        title="Play/Pause"
        class="flex-none h0 mr1 button-transparent cursor button-grow">
        <svg ng-if="player.playing !== track.src" class="icon geomicon" data-icon="play" viewBox="0 0 32 32" width="32" height="32" >
          <path d="M4 4 L28 16 L4 28 z "></path>
        </svg>
        <svg ng-if="player.playing === track.src" class="icon geomicon" data-icon="pause" viewBox="0 0 32 32" width="32" height="32" >
          <path d="M4 4 H12 V28 H4 z M20 4 H28 V28 H20 z "></path>
        </svg>
      </div>
      <div class="flex-auto">
        <div class="h5 bold mr2">
          <a target="_blank" ng-href="{{track.permalink_url}}">{{track.title}}</a>
        </div>
        <progress
          class="progress orange"
          ng-click="seek($event)"
          ng-value="currentTime / duration || 0">
        {{ currentTime / duration }}
        </progress>
      </div>
    </div>
    <!-- close nf-if streamable-->
  </div>
</body>
</code>```

Here is my JS:

```<code>var player = angular.module('player', ['plangular'])
   .config(function(plangularConfigProvider){
   plangularConfigProvider.clientId = 'XXX';
});
player.controller('SearchBar', ['$scope',function ($scope){
        $scope.loading="Track is not streamable";
}]);
</code>```

The behavior is more clear in the JSFiddle, when you run the jsfiddle it shows for a couple of seconds the negative condition of ng-if, I would like to avoid that.

EDIT:

Is it possible maybe to set a timeout on a ng-show to the content of ng-if?

答: Since Plangular uses an async method to fetch the track, you can't handle this logic unless to add a return error when the tracks is not sreamable.</p>

ContentLicense: CC BY-SA 3.0

Title: ng-if runs before the time

Body:
This is a custom Soundcloud player made with Plangular: a directive that uses AngularJS and Soundcloud API.
Since a lot of Soundcloud tracks are not streamable by third part apps (the GET request returns nothing) and basically they don't work over this player, I'm trying to check with a ng-if="track" and ng-if="!track" if the track is correctly loaded or not, and show a different content.
This is working great, however when you load the page, even if the track is streamable (like the one in my example) it is not loaded on the DOM yet, so for just a couple of seconds I see the content of the negative condition (ng-if="!track"). Is there any trick I can do to avoid this? Maybe is possible to slow down the check of ng-if?

Here is my html code, the {{loading}} is declared in the controller:

{{loading}}

        <svg ng-if="player.playing !== track.src" class="icon geomicon" data-icon="play" viewBox="0 0 32 32" width="32" height="32" >
          <path d="M4 4 L28 16 L4 28 z "></path>
        </svg>
        <svg ng-if="player.playing === track.src" class="icon geomicon" data-icon="pause" viewBox="0 0 32 32" width="32" height="32" >
          <path d="M4 4 H12 V28 H4 z M20 4 H28 V28 H20 z "></path>
        </svg>

          {{track.title}}

        <progress
          class="progress orange"
          ng-click="seek($event)"
          ng-value="currentTime / duration || 0">
        {{ currentTime / duration }}
        </progress>

Here is my JS:

var player = angular.module('player', ['plangular'])
   .config(function(plangularConfigProvider){
   plangularConfigProvider.clientId = 'XXX';
});
player.controller('SearchBar', ['$scope',function ($scope){
        $scope.loading="Track is not streamable";
}]);

The behavior is more clear in the JSFiddle, when you run the jsfiddle it shows for a couple of seconds the negative condition of ng-if, I would like to avoid that.

EDIT:

Is it possible maybe to set a timeout on a ng-show to the content of ng-if?


问:
Adding tilde to datawindow setFilter string
I've been trying to filter a datawindow by using the argument product_id = 'Z108-20-6,3~10' and company_id = 14, but the setFilter function returns -1, which is invalid.

After looking at the docs and some Google search, I've found that the tilde character is an escape character, so, in order to use it as a literal character, I should be using "~~" instead of "~". Using two tildes in the filter argument does change the return value, but doesn't apply the filter correctly (it keeps showing no rows).

How can I SetFilter a datawindow by using a tilde in the filter expression? I`m using PB 12.5.

答:
Not sure if this will fix your issue but something to try.

From the PB help for the SetFilter method.

The escape keyword designates any character as an escape character (do
  not use a character that is part of the string you want to match). In
  the following example, the asterisk (*) character is inserted before
  the _ character and designated as an escape character, so that the _
  character is treated as part of the string to be matched:

comment like ~'%o_a15progress%~' escape ~'~'


问:
When coding in nodejs, should I worry about context-switching?
I know that node.js my code runs in a single thread, and it is not concurrent, but should I worry about context-switching as a result of multiple REST requests or setTimeout triggers?

In other words, despite not being concurrent, is node.js async?

As an example, in the following code:

```<code>let a = 0;

const inc = () => new Promise(resolve => {
    temp = number;      // 1
    number = temp + 1;  // 2
    resolve();
});
</code>```

If I call inc 10 times, am I guranteed to end up with 10, or can I have a context switch between the lines marked 1 and 2?

答:
You can write asynchronous code in NodeJS.

You'll get indeterminate results if you have code like this:

let a = 0;

new Promise((resolve, reject) => { /* do something */}).then(() => { a = 1; }).then(() => { /* more stuff */});
new Promise((resolve, reject) => { /* do something */}).then(() => { a = 2; }).then(() => { /* more stuff */});
```

Both promises will act on the global variable a, and because there is no way to determine which one will finish first, there is no way to know what the value of a will be going forward in either of the promises.

One last thing - because your question uses the word "worry", it leads me to believe that it's something that'd be on your mind. If that's the case, there are several patterns, like the Reader pattern in functional programming or Dependency Injection, that help mitigate worrying about race conditions. Those are good practices in any language (NodeJS included), so it may be helpful to read up on them.

Body:
I know that node.js my code runs in a single thread, and it is not concurrent, but should I worry about context-switching as a result of multiple REST requests or setTimeout triggers?

In other words, despite not being concurrent, is node.js async?

As an example, in the following code:

let a = 0;

const inc = () => new Promise(resolve => {
    temp = number;      // 1
    number = temp + 1;  // 2
    resolve();
});

If I call inc 10 times, am I guranteed to end up with 10, or can I have a context switch between the lines marked 1 and 2?

Body:
You can write asynchronous code in NodeJS.

You'll get indeterminate results if you have code like this:

let a = 0;

new Promise((resolve, reject) => { /* do something */}).then(() => { a = 1; }).then(() => { /* more stuff */});
new Promise((resolve, reject) => { /* do something */}).then(() => { a = 2; }).then(() => { /* more stuff */});

Both promises will act on the global variable a, and because there is no way to determine which one will finish first, there is no way to know what the value of a will be going forward in either of the promises.

One last thing - because your question uses the word "worry", it leads me to believe that it's something that'd be on your mind. If that's the case, there are several patterns, like the Reader pattern in functional programming or Dependency Injection, that help mitigate worrying about race conditions. Those are good practices in any language (NodeJS included), so it may be helpful to read up on them.


问:
Java .xml creating a drawable button background
New to programming, 3 weeks beginner.
I am making a button with stacked rectangles through drawable xml.

This is my button .xml code, very straight forward:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D5A04F"
    tools:context=".MainActivity">

    <android.support.design.widget.NavigationView
        <Button
            android:id="@+id/leftnavbar"
            android:layout_width="212dp"
            android:layout_height="279dp"

            android:layout_marginTop="16sp"
            android:layout_marginBottom="500sp"
            android:background="@drawable/rounded_rectangle"
             />
    </android.support.design.widget.NavigationView>

</android.support.constraint.ConstraintLayout>
</code>```

and this is my drawable .xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingBottom="@dimen/mr_dialog_fixed_width_minor"
    android:paddingTop="@dimen/mr_dialog_fixed_width_major"
    >

    <item
        android:top="5sp"
        android:left="5sp"
        android:right="5sp"
        android:bottom="50sp">
        <shape android:shape="rectangle">
            <solid android:color="#D3AE71" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="30sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="600sp">s
            <shape android:shape="rectangle">
                <solid android:color="#E6E5E5" />
                <corners android:radius="20sp"/>
            </shape>
    </item>

    <item
        android:top="160sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="470sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="290sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="340sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="420sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="210sp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="550sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="80sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>
</layer-list>
</code>```

The only item that is shown in drawable is the first, the rest of the rectangles fail to show.
Suggestions or pointers to the reason will be much apreciated. thank you for your time and attention...

答: Your button's height is too short,chang android:layout_height="279dp" to  android:layout_height="700dp"</p>

Body:
New to programming, 3 weeks beginner.
I am making a button with stacked rectangles through drawable xml.

This is my button .xml code, very straight forward:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D5A04F"
    tools:context=".MainActivity">

    <android.support.design.widget.NavigationView
        <Button
            android:id="@+id/leftnavbar"
            android:layout_width="212dp"
            android:layout_height="279dp"

            android:layout_marginTop="16sp"
            android:layout_marginBottom="500sp"
            android:background="@drawable/rounded_rectangle"
             />
    </android.support.design.widget.NavigationView>

</android.support.constraint.ConstraintLayout>

and this is my drawable .xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingBottom="@dimen/mr_dialog_fixed_width_minor"
    android:paddingTop="@dimen/mr_dialog_fixed_width_major"
    >

    <item
        android:top="5sp"
        android:left="5sp"
        android:right="5sp"
        android:bottom="50sp">
        <shape android:shape="rectangle">
            <solid android:color="#D3AE71" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="30sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="600sp">s
            <shape android:shape="rectangle">
                <solid android:color="#E6E5E5" />
                <corners android:radius="20sp"/>
            </shape>
    </item>

    <item
        android:top="160sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="470sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="290sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="340sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="420sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="210sp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="550sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="80sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>
</layer-list>

The only item that is shown in drawable is the first, the rest of the rectangles fail to show.
Suggestions or pointers to the reason will be much apreciated. thank you for your time and attention...


问:
Position element according to body instead of the relative parent
I have a div with position relative and two children using it and both have position absolute. And I need them. But I want to make another child inside the relative div and give it the position absolute. But now the problem is that I want some part of it to appear outside of the element. So how can I do it in CSS? Thanks in advance.

Reference to what I need is: Example of what I need, check the search icon. How it is placed. I want that kind of thing.

```<code>div {
   //Parent div
    position:relative;
}
div {
   //Child div
    position:absolute;
}
div {
   //Child div
    position:absolute;
   //This is an emoji
   //But I want this to appear half outside of the parent div,
   //i.e. on the border of the parent div
}
</code>```

答: Use vw or vh in your positioning. If you use for example: 50% it will get the width of the parent and then divide it by 2. If you use vw(width of page) or vh(height of page) it takes the width and height of the whole page. Should work for you. Remember your positioning is important as well.</p>

Body:
I have a div with position relative and two children using it and both have position absolute. And I need them. But I want to make another child inside the relative div and give it the position absolute. But now the problem is that I want some part of it to appear outside of the element. So how can I do it in CSS? Thanks in advance.

Reference to what I need is: Example of what I need, check the search icon. How it is placed. I want that kind of thing.

div {
   //Parent div
    position:relative;
}
div {
   //Child div
    position:absolute;
}
div {
   //Child div
    position:absolute;
   //This is an emoji
   //But I want this to appear half outside of the parent div,
   //i.e. on the border of the parent div
}


问:
Why does the sun jdk source code not contain the javax.servlet package?
I tried to find the source code of the javax.servlet package in the jdk source code, but it seems the jdk doesn't contains the package. Where can I download the package?</p>

答:
Why the sun jdk source code dose not contains the javax.servlet package?

Because it is part of Java EE, not Java SE.

where can I download the package?

The JARs are part of your Java EE platform; e.g. Tomcat, JBoss, Glassfish, etc.


问:
discord runtimeError ('SSL is not supported.')
When I open Pycharm, create and run a discorded bot, I get this error:

```<code>Traceback (most recent call last):
  File "C:/Users/sghan/PycharmProjects/discordbot/milkbot.py", line 36, in <module>
    client.run('NzE2OTk0ODcyNDAxMzMwMjA3.XtYgFA.JOVxgA__TwM9TKnFs905n6zftFM')
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET','/users/@me'))
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 483, in _request
    timeout=real_timeout
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 859, in _create_connection
    req, traces, timeout)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 953, in
    _create_direct_connection
    sslcontext = self._get_ssl_context(req)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 901, in _get_ssl_context
    raise RuntimeError('SSL is not supported.')
RuntimeError: SSL is not supported.
</code>```

The source code is like this:

```<code>import discord
import asyncio

client = discord.Client()

@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')

@client.event
async def on_message(message):
if message.content.startswith('!test'):
await client.send_message(message.channel,'test!!!!')

elif message.content.startswith('!say'):
await client.send_message(message.channel,'leave message')
msg = await client.wait_for_message(timeout=15.0, author=message.author)

if msg is None:
await client.send_message(message.channel,'Please enter within 15 seconds. Retry: !say')
return
else:
await client.send_message(message.channel, msg.content)

client.run('token')
</code>```

答:
First of all, change your TOKEN, you've just revealed it by posting your traceback.

Also, it seems you're using an old version of discord.py which is depreciated.

Try to update your discord.py module to a version >= 1.3 and try again.

You should dump your current discord.py version by running this command :

```<code>pip3 uninstall discord.py
</code>```

Click here to see how to install the new version.

Body:
When I open Pycharm, create and run a discorded bot, I get this error:

Traceback (most recent call last):
  File "C:/Users/sghan/PycharmProjects/discordbot/milkbot.py", line 36, in <module>
    client.run('NzE2OTk0ODcyNDAxMzMwMjA3.XtYgFA.JOVxgA__TwM9TKnFs905n6zftFM')
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET','/users/@me'))
  File "C:\ProgramData\Anaconda3\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 483, in _request
    timeout=real_timeout
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 859, in _create_connection
    req, traces, timeout)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 953, in
    _create_direct_connection
    sslcontext = self._get_ssl_context(req)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 901, in _get_ssl_context
    raise RuntimeError('SSL is not supported.')
RuntimeError: SSL is not supported.

The source code is like this:

import discord
import asyncio

client = discord.Client()

@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')

@client.event
async def on_message(message):
if message.content.startswith('!test'):
await client.send_message(message.channel,'test!!!!')

elif message.content.startswith('!say'):
await client.send_message(message.channel,'leave message')
msg = await client.wait_for_message(timeout=15.0, author=message.author)

if msg is None:
await client.send_message(message.channel,'Please enter within 15 seconds. Retry: !say')
return
else:
await client.send_message(message.channel, msg.content)

client.run('token')

Body:
First of all, change your TOKEN, you've just revealed it by posting your traceback.

Also, it seems you're using an old version of discord.py which is depreciated.

Try to update your discord.py module to a version >= 1.3 and try again.

You should dump your current discord.py version by running this command :

pip3 uninstall discord.py

Click here to see how to install the new version.


问:
Can I create Python Pandas ExcelWriter format without pre-creating a workbook object?
I want to create a fixed format for ExcelWriter in Pandas which I could use in many scripts, without needing to write it everytime. I know I can create a format with:

```<code>import pandas as pd
writer = pd.ExcelWriter('demo.xlsx', engine='xlsxwriter')
workbook = writer.book
num_fmt = workbook.add_format({'num_format': '#,##0.0'})
</code>```

And then use num_fmt with:

```<code>worksheet.set_column('H:H', 8, num_fmt)
</code>```

But I'm looking for a way to avoid re-defining num_fmt in every script I write. I have a self-defined package named my_pack that I import to every script, and I want to somehow define num_fmt there, so I could use it like:

```<code>worksheet.set_column('H:H', 8, my_pack.num_fmt)
</code>```

without defining num_fmt in the current script.
Is that possible?

答:
I have a self-defined package named my_pack that I import to every script, and I want to somehow define num_fmt there ... without defining num_fmt in the current script. Is that possible?

No. Not with XlsxWriter.

You need to instantiate a format from a Workbook object and it is unique to each workbook, so you won't be able to create it once, store it, and then reuse it in different workbooks.

Body:
I want to create a fixed format for ExcelWriter in Pandas which I could use in many scripts, without needing to write it everytime. I know I can create a format with:

import pandas as pd
writer = pd.ExcelWriter('demo.xlsx', engine='xlsxwriter')
workbook = writer.book
num_fmt = workbook.add_format({'num_format': '#,##0.0'})

And then use num_fmt with:

worksheet.set_column('H:H', 8, num_fmt)

But I'm looking for a way to avoid re-defining num_fmt in every script I write. I have a self-defined package named my_pack that I import to every script, and I want to somehow define num_fmt there, so I could use it like:

worksheet.set_column('H:H', 8, my_pack.num_fmt)

without defining num_fmt in the current script.
Is that possible?


问:
Prolog - Deleting Nth Row From A Matrix
I'm trying to create a query elimrow(_, [H|T], X) that deletes the nth row in a matrix array.

Sample:

```<code>?- elimrow(-3,[[1,2],[3,4],[5,6]], X). => X = [[1,2],[3,4],[5,6]]
?- elimrow(2,[[1,2],[3,4],[5,6]], X). => X = [[1,2],[5,6]]
</code>```

So far I was able to create this:

```<code>elimrow(1, [H|_], H).
elimrow(I, [H|T], X) :-
   I1 is I-1, elimrow(I1, T, X), delete(X, [H|T], B), writeln(B).

delete(A, [A|B], B).
delete(A, [B, C|D], [B|E]) :- delete(A, [C|D], E).
</code>```

This is currently able to select the row which I want to delete. However the delete function isn't functioning fully as expected.

```<code>?- elimrow(2,[[1,2],[3,4],[5,6]],X).
[[1,2],[5,6]]
X = [3, 4]
</code>```

It outputs the correct deleted array [[1,2], [5,6]], however it also outputs a X = [3,4]

I'm confused as to why there was a second output. (I only had one writeln(B)).

I also tried checking it with my first sample and it returned with false when it's not supposed to delete anything.

```<code>?- elimrow(-3, [[1,2],[3,4],[5,6]],X).
false.
</code>```

Appreciate any help on this. Many thanks!

答:
I think you make it too complicated. Your matrix is just a list of lists. So you can delete the I-th element of a list:

```<code>eliminate(_, [], []).
eliminate(0, [_|T], T).
eliminate(I, [H|T], [H|R]) :-
    I > 0,
    I1 is I-1,
    eliminate(I1, T, R).</code>```

Title: Prolog - Deleting Nth Row From A Matrix

Body:
I'm trying to create a query elimrow(_, [H|T], X) that deletes the nth row in a matrix array.

Sample:

?- elimrow(-3,[[1,2],[3,4],[5,6]], X). => X = [[1,2],[3,4],[5,6]]
?- elimrow(2,[[1,2],[3,4],[5,6]], X). => X = [[1,2],[5,6]]

So far I was able to create this:

elimrow(1, [H|_], H).
elimrow(I, [H|T], X) :-
   I1 is I-1, elimrow(I1, T, X), delete(X, [H|T], B), writeln(B).

delete(A, [A|B], B).
delete(A, [B, C|D], [B|E]) :- delete(A, [C|D], E).

This is currently able to select the row which I want to delete. However the delete function isn't functioning fully as expected.

?- elimrow(2,[[1,2],[3,4],[5,6]],X).
[[1,2],[5,6]]
X = [3, 4]

It outputs the correct deleted array [[1,2], [5,6]], however it also outputs a X = [3,4]

I'm confused as to why there was a second output. (I only had one writeln(B)).

I also tried checking it with my first sample and it returned with false when it's not supposed to delete anything.

?- elimrow(-3, [[1,2],[3,4],[5,6]],X).
false.

Appreciate any help on this. Many thanks!

Body:
I think you make it too complicated. Your matrix is just a list of lists. So you can delete the I-th element of a list:

eliminate(_, [], []).
eliminate(0, [_|T], T).
eliminate(I, [H|T], [H|R]) :-
    I > 0,
    I1 is I-1,
    eliminate(I1, T, R).


问:
How to search through a DB using a cursor( sqlite query) in android
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.</p>

```<code>        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});
</code>```

答:
```<code> Cursor   mCursor = db.rawQuery("select ZIPCODE from TABLENAME where CITYNAME= ? ", new String[]{"NEWYORK"});
</code>```

hope you got the single result only.

then to get it from(incase of string means) mCursor.getString(coloumn_id)

Body:
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.

        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});

Body:
 Cursor   mCursor = db.rawQuery("select ZIPCODE from TABLENAME where CITYNAME= ? ", new String[]{"NEWYORK"});

hope you got the single result only.

then to get it from(incase of string means) mCursor.getString(coloumn_id)


问:
How to extract a substring from a string in a column, that matches another string in a list in python
I have a dataframe which is as follows:

```<code>     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP
</code>```

With a list similar to:

```<code>[Stevenage, Essex, Coventry, Chester]
</code>```

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

```<code>city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')
</code>```

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

```<code>     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry
</code>```

I have tried:

```<code>pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))
</code>```

But this returned an error saying 456 inputs when expecting 1.

Also:

```<code>df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)
</code>```

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

答:
have a look at str.contains function that tests if a pattern match a series:

```<code>df = pd.DataFrame([[59, '538 Walton Avenue, Chester,', 'FY6 7NP'],
                   [62, '42 Chesterton Road, Peterborough', '4HG 3HT'],
                   [179, '3 Wallbridge Street, Essex', '4HG 3HT'],
                   [180, '6 Stevenage Avenue, Coventry', '7PY 9NP']])
city_list = ["Stevenage", "Essex", "Coventry", "Chester"]
for city in city_list:
    df.loc[df[1].str.contains(city), 'match'] = city
</code>```

Body:
I have a dataframe which is as follows:

     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP

With a list similar to:

[Stevenage, Essex, Coventry, Chester]

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry

I have tried:

pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))

But this returned an error saying 456 inputs when expecting 1.

Also:

df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

Body:
have a look at str.contains function that tests if a pattern match a series:

df = pd.DataFrame([[59, '538 Walton Avenue, Chester,', 'FY6 7NP'],
                   [62, '42 Chesterton Road, Peterborough', '4HG 3HT'],
                   [179, '3 Wallbridge Street, Essex', '4HG 3HT'],
                   [180, '6 Stevenage Avenue, Coventry', '7PY 9NP']])
city_list = ["Stevenage", "Essex", "Coventry", "Chester"]
for city in city_list:
    df.loc[df[1].str.contains(city), 'match'] = city


问:
Laravel Datatables getting net::ERR_EMPTY_RESPONSE error when adding extra column
I'm using DataTable 1.10.21 with Laravel 7. I'm trying to populate all of the users data, except my user table has an additional column named group_id, which define the user group (ie. admin, manager, user etc)

Right now my user model has this relationship:

```<code>public function group() {
        return $this->belongsTo(Group::class);
    }
</code>```

When I call

```<code>App\User::select(*)->with('group')->get();
</code>```

I'll get something like this which is good:

```<code>App\User {#105150
         id: 1,
         group_id: 1,
         name: "Admin",
         email: "admin@admin.com",
         email_verified_at: "2020-01-01 01:01:01",
         ...
         deleted_at: null,
         group: App\Group {#105096
           id: 1,
           name: "admin",
         },
       }
       ...
</code>```

In my UserController I have this function:

```<code>public function datatable() {
        $data = User::select("*")->with('group');
        $dt = Datatables::of($data)->make(true);
        \Log::debug($dt); //this works!!
        return $dt;
    }
</code>```

I can use tinker to get $data and $dt without any problem.

My view contains the following javascript:

```<code>$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group_id' }, /* this won't work */
                        { data: 'group.name', name: 'group.name' }, /* this won't work either */
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });
</code>```

```<code><table class="table table-bordered" id="table">
               <thead>
                  <tr>
                     <th>ID</th>
                     <th>Name</th>
                     <th>Group ID</th>
                     <th>Group Name</th>
                     <th>Creation Date</th>
                     <th>Email</th>
                  </tr>
               </thead>
            </table>
</code>```

Neither of the group_id or group.name col will work. (net::ERR_EMPTY_RESPONSE error even $dt has response) but if I remove both columns then it works fine.

Please advise.

Edit: May 29 2020

I digged a little deeper and here's what I have found:

If I use my local test domain (ie. myproject.test)

If I remove some other columns (ie. created at, email) it worked

If I include all columns (ie. id, name, group_id, group.name, created_at, email) I got the ERR_EMPTY_RESPONSE error

If I use 127.0.0.1:8000

it worked even if I include all columns!!!!

Can someone please explain to me why??

答:
If you are using Yajra\DataTables, then I can see that you don't specify a few columns well. Let's get from the beginning.

First, change in your controller to be like this:

use Yajra\DataTables\DataTables;

    public function datatable() {
        $data = User::with(['group'])->select("users.*"); // Also select can throw ambiguous column error

        return Datatables::of($data)
           ->addColumn('group_id', function ($user) {
                return !empty($user->group) ? $user->group->id : '';
           })->addColumn('group_name', function ($user) {
                return !empty($user->group) ? $user->group->name : '';
           })->toJson(true); // Please note this line also
    }
```

<p>Then in your JS: </p>

<pre class="lang-js prettyprint-override"><code>$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group.id' }, // Data is specified data in controller and name is relationship data
                        { data: 'group_name', name: 'group.name' },
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });

</code>```

Body:
I'm using DataTable 1.10.21 with Laravel 7. I'm trying to populate all of the users data, except my user table has an additional column named group_id, which define the user group (ie. admin, manager, user etc)

Right now my user model has this relationship:

public function group() {
        return $this->belongsTo(Group::class);
    }

When I call

App\User::select(*)->with('group')->get();

I'll get something like this which is good:

App\User {#105150
         id: 1,
         group_id: 1,
         name: "Admin",
         email: "admin@admin.com",
         email_verified_at: "2020-01-01 01:01:01",
         ...
         deleted_at: null,
         group: App\Group {#105096
           id: 1,
           name: "admin",
         },
       }
       ...

In my UserController I have this function:

public function datatable() {
        $data = User::select("*")->with('group');
        $dt = Datatables::of($data)->make(true);
        \Log::debug($dt); //this works!!
        return $dt;
    }

I can use tinker to get $data and $dt without any problem.

My view contains the following javascript:

$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group_id' }, /* this won't work */
                        { data: 'group.name', name: 'group.name' }, /* this won't work either */
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });

                     ID
                     Name
                     Group ID
                     Group Name
                     Creation Date
                     Email

Neither of the group_id or group.name col will work. (net::ERR_EMPTY_RESPONSE error even $dt has response) but if I remove both columns then it works fine.

Please advise.

Edit: May 29 2020

I digged a little deeper and here's what I have found:

If I use my local test domain (ie. myproject.test)

If I remove some other columns (ie. created at, email) it worked

If I include all columns (ie. id, name, group_id, group.name, created_at, email) I got the ERR_EMPTY_RESPONSE error

If I use 127.0.0.1:8000

it worked even if I include all columns!!!!

Can someone please explain to me why??

Body:
If you are using Yajra\DataTables, then I can see that you don't specify a few columns well. Let's get from the beginning.

First, change in your controller to be like this:

use Yajra\DataTables\DataTables;

    public function datatable() {
        $data = User::with(['group'])->select("users.*"); // Also select can throw ambiguous column error

        return Datatables::of($data)
           ->addColumn('group_id', function ($user) {
                return !empty($user->group) ? $user->group->id : '';
           })->addColumn('group_name', function ($user) {
                return !empty($user->group) ? $user->group->name : '';
           })->toJson(true); // Please note this line also
    }

Then in your JS:

$(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('user/datatable') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'group_id', name: 'group.id' }, // Data is specified data in controller and name is relationship data
                        { data: 'group_name', name: 'group.name' },
                        { data: 'created_at', name: 'created_at' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });


问:
Getting an error when creating a conda environment
I try to make a conda environment for my tensorflow code but when i try it says: CondaValueError: The target prefix is the base prefix. Aborting.

```<code>C:\Users\waabe>conda create -m tensor python=3.6

CondaValueError: The target prefix is the base prefix. Aborting.
</code>```

I was watching a tutorial made by Tech With Tim and for him it worked.

Could you help me?

答:
The command is like:

$ conda create -n tensor python=3.6
```

Reference: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands

Body:
I try to make a conda environment for my tensorflow code but when i try it says: CondaValueError: The target prefix is the base prefix. Aborting.

C:\Users\waabe>conda create -m tensor python=3.6

CondaValueError: The target prefix is the base prefix. Aborting.

I was watching a tutorial made by Tech With Tim and for him it worked.

Could you help me?

Body:
The command is like:

$ conda create -n tensor python=3.6

Reference: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands


问:
jquery MMENU opened default
Anyone can help me how to display the navbar by default once the page loads? Currently the navbar hides, I just want to show the sidebar menu as a default. Thank you!</p>

```<code>script -
 $("#mmenu").mmenu({ navbar: !1 });

html-
<link href="catalog/view/javascript/jquery/mmenu/css/jquery.mmenu.all.css" rel="stylesheet" media="screen" />
<script src="catalog/view/javascript/jquery/mmenu/js/jquery.mmenu.all.min.js" type="text/javascript"></script>

<nav id="mmenu">
  <ul>
    <li class="logo-menu"></li>
    <li><a>Home</a></li>
  </ul>
</nav>
<div class="page">
<header>
  <a href="#mmenu" id="hamburger"><span class="top-bar"></span><span class="middle-bar"></span><span class="bottom-bar"></span></a>
  <div class="container">
  </div>
</header></div>
</code>```

答:
Use

$( document ).ready(function() {
        $('put your id/class of the menu/nav').show();
    });

Example

$( document ).ready(function() {
    $('#menu').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu{
display:none;
background:blue;
}</code>```

menu

```

Title: jquery MMENU opened default

Body:
Anyone can help me how to display the navbar by default once the page loads? Currently the navbar hides, I just want to show the sidebar menu as a default. Thank you!

script -
 $("#mmenu").mmenu({ navbar: !1 });

html-
<link href="catalog/view/javascript/jquery/mmenu/css/jquery.mmenu.all.css" rel="stylesheet" media="screen" />

Home

Body:
Use

$( document ).ready(function() {
        $('put your id/class of the menu/nav').show();
    });

Example

$( document ).ready(function() {
    $('#menu').show();
});

#menu{
display:none;
background:blue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="menu">
menu
</div>


问:
Can't direct a domain to a static page using AWS S3
I followed this tutorial How to Point your Domain to an S3 Website Bucket and it works well.

My domain e.g. domain.com points my S3 Bucket bucket.com.s3-website.eu-central-1.amazonaws.com.

However, the index.html does not show by default e.g. if I use the URL domain.com I get this:

```<code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>AE243F85AC91D283</RequestId>
<HostId>zAcaxygehDiR1EC6/JJADndO+JlvA7dYSAu+uOL7qWtdDGWLLQ+vGCoqescLUAKLH51/kLD/StM=</HostId>
</Error>
</code>```

However, if I use domain.com/index.html or bucket.com.s3-website.eu-central-1.amazonaws.com the index.html page appears.

It's only if I use domain.com instead of the above that it doesn't show.

The bucket has all public permissions.

答:
You're getting an error. If you are only interested in showing the index.html page whenever the plain domain.com url is used, then you need to specify index.html as the error page as well.

Alternatively, you can do this with a redirect rule in the box below

```<code><RoutingRules>
    <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals >
    </Condition>
    <Redirect>
      <ReplaceKeyWith>index.html</ReplaceKeyWith>
    </Redirect>
    </RoutingRule>
</RoutingRules>
</code>```

Body:
I followed this tutorial How to Point your Domain to an S3 Website Bucket and it works well.

My domain e.g. domain.com points my S3 Bucket bucket.com.s3-website.eu-central-1.amazonaws.com.

However, the index.html does not show by default e.g. if I use the URL domain.com I get this:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>AE243F85AC91D283</RequestId>
<HostId>zAcaxygehDiR1EC6/JJADndO+JlvA7dYSAu+uOL7qWtdDGWLLQ+vGCoqescLUAKLH51/kLD/StM=</HostId>
</Error>

However, if I use domain.com/index.html or bucket.com.s3-website.eu-central-1.amazonaws.com the index.html page appears.

It's only if I use domain.com instead of the above that it doesn't show.

The bucket has all public permissions.

Body:
You're getting an error. If you are only interested in showing the index.html page whenever the plain domain.com url is used, then you need to specify index.html as the error page as well.

Alternatively, you can do this with a redirect rule in the box below

<RoutingRules>
    <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals >
    </Condition>
    <Redirect>
      <ReplaceKeyWith>index.html</ReplaceKeyWith>
    </Redirect>
    </RoutingRule>
</RoutingRules>


问:
specific leaflet layer style to change dynamically based on django tags
Potion of my html code do do style

```<code><script type="text/javascript">
         function our_Layers (map, options){
            var datasets = new L.GeoJSON.AJAX("{% url 'owner' %}",{

                style: function colors(feature){
                    switch(feature.properties.lr){
                        case "{{LR}}":
                            return{
                                color: 'red'
                            };
                        break
                    }
                },

                onEachFeature: function(feature, layer){
                    //layer.bindPopup(feature.properties.lr.toString());
                    layer.bindPopup('<strong>LR No.: </strong>'+ feature.properties.lr.toString()
                   );
                }
            });
            datasets.addTo(map);

         }
    </script>

    {% leaflet_map "parcels" callback="window.our_Layers" %}
</code>```

my view in django

```<code>def Usermap(request):
    plots1 = request.user.person.Persona.all()

    for Registration in plots1:
        LR=(Registration.parcels.lr)
    context = {'plots':plots1,'LR':LR}
    return render(request, 'Cadastre/Usermap.html', context)
</code>```

Have used that for loop in django to show me available lr which are 3 but i cant use django for loop tags inside the leaflet function any help

答:
I found a way to go around it..first i perform a for loop in django views and append my result in a list.
example

```<code>def Usermap(request):
    plots1 = request.user.person.Persona.all()
    LR =[]

    for Registration in plots1:
        LR.append(Registration.parcels.lr)
    context = {'plots':plots1,'LR':LR}
    return render(request, 'Cadastre/Usermap.html', context)
</code>```

then do another loop in html to access the list items and use it to style my map dynamically.
example

```<code><script type="text/javascript">
datasets = new L.GeoJSON.AJAX("{% url 'Plots' %}",{
 style: function colors(feature){
     var LRS = {{LR|safe}};
     var x;
     for (x of LRS){
         switch(feature.properties.lr){
            case x:
                 return{
                    color: 'red'
                 };
            break
         }
      }
 },
    onEachFeature: onEachFeature
}).addTo(map);
</script>
</code>```

I hope this help someone with same issue since there is no other answer thank you.

Body:
Potion of my html code do do style

    {% leaflet_map "parcels" callback="window.our_Layers" %}

my view in django

def Usermap(request):
    plots1 = request.user.person.Persona.all()

    for Registration in plots1:
        LR=(Registration.parcels.lr)
    context = {'plots':plots1,'LR':LR}
    return render(request, 'Cadastre/Usermap.html', context)

Have used that for loop in django to show me available lr which are 3 but i cant use django for loop tags inside the leaflet function any help

Body:
I found a way to go around it..first i perform a for loop in django views and append my result in a list.
example

def Usermap(request):
    plots1 = request.user.person.Persona.all()
    LR =[]

    for Registration in plots1:
        LR.append(Registration.parcels.lr)
    context = {'plots':plots1,'LR':LR}
    return render(request, 'Cadastre/Usermap.html', context)

then do another loop in html to access the list items and use it to style my map dynamically.
example

<script type="text/javascript">
datasets = new L.GeoJSON.AJAX("{% url 'Plots' %}",{
 style: function colors(feature){
     var LRS = {{LR|safe}};
     var x;
     for (x of LRS){
         switch(feature.properties.lr){
            case x:
                 return{
                    color: 'red'
                 };
            break
         }
      }
 },
    onEachFeature: onEachFeature
}).addTo(map);
</script>

I hope this help someone with same issue since there is no other answer thank you.


问:
escaping string - php in html element
i know this is really obvious but i just don't know what I'm missing. </p>

```<code>$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`
</code>```

<p>thanks </p>

答:
For starters, I'd break it up.  Also, swap your double quotes for single quotes:</p>

```<code>$option[] = implode('', array(
    '<option value="user" selected="',
    $row[5] == 'admin' ? 'selected' : '',
    '">user</option>'
));
</code>```

Title: escaping string - php in html element

Body:
i know this is really obvious but i just don't know what I'm missing.

$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`

thanks

Body:
For starters, I'd break it up.  Also, swap your double quotes for single quotes:

$option[] = implode('', array(
    '<option value="user" selected="',
    $row[5] == 'admin' ? 'selected' : '',
    '">user</option>'
));


问:
How to find distinct dates across multiple tables / columns
I have a project planner app. Part of the app shows the project's timeline.
There are three tables that hold the timeline info; Stage_Plan, Target_Date, Actual_Date.

I want to be able to list all the dates that a change has been made to the project timeline.

All three tables have "Created_DateTime" & "Deleted_Datetime" (If a user deletes a stage or edits a Target_Date then "Is_Deleted" is set to true and that stage/old date is hidden from view).

So I want to get all distinct cases of these two dates across the three tables.

Is the best/only way to do this to do 6 select statements and union the results together?

i.e

```<code>SELECT DISTINCT CAST(Created_DateTime AS Date)
FROM stg.Stage_Plan

UNION

SELECT DISTINCT CAST(Deleted_DateTime AS Date)
FROM stg.Stage_Plan

UNION

SELECT DISTINCT CAST(AD.Created_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Actual_Date AD ON SP.Stage_Plan_ID = AD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(AD.Deleted_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Actual_Date AD ON SP.Stage_Plan_ID = AD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(TD.Deleted_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Target_Date TD ON SP.Stage_Plan_ID = TD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(TD.Created_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Target_Date TD ON SP.Stage_Plan_ID = TD.Stage_Plan_ID
</code>```

This just seems very ugly.
(I know the DISTINCT is irrelevant because I am doing a UNION)

Wanted output is a list all the dates that a change has been made to the project timeline e.g:

```<code>2020-05-29
2020-06-01
</code>```

答:
You can use cross apply. I think that the following query does what you want:

```<code>select distinct x.dt
from stg.Stage_Plan sp
left join stg.stage_plan_actual_date ad on sp.stage_plan_id = ad.stage_plan_id
left join stg.stage_plan_target_date td on sp.stage_plan_id = td.stage_plan_id
cross apply (values
    (sp.Created_DateTime), (sp.Deleted_DateTime),
    (ad.Created_DateTime), (ad.Deleted_DateTime),
    (td.Created_DateTime), (td.Deleted_DateTime)
) x(dt)
where sp.stage_plan_id = ?
</code>```

Presumably you want data for a given project, if so you should also have a where clause in the query - I added that.

Body:
I have a project planner app. Part of the app shows the project's timeline.
There are three tables that hold the timeline info; Stage_Plan, Target_Date, Actual_Date.

I want to be able to list all the dates that a change has been made to the project timeline.

All three tables have "Created_DateTime" & "Deleted_Datetime" (If a user deletes a stage or edits a Target_Date then "Is_Deleted" is set to true and that stage/old date is hidden from view).

So I want to get all distinct cases of these two dates across the three tables.

Is the best/only way to do this to do 6 select statements and union the results together?

i.e

SELECT DISTINCT CAST(Created_DateTime AS Date)
FROM stg.Stage_Plan

UNION

SELECT DISTINCT CAST(Deleted_DateTime AS Date)
FROM stg.Stage_Plan

UNION

SELECT DISTINCT CAST(AD.Created_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Actual_Date AD ON SP.Stage_Plan_ID = AD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(AD.Deleted_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Actual_Date AD ON SP.Stage_Plan_ID = AD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(TD.Deleted_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Target_Date TD ON SP.Stage_Plan_ID = TD.Stage_Plan_ID

UNION

SELECT DISTINCT CAST(TD.Created_DateTime AS Date)
FROM stg.Stage_Plan SP
     JOIN stg.Stage_Plan_Target_Date TD ON SP.Stage_Plan_ID = TD.Stage_Plan_ID

This just seems very ugly.
(I know the DISTINCT is irrelevant because I am doing a UNION)

Wanted output is a list all the dates that a change has been made to the project timeline e.g:

2020-05-29
2020-06-01

Body:
You can use cross apply. I think that the following query does what you want:

select distinct x.dt
from stg.Stage_Plan sp
left join stg.stage_plan_actual_date ad on sp.stage_plan_id = ad.stage_plan_id
left join stg.stage_plan_target_date td on sp.stage_plan_id = td.stage_plan_id
cross apply (values
    (sp.Created_DateTime), (sp.Deleted_DateTime),
    (ad.Created_DateTime), (ad.Deleted_DateTime),
    (td.Created_DateTime), (td.Deleted_DateTime)
) x(dt)
where sp.stage_plan_id = ?

Presumably you want data for a given project, if so you should also have a where clause in the query - I added that.


问:
Cloud Formation - can't upload template file
I try and create a stack by uploading a template.

That fails with an error heading that is blank.

I have permissions to create buckets, upload files, create EC2 instances, etc.
I tried switching to my root account even but that didn't help.

I've tried different YAML files and examples but none seem to work.
Without meaningful error messages with actionable items I am stuck.

```<code>{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "213de823-ad0a-4f4c-af04-e3c9e565eef8": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": 581,
                    "y": 148
                },
                "z": 0
            }
        }
    },
    "Resources": {
        "EC2I4PJFK": {
            "Type": "AWS::EC2::Instance",
            "Properties": {},
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "213de823-ad0a-4f4c-af04-e3c9e565eef8"
                }
            }
        }
    }
}
</code>```

答:
Adding following policy to my role(in your case, it may be a role or a user) worked for me:</p>

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::cf-template*"
        }
    ]
}
</code>```

Body:
I try and create a stack by uploading a template.

That fails with an error heading that is blank.

I have permissions to create buckets, upload files, create EC2 instances, etc.
I tried switching to my root account even but that didn't help.

I've tried different YAML files and examples but none seem to work.
Without meaningful error messages with actionable items I am stuck.

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "213de823-ad0a-4f4c-af04-e3c9e565eef8": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": 581,
                    "y": 148
                },
                "z": 0
            }
        }
    },
    "Resources": {
        "EC2I4PJFK": {
            "Type": "AWS::EC2::Instance",
            "Properties": {},
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "213de823-ad0a-4f4c-af04-e3c9e565eef8"
                }
            }
        }
    }
}

Body:
Adding following policy to my role(in your case, it may be a role or a user) worked for me:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::cf-template*"
        }
    ]
}


问:
How to convert an internal numeric date to Access Date/Time format?
I get some data from a PICK/UniVerse database that includes dates in a 4 or 5 character numeric format. Here are some examples .. I grabbed the date values from the database, and compared it to the date being shown in an application:

```<code>9832       12/1/1994
10027      6/14/1995
10594      1/1/1997
</code>```

Is it possible to convert these into something that can be put into Access as a Date/Time value?

As A test, I put 9832 in Excel as a General format and then change it to Short Date, it comes up as 12/1/1926. So it's off by exactly 68 years. This was true for 10027 and 10594 as well.

答:
All multivalue database dates (this includes UniVerse and UniData) are based on a base date of 31st December 1967. You can resolve this to an external data in a number of ways.

The favourite - e.g. if using SQL or one of the internal database tools is to create a data dictionary entry for the field concerned with a date conversion field, For example:

'D2' for a 2-digit year
'D4' for a 4-digit year
'D4/' for a 4-digit year with slash separators
'D4/E' for a 4-digit year with slash separators and explicitly in European format (DD/MM/YYYY) as compared to US format (MM/DD/YYYY).

If no explicit formatting is given then the format will default to environmental settings. There are other formatting options as well and many can be used in combination (as with the above).

As previously advised, the alternative is to adjust the raw date with a formula. The date is in days since 31st December 1967 - The base data for all multivalue databases.

Body:
I get some data from a PICK/UniVerse database that includes dates in a 4 or 5 character numeric format. Here are some examples .. I grabbed the date values from the database, and compared it to the date being shown in an application:

9832       12/1/1994
10027      6/14/1995
10594      1/1/1997

Is it possible to convert these into something that can be put into Access as a Date/Time value?

As A test, I put 9832 in Excel as a General format and then change it to Short Date, it comes up as 12/1/1926. So it's off by exactly 68 years. This was true for 10027 and 10594 as well.


问:
How to save files locally using html5
how can i download mp3 files locally and then play them using a html5 player , the files should be there even user quit the browser or even come back after couple of days.</p>

答:
HTML5 introduced the manifest attribute to the HTML element, which lets you specify a manifest of files to cache locally. All of the examples I saw cache only HTML, CSS, and JS pages, but you could experiment with caching other types of data.

For more information, see:

http://www.webreference.com/authoring/languages/html/HTML5-Application-Caching/
http://www.w3.org/TR/html5/offline.html

Title: How to save files locally using html5


问:
Is there a way to use jests toHaveBeenCalledWith to check arguments array length?
Function would be called with:

{ items: [1, 2, 3]}

expect(mockedFunction).toHaveBeenCalledWith(
      expect.objectContaining({
        items: expect.toBeLengthOf(3) // Pseudocode, this function does not exist here
      }),
    );
```

答:
.mock object on mocked function has .calls list on it. So

```<code>expect(
  mockedFunction.mock.calls[mockedFunction.mock.calls.length - 1][0].items
).toHaveLength(3);
</code>```

will validate length of items property on first(0-based numeration) argument for last time(mockedFunction.mock.calls.length - 1) it has been called.

Also you may consider using expect.anything() as a placeholder:

```<code>expect(mockedFunction).toHaveBeenLastCalledWith(
  expect.objectContaining({
    items: [expect.anything(), expect.anything(), expect.anything()]
  })
)
</code>```

But it may be better to use a mock and return the same values consistently - this will allow you to validate the contents of the array rather than just its length

Body:
.mock object on mocked function has .calls list on it. So

expect(
  mockedFunction.mock.calls[mockedFunction.mock.calls.length - 1][0].items
).toHaveLength(3);

will validate length of items property on first(0-based numeration) argument for last time(mockedFunction.mock.calls.length - 1) it has been called.

Also you may consider using expect.anything() as a placeholder:

expect(mockedFunction).toHaveBeenLastCalledWith(
  expect.objectContaining({
    items: [expect.anything(), expect.anything(), expect.anything()]
  })
)

But it may be better to use a mock and return the same values consistently - this will allow you to validate the contents of the array rather than just its length


问:
initializer_list and move semantics
Am I allowed to move elements out of a std::initializer_list<T>?

```<code>#include <initializer_list>
#include <utility>

template<typename T>
void foo(std::initializer_list<T> list)
{
    for (auto it = list.begin(); it != list.end(); ++it)
    {
        bar(std::move(*it));   // kosher?
    }
}
</code>```

Since std::intializer_list<T> requires special compiler attention and does not have value semantics like normal containers of the C++ standard library, I'd rather be safe than sorry and ask.

答:
Instead of using a std::initializer_list<T>, you can declare your argument as an array rvalue reference:

```<code>template <typename T>
void bar(T &&value);

template <typename T, size_t N>
void foo(T (&&list)[N] ) {
   std::for_each(std::make_move_iterator(std::begin(list)),
                 std::make_move_iterator(std::end(list)),
                 &bar);
}

void baz() {
   foo({std::make_unique<int>(0), std::make_unique<int>(1)});
}
</code>```

See example using std::unique_ptr<int>: https://gcc.godbolt.org/z/2uNxv6

Title: initializer_list and move semantics

Body:
Am I allowed to move elements out of a std::initializer_list<T>?

#include <initializer_list>
#include <utility>

template<typename T>
void foo(std::initializer_list<T> list)
{
    for (auto it = list.begin(); it != list.end(); ++it)
    {
        bar(std::move(*it));   // kosher?
    }
}

Since std::intializer_list<T> requires special compiler attention and does not have value semantics like normal containers of the C++ standard library, I'd rather be safe than sorry and ask.

Body:
Instead of using a std::initializer_list<T>, you can declare your argument as an array rvalue reference:

template <typename T>
void bar(T &&value);

template <typename T, size_t N>
void foo(T (&&list)[N] ) {
   std::for_each(std::make_move_iterator(std::begin(list)),
                 std::make_move_iterator(std::end(list)),
                 &bar);
}

void baz() {
   foo({std::make_unique<int>(0), std::make_unique<int>(1)});
}

See example using std::unique_ptr<int>: https://gcc.godbolt.org/z/2uNxv6


问:
Insert blob in oracle database with C#
I have to persist a .csv in my database, but for a more testable application I prefer don't use procedures.
Basically I just generate a file and the next instruction is put this in database.

Someone have some clue about best way to do this in code?

答:
```<code>    private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            //Read Image Bytes into a byte array
            byte[] blob = ReadFile(txtPath.Text);

            //Initialize Oracle Server Connection
            con = new OracleConnection(conString);

            //Set insert query
            string qry = "insert into Imgpn (imgpath,photo) values('" + txtPath.Text + "'," + " :BlobParameter )";
            OracleParameter blobParameter = new OracleParameter();
            blobParameter.OracleType = OracleType.Blob;
            blobParameter.ParameterName = "BlobParameter";
            blobParameter.Value = blob;

            //Initialize OracleCommand object for insert.
            cmd = new OracleCommand(qry, con);

            //We are passing Name and Blob byte data as Oracle parameters.
            cmd.Parameters.Add(blobParameter);

            //Open connection and execute insert query.
            con.Open();
            cmd.ExecuteNonQuery();

            MessageBox.Show("Image added to blob field");
            GetImagesFromDatabase();
            cmd.Dispose();
            con.Close();
            //this.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    byte[] ReadFile(string sPath)
    {
        //Initialize byte array with a null value initially.
        byte[] data = null;

        //Use FileInfo object to get file size.
        FileInfo fInfo = new FileInfo(sPath);
        long numBytes = fInfo.Length;

        //Open FileStream to read file
        FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

        //Use BinaryReader to read file stream into byte array.
        BinaryReader br = new BinaryReader(fStream);

        //When you use BinaryReader, you need to supply number of bytes to read from file.
        //In this case we want to read entire file. So supplying total number of bytes.
        data = br.ReadBytes((int)numBytes);
        return data;
    }
    void GetImagesFromDatabase()
    {
        try
        {
            //Initialize Oracle  connection.
            con = new OracleConnection(conString);
            //MessageBox.Show("Connection Successfull");
            //Initialize Oracle adapter.
            OracleDataAdapter oda = new OracleDataAdapter("Select * from Imgpn", con);

            //Initialize Dataset.
            DataSet DS = new DataSet();

            //Fill dataset with ImagesStore table.
            oda.Fill(DS, "Imgpn");

            //Fill Grid with dataset.

            dataGridView1.DataSource = DS.Tables["Imgpn"];
            //
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
</code>```

here is the simple way to insert image into oracle database ane retrieve ane show in datagridview

ContentLicense: CC BY-SA 2.5

Title: Insert blob in oracle database with C#

Body:
    private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            //Read Image Bytes into a byte array
            byte[] blob = ReadFile(txtPath.Text);

            //Initialize Oracle Server Connection
            con = new OracleConnection(conString);

            //Set insert query
            string qry = "insert into Imgpn (imgpath,photo) values('" + txtPath.Text + "'," + " :BlobParameter )";
            OracleParameter blobParameter = new OracleParameter();
            blobParameter.OracleType = OracleType.Blob;
            blobParameter.ParameterName = "BlobParameter";
            blobParameter.Value = blob;

            //Initialize OracleCommand object for insert.
            cmd = new OracleCommand(qry, con);

            //We are passing Name and Blob byte data as Oracle parameters.
            cmd.Parameters.Add(blobParameter);

            //Open connection and execute insert query.
            con.Open();
            cmd.ExecuteNonQuery();

            MessageBox.Show("Image added to blob field");
            GetImagesFromDatabase();
            cmd.Dispose();
            con.Close();
            //this.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    byte[] ReadFile(string sPath)
    {
        //Initialize byte array with a null value initially.
        byte[] data = null;

        //Use FileInfo object to get file size.
        FileInfo fInfo = new FileInfo(sPath);
        long numBytes = fInfo.Length;

        //Open FileStream to read file
        FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

        //Use BinaryReader to read file stream into byte array.
        BinaryReader br = new BinaryReader(fStream);

        //When you use BinaryReader, you need to supply number of bytes to read from file.
        //In this case we want to read entire file. So supplying total number of bytes.
        data = br.ReadBytes((int)numBytes);
        return data;
    }
    void GetImagesFromDatabase()
    {
        try
        {
            //Initialize Oracle  connection.
            con = new OracleConnection(conString);
            //MessageBox.Show("Connection Successfull");
            //Initialize Oracle adapter.
            OracleDataAdapter oda = new OracleDataAdapter("Select * from Imgpn", con);

            //Initialize Dataset.
            DataSet DS = new DataSet();

            //Fill dataset with ImagesStore table.
            oda.Fill(DS, "Imgpn");

            //Fill Grid with dataset.

            dataGridView1.DataSource = DS.Tables["Imgpn"];
            //
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

here is the simple way to insert image into oracle database ane retrieve ane show in datagridview