答:
Check out the docs for twemoji....
https://github.com/twitter/twemoji#api

API

Following are all the methods exposed in the twemoji namespace.

twemoji.parse( ... ) V1

This is the main parsing utility and has 3 overloads per parsing type.

There are mainly two kinds of parsing: string parsing and DOM parsing.

You can parse strings (parse their input).

I believe you're looking for smoething like this:

However, for already sanitized strings, this method can be considered safe enough. Please see DOM parsing if security is one of your major concerns.

twemoji.parse('I \u2764\uFE0F emoji!');

// will produce
/*
I  emoji!
*/
```

Title: How to replace emojis in html with twemoji?

Body:
Check out the docs for twemoji....
https://github.com/twitter/twemoji#api

API

Following are all the methods exposed in the twemoji namespace.

twemoji.parse( ... ) V1

This is the main parsing utility and has 3 overloads per parsing type.

There are mainly two kinds of parsing: string parsing and DOM parsing.

You can parse strings (parse their input).

I believe you're looking for smoething like this:

However, for already sanitized strings, this method can be considered safe enough. Please see DOM parsing if security is one of your major concerns.

twemoji.parse('I \u2764\uFE0F emoji!');

// will produce
/*
I <img
  class="emoji"
  draggable="false"
  alt="❤"
  src="https://twemoji.maxcdn.com/36x36/2764.png"/> emoji!
*/


来源: stackexchange

问:
Requesting API with fetch in javascript has CORS policy error
I'm trying to call some APIs with fetch in my javascript code. I'm developing with ReactJs in my machine and have another development in the same network developing the API with .net in another machine. With postman, I can call the API, but with fetch no. I try to call another API in other server and the result was successful.

I'm using fetch and tried to use axios too. I have found in other question in stack overflow this API: https://gturnquist-quoters.cfapps.io/api/random.
The answer says to try to fetch they and I try but throw same error again.

My code to fetch the gturnquist API:

```<code>const myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
fetch('http://gturnquist-quoters.cfapps.io/api/random', {
  method: 'GET', headers: myHeader,
})
 .then((res) => {
   console.log(res);
   return {};
 })
 .then(res => console.log(res));
</code>```

and my code to fetch the API that i need:

```<code>const myHeader = new Headers();

const token = 'mytoken';
myHeader.append('id-tenant', token);
myHeader.append('Content-Type', 'application/json');

const id = 'myid';
const url = 'myurl';

fetch(`http://10.1.1.35/${url}/${id}`, {
  method: 'GET',
  headers: myHeader,
}).then(res => res.json()).then(res => console.log(res));
</code>```

I have this errors when I try to call an API

OPTIONS http://10.1.1.35/url/id 503 (Service Unavailable)

Access to fetch at 'http://10.1.1.35/url/id' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

It's a server side error or javascript error?

In my server, the API is configured like the answer of Rajkumar Peter

EDIT: My network error

Questions i have see to try handle my error:

Fetch CORS error with instagram api

Enable CORS in fetch api

managing CORS with fetch API GET request

React fetch has error fetch was blocked by CORS policy

Response to preflight request doesn't pass access control check

答:
When performing an API call from a web browser, it will often do something called a "preflight check". This is essentially where the browser sends a request to your API (ahead of your own API call), to check what it is allowed to do and whether it's even worth sending the actual request.

To do this, it uses the OPTIONS method (instead of GET, POST .etc).

If your API endpoint hasn't been configured to accept OPTIONS requests, then the preflight request from the browser will fail - and it will abort sending your request.

To fix your issue, you need to configure your API to accept OPTIONS methods. You should also check which origins (IP addresses of clients connecting to the API) are allowed.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to call some APIs with fetch in my javascript code. I'm developing with ReactJs in my machine and have another development in the same network developing the API with .net in another machine. With postman, I can call the API, but with fetch no. I try to call another API in other server and the result was successful.

I'm using fetch and tried to use axios too. I have found in other question in stack overflow this API: https://gturnquist-quoters.cfapps.io/api/random.
The answer says to try to fetch they and I try but throw same error again.

My code to fetch the gturnquist API:

const myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
fetch('http://gturnquist-quoters.cfapps.io/api/random', {
  method: 'GET', headers: myHeader,
})
 .then((res) => {
   console.log(res);
   return {};
 })
 .then(res => console.log(res));

and my code to fetch the API that i need:

const myHeader = new Headers();

const token = 'mytoken';
myHeader.append('id-tenant', token);
myHeader.append('Content-Type', 'application/json');

const id = 'myid';
const url = 'myurl';

fetch(`http://10.1.1.35/${url}/${id}`, {
  method: 'GET',
  headers: myHeader,
}).then(res => res.json()).then(res => console.log(res));

I have this errors when I try to call an API

OPTIONS http://10.1.1.35/url/id 503 (Service Unavailable)

Access to fetch at 'http://10.1.1.35/url/id' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

It's a server side error or javascript error?

In my server, the API is configured like the answer of Rajkumar Peter

EDIT: My network error

Questions i have see to try handle my error:

Fetch CORS error with instagram api

Enable CORS in fetch api

managing CORS with fetch API GET request

React fetch has error fetch was blocked by CORS policy

Response to preflight request doesn't pass access control check


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

答:
Single line solution using list comprehension

[(z[0], [j[1] for i in z[1] for j in users if j[0] == i]) for z in prod]

```<code>    # How to solve this kinda problem step by step:
    # First assume you have only one element in prod --> (1004, [2, 4, 1]).
    # Now write a list comprehension to replace the [2, 4, 1] with ['MX', 'EN', 'FR'], this can be done using 2 for loops as below:
    aa = [2, 4, 1]
    print ([j[1] for i in aa for j in users if j[0] == i])

    # Now perform above logic for the entire prod data using for loop and store desired result:
    print ([(z[0], [j[1] for i in z[1] for j in users if j[0] == i]) for z in prod])
</code>```

I hope this counts. :)

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
Single line solution using list comprehension

[(z[0], [j[1] for i in z[1] for j in users if j[0] == i]) for z in prod]

    # How to solve this kinda problem step by step:
    # First assume you have only one element in prod --> (1004, [2, 4, 1]).
    # Now write a list comprehension to replace the [2, 4, 1] with ['MX', 'EN', 'FR'], this can be done using 2 for loops as below:
    aa = [2, 4, 1]
    print ([j[1] for i in aa for j in users if j[0] == i])

    # Now perform above logic for the entire prod data using for loop and store desired result:
    print ([(z[0], [j[1] for i in z[1] for j in users if j[0] == i]) for z in prod])

I hope this counts. :)


问:
GYP ERR! build error. stack Error: 'make' failed with exit code 2
I am currently working on a nodejs web application I am having trouble pushing the application online with cloud foundry. I did some research on the errors and it seems that maybe some of the packages being installed have some conflicts.

This is the package.json file.

```<code>{
  "dependencies": {
    "c3": "^0.4.12",
    "cfenv": "1.0.0",
    "cloudant": "^1.8.0",
    "dygraphs": "^2.0.0",
    "express": "4.5.1",
    "getmac": "1.0.6",
    "http": "0.0.0",
    "mqtt": "1.0.5",
    "properties": "1.2.1",
    "save": "^2.3.0",
    "sockjs": "0.3.9",
    "websocket-multiplex": "0.1.x"
  },
  "description": "description.",
  "license": "UNLICENSED",
  "main": "app.js",
  "repository": {
    "type": "git",
    "url": "<gitUrl>"
  }
}
</code>```

This is the error I encounter when I try to push the application via cloud foundry. This similar error happens when I npm install after deleting all the content of the node_modules folder.

```<code>../src/bufferutil.cc:32:50: error: call of overloaded 'NODE_SET_METHOD(v8::Local<v8::FunctionTemplate>&, const char [6], void (&)(const v8::FunctionCallbackInfo<v8::Value>&))' is ambiguous
     NODE_SET_METHOD(t, "merge", BufferUtil::Merge);

../src/bufferutil.cc:32:50: note: candidates are:
In file included from ../src/bufferutil.cc:8:0:
/root/.node-gyp/8.0.0/include/node/node.h:257:13: note: void node::NODE_SET_METHOD(v8::Local<v8::Template>, const char*, v8::FunctionCallback)
 inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
             ^
/root/.node-gyp/8.0.0/include/node/node.h:270:13: note: void node::NODE_SET_METHOD(v8::Local<v8::Object>, const char*, v8::FunctionCallback)
 inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
             ^
bufferutil.target.mk:95: recipe for target 'Release/obj.target/bufferutil/src/bufferutil.o' failed
make: *** [Release/obj.target/bufferutil/src/bufferutil.o] Error 1
make: Leaving directory '/home/WibiSmart-Bluemix-App/node_modules/bufferutil/build'

gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12)
gyp ERR! System Linux 4.4.30-ti-r64
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/WibiSmart-Bluemix-App/node_modules/bufferutil
gyp ERR! node -v v8.0.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok
</code>```

Did anyone else encounter this issue, or knows how to fix it?

答:
I got the same problem when installed the gazebo gzweb. I found out that apt install nodejs install the "node" in the direction of "/usr/bin/". You can verify by which node. But node -v is still referring to "/usr/local/bin/node" which is a wrong version I failed to uninstall.
Thus as my solution:

```<code>rm -rf /usr/local/bin/node
cp -i /usr/bin/node /usr/local/bin/
cp -i /usr/bin/nodejs /usr/local/bin/
</code>```

Steps:

sudo apt-get install npm
npm install -g n
n stable
npm install npm@6.9.0 -g
ln -s /usr/local/bin/npm /usr/bin/npm

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on a nodejs web application I am having trouble pushing the application online with cloud foundry. I did some research on the errors and it seems that maybe some of the packages being installed have some conflicts.

This is the package.json file.

{
  "dependencies": {
    "c3": "^0.4.12",
    "cfenv": "1.0.0",
    "cloudant": "^1.8.0",
    "dygraphs": "^2.0.0",
    "express": "4.5.1",
    "getmac": "1.0.6",
    "http": "0.0.0",
    "mqtt": "1.0.5",
    "properties": "1.2.1",
    "save": "^2.3.0",
    "sockjs": "0.3.9",
    "websocket-multiplex": "0.1.x"
  },
  "description": "description.",
  "license": "UNLICENSED",
  "main": "app.js",
  "repository": {
    "type": "git",
    "url": "<gitUrl>"
  }
}

This is the error I encounter when I try to push the application via cloud foundry. This similar error happens when I npm install after deleting all the content of the node_modules folder.

../src/bufferutil.cc:32:50: error: call of overloaded 'NODE_SET_METHOD(v8::Local<v8::FunctionTemplate>&, const char [6], void (&)(const v8::FunctionCallbackInfo<v8::Value>&))' is ambiguous
     NODE_SET_METHOD(t, "merge", BufferUtil::Merge);

../src/bufferutil.cc:32:50: note: candidates are:
In file included from ../src/bufferutil.cc:8:0:
/root/.node-gyp/8.0.0/include/node/node.h:257:13: note: void node::NODE_SET_METHOD(v8::Local<v8::Template>, const char*, v8::FunctionCallback)
 inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
             ^
/root/.node-gyp/8.0.0/include/node/node.h:270:13: note: void node::NODE_SET_METHOD(v8::Local<v8::Object>, const char*, v8::FunctionCallback)
 inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
             ^
bufferutil.target.mk:95: recipe for target 'Release/obj.target/bufferutil/src/bufferutil.o' failed
make: *** [Release/obj.target/bufferutil/src/bufferutil.o] Error 1
make: Leaving directory '/home/WibiSmart-Bluemix-App/node_modules/bufferutil/build'

gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12)
gyp ERR! System Linux 4.4.30-ti-r64
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/WibiSmart-Bluemix-App/node_modules/bufferutil
gyp ERR! node -v v8.0.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok

Did anyone else encounter this issue, or knows how to fix it?

Body:
I got the same problem when installed the gazebo gzweb. I found out that apt install nodejs install the "node" in the direction of "/usr/bin/". You can verify by which node. But node -v is still referring to "/usr/local/bin/node" which is a wrong version I failed to uninstall.
Thus as my solution:

rm -rf /usr/local/bin/node
cp -i /usr/bin/node /usr/local/bin/
cp -i /usr/bin/nodejs /usr/local/bin/

Steps:

sudo apt-get install npm
npm install -g n
n stable
npm install npm@6.9.0 -g
ln -s /usr/local/bin/npm /usr/bin/npm


问:
Is "docker logs container-id | tail -10" a valid command?
I'm running the command docker logs <container-id> | tail -10 and still, docker shows the entire log history. I know docker logs --tail 10 <container-id> is a valid command and serves the purpose. But, why doesn't the former command works as it does in case of a file?

答:
If you want your everything your program writes to either stdout or stderr to go through the pipeline to tail, redirect stderr to stdout:

```<code>docker logs "$container_id" 2>&1 | tail -10
</code>```

Body:
If you want your everything your program writes to either stdout or stderr to go through the pipeline to tail, redirect stderr to stdout:

docker logs "$container_id" 2>&1 | tail -10


问:
UPDATE RECORDS USING PHP LOOP
I want to update data in my database using php loop.

I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.

```<code>// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
    $student_count_count = $row2['0'];

for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}

if (mysqli_query($mysqli, $sql)) {
    echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
    echo "Error updating record: " . mysqli_error($mysqli);
}
</code>```

I would want it to update all the records in the column score_s

答:
You're generating the SQL string in a loop:

```<code>for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = ...;
}
</code>```

But you're only executing it once, because this is outside the loop:

```<code>if (mysqli_query($mysqli, $sql)) {
</code>```

Move the query command inside the loop:

```<code>for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = ...
    if (mysqli_query($mysqli, $sql)) {
        ...
    } else {
        ...
    }
}
</code>```

You're also missing braces on your while loop:

```<code>while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
</code>```

Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:

```<code>while($row2 = mysqli_fetch_row($rcount_student_lists))
{
    $student_count_count = $row2['0'];
    for ($id = 1; $id <=$student_count_count; $id++)
    {
        ...
    }
}
</code>```

Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.

Title: UPDATE RECORDS USING PHP LOOP

Body:
I want to update data in my database using php loop.

I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.

// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
    $student_count_count = $row2['0'];

for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}

if (mysqli_query($mysqli, $sql)) {
    echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
    echo "Error updating record: " . mysqli_error($mysqli);
}

I would want it to update all the records in the column score_s

Body:
You're generating the SQL string in a loop:

for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = ...;
}

But you're only executing it once, because this is outside the loop:

if (mysqli_query($mysqli, $sql)) {

Move the query command inside the loop:

for ($id = 1; $id <=$student_count_count; $id++)
{
    $sql = ...
    if (mysqli_query($mysqli, $sql)) {
        ...
    } else {
        ...
    }
}

You're also missing braces on your while loop:

while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];

Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:

while($row2 = mysqli_fetch_row($rcount_student_lists))
{
    $student_count_count = $row2['0'];
    for ($id = 1; $id <=$student_count_count; $id++)
    {
        ...
    }
}

Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.


问:
WiX: Bundling dependencies inside MSI using Burn
I use the burn tool from WiX v3.6.1601.0 to create a bootstrapper that will download my project dependencies (.NET 3.5). The end result however is two executables (a program MSI and a exe that will download dependencies). Since many of my customers seams not to understand which executable to use, I would like to make it even simpler by only shipping one file (i.e. the MSI).

Is this possible with Burn ?, and if it is can anyone point me to documentation on how to create a single MSI that will bootstrap its own dependencies.

答: MSI packages can't bootstrap other installers except through the use of "embedded chainers." (See the MSI SDK topic on MsiEmbeddedChainer.) Burn creates an .exe that contains MSIs and other prerequisites.</p>


问:
unit test for Angular service when service doesn't return an Observable?
I have looked at the doc to learn how to test an http request, but I could not figure out how to unit test a service like below from the docs.

```<code>class service {

data$: BehaviorSubject<any> = new BehaviorSubject<>(any);

getDatas(): Observable<any> {
    this.http.get(url).subscribe((response) => {
       this.data$.emit(response);
    });
    // if return a observable will be like:
    // return this.http.get(url).

  }

}
</code>```

How can i test the service above if it's method doesn't return an Observable?

答:
The comment from The Head Rush is right.  Here is a code example I had handy for this.

service

```<code>export class SomeService {
  constructor() {}

  goDoSomething(): void {
      console.log('I did something');
  }

}
</code>```

test

```<code>    describe('testing goDoSomething method', () => {
        it('should call console log', () => {
            spyOn(console, 'log'); // console is the object, and log is the method I expect to be called
            service.goDoSomething();
            expect(console.log).toHaveBeenCalled();
        });
    });
</code>```

Body:
I have looked at the doc to learn how to test an http request, but I could not figure out how to unit test a service like below from the docs.

class service {

data$: BehaviorSubject<any> = new BehaviorSubject<>(any);

getDatas(): Observable<any> {
    this.http.get(url).subscribe((response) => {
       this.data$.emit(response);
    });
    // if return a observable will be like:
    // return this.http.get(url).

  }

}

How can i test the service above if it's method doesn't return an Observable?

Body:
The comment from The Head Rush is right.  Here is a code example I had handy for this.

service

export class SomeService {
  constructor() {}

  goDoSomething(): void {
      console.log('I did something');
  }

}

test

    describe('testing goDoSomething method', () => {
        it('should call console log', () => {
            spyOn(console, 'log'); // console is the object, and log is the method I expect to be called
            service.goDoSomething();
            expect(console.log).toHaveBeenCalled();
        });
    });


问:
cmd PATH error - \common was unexpected at this time
i am adding a line in a .bat file look like this:

```<code>path %~dp0;%PATH%
</code>```

But this message is shown:

\common was unexpected at this time.

Let me show you the path.

```<code>PATH=C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program File
s (x86)\Common Files\Microsoft Shared\Windows Live;c:\Program Files (x86)\AMD AP
P\bin\x86_64;c:\Program Files (x86)\AMD APP\bin\x86;C:\Windows\system32;C:\Windo
ws;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\Progr
am Files (x86)\ATI Technologies\ATI.ACE\Core-Static\;C:\Program Files (x86)\Sony
\VAIO Startup Setting Tool;;C:\Program Files (x86)\Windows Live\Shared;C:\Progra
m Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\P
rogram Files (x86)\Common Files\Thunder Network\KanKan\Codecs;C:\Program Files\C
alibre2\
</code>```

This is the path. The path i want to add (%~dp0) is:

```<code>C:\Users\Workspace\Desktop\Files\Programming\GoogleSearch\
</code>```

This is important for me.

Thank you.

答:
Related to this post (tested)

Remove %PATH%variable in your set PATH=.. string.

Like set PATH=C:\Path\to\file instead of set PATH=%PATH%;C:\Path\to\file

Body:
i am adding a line in a .bat file look like this:

path %~dp0;%PATH%

But this message is shown:

\common was unexpected at this time.

Let me show you the path.

PATH=C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program File
s (x86)\Common Files\Microsoft Shared\Windows Live;c:\Program Files (x86)\AMD AP
P\bin\x86_64;c:\Program Files (x86)\AMD APP\bin\x86;C:\Windows\system32;C:\Windo
ws;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\Progr
am Files (x86)\ATI Technologies\ATI.ACE\Core-Static\;C:\Program Files (x86)\Sony
\VAIO Startup Setting Tool;;C:\Program Files (x86)\Windows Live\Shared;C:\Progra
m Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\P
rogram Files (x86)\Common Files\Thunder Network\KanKan\Codecs;C:\Program Files\C
alibre2\

This is the path. The path i want to add (%~dp0) is:

C:\Users\Workspace\Desktop\Files\Programming\GoogleSearch\

This is important for me.

Thank you.


问:
Oracle Update with Subselect with Multiple Joins
I'm trying to write a script that includes an Oracle query to update the scheduled finish date of a project to the revised end date that was submitted through a change request, but the date is not being updated upon running the script.

I'm unsure whether this is a problem with my query or something else. Before I delve any deeper, does this query look like it should work? (I'm currently unable to test the query against the database itself.)

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM Change ch
               WHERE ch.ID = ?)
</code>```

Note: The ? in the query is a bind variable that will take on the value of the record currently being worked on. ie. If the Change Request being operated on has an ID of 1214, the ? will be 1214 once the script runs.

Thanks in advance.

Update:

I believe this is the correct logic:

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?)
</code>```

Gordon, you were correct. I was trying to match a Change ID with a Project ID, but they don't correlate. So this new subselect in the WHERE clause of the update should fix the linkage issue.

答:
There is probably no change.id that matches your project id.  It is very suspicious that all the JOIN columns are called ID.  I would expect something more like this:

Wouldn't this express the logic you want?

```<code>UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch JOIN
                               ChangeRequests cr
                               ON cr.ID = ch.ChangeID JOIN
                               RisksAndIssues ri
                               ON ri.ID = cr.RiskID
                          WHERE ri.ProjectID = pr.ID
                         )
WHERE pr.ID = (SELECT ch.projectID
               FROM Change ch
               WHERE ch.ID = ?
              )
</code>```

However, I don't know the actual names of the columns in your table, so this is just a guess.

Note that this removes the Project reference in the subquery.

Body:
I'm trying to write a script that includes an Oracle query to update the scheduled finish date of a project to the revised end date that was submitted through a change request, but the date is not being updated upon running the script.

I'm unsure whether this is a problem with my query or something else. Before I delve any deeper, does this query look like it should work? (I'm currently unable to test the query against the database itself.)

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM Change ch
               WHERE ch.ID = ?)

Note: The ? in the query is a bind variable that will take on the value of the record currently being worked on. ie. If the Change Request being operated on has an ID of 1214, the ? will be 1214 once the script runs.

Thanks in advance.

Update:

I believe this is the correct logic:

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch
                          JOIN ChangeRequests cr ON cr.ID = ch.ID
                          JOIN RisksAndIssues ri ON ri.ID = cr.ID
                          JOIN Project pr ON pr.ID = ri.PK_ID
                          WHERE pr.ID = ?)
WHERE pr.ID = (SELECT ID
               FROM RisksAndIssues ri
               JOIN ChangeRequests cr ON cr.ID = ri.ID
               JOIN Change ch ON ch.ID = cr.ID
               JOIN Project pr ON pr.ID = ri.PK_ID
               WHERE pr.ID = ?)

Gordon, you were correct. I was trying to match a Change ID with a Project ID, but they don't correlate. So this new subselect in the WHERE clause of the update should fix the linkage issue.

Body:
There is probably no change.id that matches your project id.  It is very suspicious that all the JOIN columns are called ID.  I would expect something more like this:

Wouldn't this express the logic you want?

UPDATE Project pr
SET pr.ScheduledFinish = (SELECT ch.RevisedEndDate
                          FROM Change ch JOIN
                               ChangeRequests cr
                               ON cr.ID = ch.ChangeID JOIN
                               RisksAndIssues ri
                               ON ri.ID = cr.RiskID
                          WHERE ri.ProjectID = pr.ID
                         )
WHERE pr.ID = (SELECT ch.projectID
               FROM Change ch
               WHERE ch.ID = ?
              )

However, I don't know the actual names of the columns in your table, so this is just a guess.

Note that this removes the Project reference in the subquery.


问:
Button Text does not Update
>> BACKGROUND :

I want to update/change the text of a Button in the SecondScreen with a press of a Button in the MainScreen. Well I did some research and did what I want, and when I checked in the terminal the text did change. BUUT, the text shown on the SecondScreen did not.

>> THIS IS WHAT I DID :

((Mind you that I'm only using snippets of code for example, I'm going to post the whole code below.))

```<code>Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.funcself()
        ## on press it goes to it's root and do the "funcself" function in it
</code>```

which is :

```<code>class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()
        ## it re-directs to the SecondScreen and do the "funcscreen" function
</code>```

which is :

```<code>class SecondScreen(Screen):
    def funcscreen(self):
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"
</code>```

and then I checked if I did it successfully by doing print(self.ids["button"].text), and yes!
It did change, but when I navigated to the next screen, the text shown still didn't change.

Anyone mind helping and explaining?

FULL CODE :

python file :

```<code>import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")
class reproduce(App):
    second = SecondScreen()
    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

if __name__ == "__main__":
    app = reproduce()
    app.run()
</code>```

kivy file :

```<code><MainScreen>:
    GridLayout:
        rows:2
        Label:
            text: "PRESS TO GO TO THE NEXT PAGE"
        GridLayout:
            cols:2
            Button:
                text:"PRESS TO CHANGE TEXT"
                on_press:
                    root.funcself()

            Button:
                text:">>>"
                on_press:
                    app.change_screen("second")
                    root.manager.transition.direction = "left"

<SecondScreen>:
    GridLayout:
        rows:2
        Label:
            id:label
            text: "PRESS TO CHECK AND RETURN TO PREV PAGE"
        Button:
            id:button
            text:"TEXT BEFORE CHANGE"
            on_press:
                app.change_screen("first")
                root.manager.transition.direction = "right"
                app.check()
GridLayout:
    cols: 1
    ScreenManager:
        id:sm
        MainScreen:
            id:main
            name:"first"
        SecondScreen:
            id:second
            name:"second"
</code>```

答:
The second attribute you define in your app class, is a new instantiation of the screen, and not really the instance you got in your screenmanager, which you add in kv. This is why when you check, you see its changed, but not on the right instance. And again when you call app.second.func, from mainscreen, again its the wrong instance.

But your app always has a root. In your case its the gridlayout. And every screen has a manager. There are a couple of ways to acces it. But you can do like this.

In your mainscreen class in kv:

```<code>Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.manager.get_screen("second").ids["button"].text = "Something"
</code>```

Here it gets the screenmanager, and uses its get_screen() method to get the screen named second, and then the id's of that kv rule.

Title: Button Text does not Update

Body:
>> BACKGROUND :

I want to update/change the text of a Button in the SecondScreen with a press of a Button in the MainScreen. Well I did some research and did what I want, and when I checked in the terminal the text did change. BUUT, the text shown on the SecondScreen did not.

>> THIS IS WHAT I DID :

((Mind you that I'm only using snippets of code for example, I'm going to post the whole code below.))

Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.funcself()
        ## on press it goes to it's root and do the "funcself" function in it

which is :

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()
        ## it re-directs to the SecondScreen and do the "funcscreen" function

which is :

class SecondScreen(Screen):
    def funcscreen(self):
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

and then I checked if I did it successfully by doing print(self.ids["button"].text), and yes!
It did change, but when I navigated to the next screen, the text shown still didn't change.

Anyone mind helping and explaining?

FULL CODE :

python file :

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")
class reproduce(App):
    second = SecondScreen()
    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

if __name__ == "__main__":
    app = reproduce()
    app.run()

kivy file :

<MainScreen>:
    GridLayout:
        rows:2
        Label:
            text: "PRESS TO GO TO THE NEXT PAGE"
        GridLayout:
            cols:2
            Button:
                text:"PRESS TO CHANGE TEXT"
                on_press:
                    root.funcself()

            Button:
                text:">>>"
                on_press:
                    app.change_screen("second")
                    root.manager.transition.direction = "left"

<SecondScreen>:
    GridLayout:
        rows:2
        Label:
            id:label
            text: "PRESS TO CHECK AND RETURN TO PREV PAGE"
        Button:
            id:button
            text:"TEXT BEFORE CHANGE"
            on_press:
                app.change_screen("first")
                root.manager.transition.direction = "right"
                app.check()
GridLayout:
    cols: 1
    ScreenManager:
        id:sm
        MainScreen:
            id:main
            name:"first"
        SecondScreen:
            id:second
            name:"second"

Body:
The second attribute you define in your app class, is a new instantiation of the screen, and not really the instance you got in your screenmanager, which you add in kv. This is why when you check, you see its changed, but not on the right instance. And again when you call app.second.func, from mainscreen, again its the wrong instance.

But your app always has a root. In your case its the gridlayout. And every screen has a manager. There are a couple of ways to acces it. But you can do like this.

In your mainscreen class in kv:

Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.manager.get_screen("second").ids["button"].text = "Something"

Here it gets the screenmanager, and uses its get_screen() method to get the screen named second, and then the id's of that kv rule.


问:
TypeScript + React: enforce correct ref props
I just got bitten by a runtime exception because I passed a React ref into the wrong component.

I wonder if/how TypeScript could have saved my bacon here?

Reduced test case:

```<code>import * as React from 'react';

class Modal extends React.Component<{}> {
    close = () => {};
}

declare const modal: Modal;

modal.close();

const modalRef = React.createRef<Modal>();

// Let's try giving this ref to the correct component…
// No error as expected :-)
<Modal ref={modalRef} />;

class SomeOtherComponent extends React.Component<{}> {}

// Let's try giving this ref to the wrong component…
// Expected type error but got none! :-(
<SomeOtherComponent ref={modalRef} />;

// Now when we try to use this ref, TypeScript tells us it's safe to do so.
// But it's not, because the ref has been incorrectly assigned to another component!
if (modalRef.current !== null) {
    modalRef.current.close() // runtime error!
}
</code>```

答:
Possible solutions is to use interface for class and ref.

interface IModal {
  close(): void;
}

class Modal extends React.Component<{}> implements IModal {
    close = () => {};
}

const modalRef = React.createRef<IModal>();

<Modal ref={modalRef as React.RefObject<Modal>}/>
<SomeOtherComponent ref={modalRef} />
// Type 'RefObject<IModal>' is not assignable to type 'string | ((instance: //SomeOtherComponent | null) => void) | RefObject<SomeOtherComponent> | null | undefined'.
//  Type 'RefObject<IModal>' is not assignable to type 'RefObject<SomeOtherComponent>'.
//    Type 'IModal' is missing the following properties from type 'SomeOtherComponent': render, context, setState, forceUpdate, and 3 more.  TS2322
```

Body:
I just got bitten by a runtime exception because I passed a React ref into the wrong component.

I wonder if/how TypeScript could have saved my bacon here?

Reduced test case:

import * as React from 'react';

class Modal extends React.Component<{}> {
    close = () => {};
}

declare const modal: Modal;

modal.close();

const modalRef = React.createRef<Modal>();

// Let's try giving this ref to the correct component…
// No error as expected :-)
<Modal ref={modalRef} />;

class SomeOtherComponent extends React.Component<{}> {}

// Let's try giving this ref to the wrong component…
// Expected type error but got none! :-(
<SomeOtherComponent ref={modalRef} />;

// Now when we try to use this ref, TypeScript tells us it's safe to do so.
// But it's not, because the ref has been incorrectly assigned to another component!
if (modalRef.current !== null) {
    modalRef.current.close() // runtime error!
}


问:
WCF Service Max number of Methods
What is the maximum number of methods/operations that can be exposed via a single WCF Service Contract?</p>

答:
There is no maximum.  You can have as many as you wish, AFAIK.

However, whether or not it is practical is a different issue.  It will become quite unwieldy if you have too many methods on a single contract.

OwnerDisplayName: san

Title: WCF Service Max number of Methods

OwnerDisplayName: casperOne

ContentLicense: CC BY-SA 2.5


问:
reload datepicker dynamically
ok i have a javascript object to control elements on my page such as load html, undo, redo etc.

When i do undo, it removes the datepickers from the inputs that should be datepickers.

My code is located here: http://jsfiddle.net/maniator/qAWuA/

i changed my code to inline JSON just for the fiddle

It has 6 columns, two of them being datepickers with start date and its expiration.

When a user clicks of undo or undo all -- the datepickers no longer work.

Can someone please help me out here?

Thanks :-D

UPDATED

still have the issue, but i changed the fiddle a bit

答:
I solved the issue:

i added this line to both of the undo clicks:

```<code>self.refreshDatePickers();
</code>```

on create row i added this to expiration:

```<code>case 'expiration':
     td.append($('<input>',
          {value: i, name: index+"["+topIndex+"]",
               type: 'text', size: 30, id: 'to['+topIndex+']',
               'class': 'dp', 'index': topIndex}));
     break;
</code>```

and then i added the refreshDatePickers function:

```<code>refreshDatePickers: function(){
    var self = this;
    $.each($('.dp'),function(){
        var index = $(this).attr('index');
        var tr = $(this).parent().parent();
        $( "input[name='startDate["+index+"]'], input[name='expiration["+index+"]']", tr ).removeClass("hasDatepicker");
        self.createDatePicker(index, tr);
    })
}
</code>```

Title: reload datepicker dynamically

Body:
I solved the issue:

i added this line to both of the undo clicks:

self.refreshDatePickers();

on create row i added this to expiration:

case 'expiration':
     td.append($('<input>',
          {value: i, name: index+"["+topIndex+"]",
               type: 'text', size: 30, id: 'to['+topIndex+']',
               'class': 'dp', 'index': topIndex}));
     break;

and then i added the refreshDatePickers function:

refreshDatePickers: function(){
    var self = this;
    $.each($('.dp'),function(){
        var index = $(this).attr('index');
        var tr = $(this).parent().parent();
        $( "input[name='startDate["+index+"]'], input[name='expiration["+index+"]']", tr ).removeClass("hasDatepicker");
        self.createDatePicker(index, tr);
    })
}


问:
Adding Labels to Images with Openshift s2i Binary build
I would like to add some labels (commit hash, branch name,...) to images I create using Openshift source-to-image binary build. These labels will have naturally different values for every build.

Currently oc start-build does not even support -e flags to add environment variables. (At least is seems to, it works for Git source, its a bug?)

And for binary build does not supports --build-arg to pass argument for docker file.

The only way I was able to accomplish this to call oc set env bc [build-name] then start the build. And use Label in Dockerfile with values from environment variables.

My question is isn't there a better way to do this? (Ideally in a way that Dockerfile is not necessarily changed) Doesn't s2i supports passing --label to docker build behind?

Thank you.

答:
Do you want to add environment variable when you start oc start-build ? Because you mentioned oc set env bc [build-name].
Then you can use --env=<key>=<value> option, refer Starting Build for more details.

```<code>$ oc start-build <buildconfig_name> --env=<key>=<value>
</code>```

I hope it help you.

Body:
Do you want to add environment variable when you start oc start-build ? Because you mentioned oc set env bc [build-name].
Then you can use --env=<key>=<value> option, refer Starting Build for more details.

$ oc start-build <buildconfig_name> --env=<key>=<value>

I hope it help you.


问:
How to disable copy on a JTable
First of all I have to say that I never worked on java application.

I've been asked to prevent the possibility the user copy (ctrl+c or right click of the mouse) the content of JTable/JLabel (I didn't developed this java application).

I can't disable JTable or JLabel since the user must be allowed to edit them. I just need to disable the copy function on JLabel and/or JLabel.

What's the easiest way?
I read some posts on the internet but I didn't understand much since I never worked on Java application.

Thank you

答:
You can override this behavior by calling setTransferHandler on the JTable, which you seem to already understand.

When a cell is being edited, the CellEditor for the column’s class is active.  To prevent copying during a cell edit:

Create a new JTextField

Call that JTextField’s setTransferHandler method

Create a new DefaultCellEditor with that JTextField

Install that cell editor on your JTable:

```<code>TransferHandler copyDisabledHandler = new TransferHandler() {
    @Override
    public int getSourceActions(JComponent c) {
        return NONE;
    }
};

JTextField editorField = new JTextField();
editorField.setTransferHandler(copyDisabledHandler);

TableCellEditor uncopyableEditor = new DefaultCellEditor(editorField);

table.setDefaultEditor(Object.class, uncopyableEditor);
</code>```

Depending on the values returned by your TableModel’s getColumnClass method, you may need to pass a class other than Object.class to setDefaultEditor, such as String.class or Integer.class.

Title: How to disable copy on a JTable

Body:
You can override this behavior by calling setTransferHandler on the JTable, which you seem to already understand.

When a cell is being edited, the CellEditor for the column’s class is active.  To prevent copying during a cell edit:

Create a new JTextField

Call that JTextField’s setTransferHandler method

Create a new DefaultCellEditor with that JTextField

Install that cell editor on your JTable:

TransferHandler copyDisabledHandler = new TransferHandler() {
    @Override
    public int getSourceActions(JComponent c) {
        return NONE;
    }
};

JTextField editorField = new JTextField();
editorField.setTransferHandler(copyDisabledHandler);

TableCellEditor uncopyableEditor = new DefaultCellEditor(editorField);

table.setDefaultEditor(Object.class, uncopyableEditor);

Depending on the values returned by your TableModel’s getColumnClass method, you may need to pass a class other than Object.class to setDefaultEditor, such as String.class or Integer.class.


问:
How do I mirror (synchronize) panels in tmux?
I'd like that whatever I do on a panel to be copied on other panels simultaneously.

For example, I'd like to ssh to multiple similar servers and execute identical tasks in all of them simultaneously.

答:
If by panels you mean panes, doing

```<code><prefix> :setw synchronize-panes on
</code>```

will enable the feature you want.

If you want to turn it off after you are done doing what you want,

```<code><prefix> :setw synchronize-panes off
</code>```

Body:
If by panels you mean panes, doing

<prefix> :setw synchronize-panes on

will enable the feature you want.

If you want to turn it off after you are done doing what you want,

<prefix> :setw synchronize-panes off


问:
Why Does .net 4.0 Write All this Stuff to DebugView?
When I run my .net 4.0 winforms application, I see tons of output in debugview (the following is an excerpt).  I routinely use debugview for debug messages so all this extra stuff can get quite noisy.

```<code>[8092] *** HR propagated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\enumidentityattribute.cpp, line 144
[8092]
[8092]
[8092] *** HR originated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\copyout.cpp, line 1302
[8092]
[8092]
[8092] *** HR propagated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\enumidentityattribute.cpp, line 144
[8092]
[8092]
[8092] *** HR originated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\copyout.cpp, line 1302
</code>```

Does anyone know why this happens, and if/how I can prevent it?

答:
Workaround is to add some Exclude filters, but doesn't exclude blank lines:

*originated*;*iso_whid*;*propagated*; ;

Body:
When I run my .net 4.0 winforms application, I see tons of output in debugview (the following is an excerpt).  I routinely use debugview for debug messages so all this extra stuff can get quite noisy.

[8092] *** HR propagated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\enumidentityattribute.cpp, line 144
[8092]
[8092]
[8092] *** HR originated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\copyout.cpp, line 1302
[8092]
[8092]
[8092] *** HR propagated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\enumidentityattribute.cpp, line 144
[8092]
[8092]
[8092] *** HR originated: -2147024774
[8092] ***   Source File: d:\iso_whid\x86fre\base\isolation\com\copyout.cpp, line 1302

Does anyone know why this happens, and if/how I can prevent it?


问:
How to scroll to the bottom of a UITableView on the iPhone without seeing the scroll
I have a UITableView that is populated with cells of variable height. I would like the table to scroll to the bottom when the view is pushed into view.

I currently have the following function:

```<code>[self.table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
</code>```

I'm using autolayout, dynamic table cells and UITableViewAutomaticDimension as row height. I set estimatedRowHeight = 100

The above code works fine in viewDidLoad however this has the unfortunate side effect of displaying the top of the table when the view first appears and then jumping to the bottom. I would prefer it if the table view could be scrolled to the bottom before it appears.

Please note: I'm loading data from core data.

Any guidance would be much appreciated, even if it's just a case of telling me what I have is all that is possible.

答:
This seems pretty reliable...

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 100;

    [self.tableView performBatchUpdates:nil completion:^(BOOL b) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:numRows - 1 inSection:numSections - 1];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }];

}
</code>```

Replace numRows and numSections with your data count(s).

Body:
I have a UITableView that is populated with cells of variable height. I would like the table to scroll to the bottom when the view is pushed into view.

I currently have the following function:

[self.table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];

I'm using autolayout, dynamic table cells and UITableViewAutomaticDimension as row height. I set estimatedRowHeight = 100

The above code works fine in viewDidLoad however this has the unfortunate side effect of displaying the top of the table when the view first appears and then jumping to the bottom. I would prefer it if the table view could be scrolled to the bottom before it appears.

Please note: I'm loading data from core data.

Any guidance would be much appreciated, even if it's just a case of telling me what I have is all that is possible.

Body:
This seems pretty reliable...

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 100;

    [self.tableView performBatchUpdates:nil completion:^(BOOL b) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:numRows - 1 inSection:numSections - 1];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }];

}

Replace numRows and numSections with your data count(s).


问:
Working Around a Visual Studio Internal Compiler Error With Nested Templated Variables
I'm trying to write code that will let me index into the parameter types of a function:

```<code>template <typename R, typename... ARGS>
R function_return(R(*)(ARGS...));

template <typename R, typename... ARGS>
std::tuple<ARGS...> function_parameters(R(*)(ARGS...));

template <int I, typename T>
using get_type = typename std::conditional_t<(I < 0), std::tuple_element<static_cast<int>(std::tuple_size_v<T>) + I, T>, std::tuple_element<I, T>>::type;

template <int I, typename T>
using parameter_type = get_type<I, decltype(function_parameters(std::declval<T>()))>;
</code>```

Live Example (ICE under VS)
Live Example (working on GCC)

But when I try to use this on visual-studio-2017 I get an internal compiler error:

fatal error C1001: An internal error has occurred in the compiler.

Is there another way that I can do this which might work around the internal compiler error?

答:
It probably depends on the exact (sub)version of VS2017, as mine does not produce an ICE on the code. However, the code is still problematic, as it can potentially instantiate std::tuple_element<2147483647, T> or something similar. You need to make sure only the correct branch is ever evaluated. Replace your definition of get_type with this:

```<code>template <int I, typename T, bool negative = (I < 0)>
struct get_type_impl;

template <int I, typename T>
struct get_type_impl<I, T, true>
{
  using type = typename std::tuple_element<static_cast<int>(std::tuple_size<T>::value) + I, T>::type;
};

template <int I, typename T>
struct get_type_impl<I, T, false>
{
  using type = typename std::tuple_element<I, T>::type;
};

template <int I, typename T>
using get_type = typename get_type_impl<I, T>::type;
</code>```

This works for me on my VS 2017 (cl version 19.12)

Body:
I'm trying to write code that will let me index into the parameter types of a function:

template <typename R, typename... ARGS>
R function_return(R(*)(ARGS...));

template <typename R, typename... ARGS>
std::tuple<ARGS...> function_parameters(R(*)(ARGS...));

template <int I, typename T>
using get_type = typename std::conditional_t<(I < 0), std::tuple_element<static_cast<int>(std::tuple_size_v<T>) + I, T>, std::tuple_element>::type;

template <int I, typename T>
using parameter_type = get_type<I, decltype(function_parameters(std::declval<T>()))>;

Live Example (ICE under VS)
Live Example (working on GCC)

But when I try to use this on visual-studio-2017 I get an internal compiler error:

fatal error C1001: An internal error has occurred in the compiler.

Is there another way that I can do this which might work around the internal compiler error?

Body:
It probably depends on the exact (sub)version of VS2017, as mine does not produce an ICE on the code. However, the code is still problematic, as it can potentially instantiate std::tuple_element<2147483647, T> or something similar. You need to make sure only the correct branch is ever evaluated. Replace your definition of get_type with this:

template <int I, typename T, bool negative = (I < 0)>
struct get_type_impl;

template <int I, typename T>
struct get_type_impl<I, T, true>
{
  using type = typename std::tuple_element<static_cast<int>(std::tuple_size<T>::value) + I, T>::type;
};

template <int I, typename T>
struct get_type_impl<I, T, false>
{
  using type = typename std::tuple_element<I, T>::type;
};

template <int I, typename T>
using get_type = typename get_type_impl<I, T>::type;

This works for me on my VS 2017 (cl version 19.12)


问:
Database Design For Historical Table
I have a table of employers(Table A). I want to create a similar table with an extra date column(Table B), showing the date the rows were inserted. I want to insert the rows from Table A to the new table at the end of every month. Is there a way to automate this in SQL?

I have heard that you can do this through stored procedures, but I don't have any experience using them and any guidance would be greatly appreciated.

Here is what the table may look like:

```<code>MemberID First Last   Department Salary Daily_Hours Active_Flag
100      Evan  Turner Sales      75000  8           1
200      Ron   Gold   Marketing  80000  9           1
300      Bob   Gun    HR         50000  8           1
</code>```

Desired output:

```<code>ID MemberID First Last   Department Salary Daily_Hours Active_Flag Date
1  100      Evan  Turner Sales      75000  8           1           3/31/19
2  200      Ron   Gold   Marketing  80000  9           1           3/31/19
3  300      Bob   Gun    HR         50000  8           1           3/31/19
4  100      Evan  Turner Sales      75000  8           1           4/30/19
5  200      Ron   Gold   Marketing  80000  9           1           4/30/19
6  300      Bob   Gun    HR         50000  8           1           4/30/19
7  100      Evan  Turner Finance    95000  8           1           5/31/19
8  200      Ron   Gold   Marketing  80000  9           1           5/31/19
9  300      Bob   Gun    HR         60000  8           1           5/31/19
</code>```

Note how Evan Turner has changed department and received a salary bump on the month of May. Bob got a salary increase in the same month as well

The idea is that table A gets updated once every month and I want to record that change into the new table.

答:
Add a new column that records when a row is inserted:

```<code>alter table t add column createdAt datetime default getdate();
</code>```

This will be automatically populated with the insertion date (moving forward).

Title: Database Design For Historical Table

Body:
I have a table of employers(Table A). I want to create a similar table with an extra date column(Table B), showing the date the rows were inserted. I want to insert the rows from Table A to the new table at the end of every month. Is there a way to automate this in SQL?

I have heard that you can do this through stored procedures, but I don't have any experience using them and any guidance would be greatly appreciated.

Here is what the table may look like:

MemberID First Last   Department Salary Daily_Hours Active_Flag
100      Evan  Turner Sales      75000  8           1
200      Ron   Gold   Marketing  80000  9           1
300      Bob   Gun    HR         50000  8           1

Desired output:

ID MemberID First Last   Department Salary Daily_Hours Active_Flag Date
1  100      Evan  Turner Sales      75000  8           1           3/31/19
2  200      Ron   Gold   Marketing  80000  9           1           3/31/19
3  300      Bob   Gun    HR         50000  8           1           3/31/19
4  100      Evan  Turner Sales      75000  8           1           4/30/19
5  200      Ron   Gold   Marketing  80000  9           1           4/30/19
6  300      Bob   Gun    HR         50000  8           1           4/30/19
7  100      Evan  Turner Finance    95000  8           1           5/31/19
8  200      Ron   Gold   Marketing  80000  9           1           5/31/19
9  300      Bob   Gun    HR         60000  8           1           5/31/19

Note how Evan Turner has changed department and received a salary bump on the month of May. Bob got a salary increase in the same month as well

The idea is that table A gets updated once every month and I want to record that change into the new table.

Body:
Add a new column that records when a row is inserted:

alter table t add column createdAt datetime default getdate();

This will be automatically populated with the insertion date (moving forward).


问:
Why is flink SplitStream marked deprecated
Why is flink SplitStream marked deprecated?
Will the stream be removed in the future?
Or what else is there to replace this</p>

答:
Looks like it's not documented, but, I found the Pull Request which deprecated this class. https://github.com/apache/flink/commit/e0efabe8884f22b4a1c7ab9df3274b3fca03dcfb#diff-163a9f7f1b682eab706eb5e2a94faabcR36

By looking this PR you will see that it's missing the following description: Please use side ouput instead.

Looks like they forgot to add why and what to use instead.


答:
As mentioned here it seems like visual-studio-2017 struggles with templated using statements being passed to each other. (I'm seeing the internal compiler error on 15.6.7; as mentioned here this may have been fixed by patches.)

I've been able to work around it by capturing all the functionality in a single using statement:

```<code>template <typename R, typename... ARGS>
R function_return(R(*)(ARGS...));

template <typename R, typename... ARGS>
std::tuple<ARGS...> function_parameters(R(*)(ARGS...));

template <int I, typename T, typename X = decltype(function_parameters(std::declval<T>()))>
using parameter_type = typename std::conditional_t<(I < 0), std::tuple_element<static_cast<int>(std::tuple_size_v<X>) + I, X>, std::tuple_element<I, X>>::type;
</code>```

Title: Working Around a Visual Studio Internal Compiler Error With Nested Templated Variables

Body:
As mentioned here it seems like visual-studio-2017 struggles with templated using statements being passed to each other. (I'm seeing the internal compiler error on 15.6.7; as mentioned here this may have been fixed by patches.)

I've been able to work around it by capturing all the functionality in a single using statement:

template <typename R, typename... ARGS>
R function_return(R(*)(ARGS...));

template <typename R, typename... ARGS>
std::tuple<ARGS...> function_parameters(R(*)(ARGS...));

template <int I, typename T, typename X = decltype(function_parameters(std::declval<T>()))>
using parameter_type = typename std::conditional_t<(I < 0), std::tuple_element<static_cast<int>(std::tuple_size_v<X>) + I, X>, std::tuple_element<I, X>>::type;


问:
error 'import string_types ValueError: Attempted relative import in non-package'
Using cmd on windows 10 to run Python 2.7.16. When I run a .py file which imports scipy.py it comes up with the error:

"File "C:\Python27\scipy.py", line 18, in
      from .python import string_types
  ValueError: Attempted relative import in non-package"

As string_types should already be included in python, I don't understand why this error is happening and cant seem to get passed it. Does anyone know how to fix this?

答:
you tried,

```<code>>>> from . import MyModule #MyModule.py
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
>>>
</code>```

here . mean your current path

try,
    from MyModule import *

now you can use string_types

or

```<code>import MyModule as m
m.string_types
</code>```

Body:
you tried,

>>> from . import MyModule #MyModule.py
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
>>>

here . mean your current path

try,
    from MyModule import *

now you can use string_types

or

import MyModule as m
m.string_types


问:
SelectedIndexChanging not firing
I have a drop down list that I am populating from the code behind and I have a Gridview control below the drop down list that I am also populating from code behind. My goal is to select a department from the drop down list and populate the Gridview control will all employees in that department

This is my code to populate my Gridview control:

```<code>
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        If Not Me.IsPostBack Then

            LoadDataGrid()
            FillWithDepartments()

        End If

    End Sub

 Private Sub LoadDataGrid()

        Try
            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)

                Using cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] ,  CostCentre AS [Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No]  , EmployeeCodes.Code AS [Clock No] ,MedicalResults.[DateTested] AS [Date Tested]  , MedicalResults.[NextDueDate] AS [Next Due Date] , MedicalResults.ECGDate AS [ECG] , MedicalResults.LungFunctionDate AS [Lungfunction] , MedicalResults.AudioGramDate AS [Hearing Test] , MedicalResults.EyeTestDate AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND  EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND   MedicalResults.EmployeeID = EmployeeCodes.EmployeeID Order By DateTested DESC", conn)
                    Dim sda As New SqlDataAdapter(cmd)
                    Dim dt As New DataTable()

                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()

                End Using

            End Using

        Catch ex As Exception

        End Try

    End Sub

</code>```

This is the code to populate my drop down list from code behind:

```<code>    Protected Sub FillWithDepartments()

        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)
            'conn.Open()

            Dim cmd As New SqlCommand("SELECT Code , ShortDescription  FROM Departments", conn)
            Dim adapter As New SqlDataAdapter(cmd)
            Dim tbl As New DataTable()
            adapter.Fill(tbl)
            drplstDepartment.DataSource = tbl
            drplstDepartment.DataTextField = "ShortDescription"
            drplstDepartment.DataValueField = "Code"
            drplstDepartment.DataBind()

            ' conn.Close()

        End Using
    End Sub

</code>```

Front End Code for Drop Down List

```<code>
<asp:DropDownList ID="drplstDepartment" OnSelectedIndexChanged="drplstDepartment_SelectedIndexChanged"  CssClass="form-control mb-2 mr-sm-2" runat="server" AutoPostBack="true">
    </asp:DropDownList>

</code>```

Front End Code Fro Grid View

```<code>
     <asp:GridView  RowStyle-CssClass="text-center" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging"   AllowPaging="true" class="table table-default table-striped table-bordered table-condensed table-responsive table-hover" border="1" ID="GridView1" runat="server" HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Middle" HeaderStyle-BackColor="#6C6C6C" HeaderStyle-ForeColor="White"  RowStyle-BackColor="#eeeeee" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" RowStyle-ForeColor="#000"  AutoGenerateColumns="false" >
                 <Columns>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Department"     HeaderText = "Department"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Cost Centre"    HeaderText = "Cost Centre"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Name"           HeaderText = "Name" />
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Surname"        HeaderText = "Surname"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "ID No"          HeaderText = "ID No"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Clock No"       HeaderText = "Clock No"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Date Tested"    HeaderText = "Date Tested"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Next Due Date"  HeaderText = "Next Due Date"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "ECG"            HeaderText = "ECG"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Lungfunction"   HeaderText = "Lungfunction"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Hearing Test"   HeaderText = "Hearing Test"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Eye Test"       HeaderText = "Eye Test"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Other Problems" HeaderText = "Other Problems"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Notes"          HeaderText = "Notes"/>

                 </Columns>

                </asp:GridView>

</code>```

This is the code that is not firing

```<code>   Protected Sub drplstDepartment_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim dt As DataTable = New DataTable()
        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("#").ToString())

            Dim cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] ,  CostCentre AS [ Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No]  , EmployeeCodes.Code AS [Clock No] ,CONVERT(nvarchar(10), MedicalResults.[DateTested], 101) AS [Date Tested]  ,CONVERT(nvarchar(10), MedicalResults.[NextDueDate], 101)  AS [Next Due Date] , CONVERT(nvarchar(10), MedicalResults.ECGDate, 101) AS [ECG] , CONVERT(nvarchar(10), MedicalResults.LungFunctionDate, 101)  AS [Lungfunction] , CONVERT(nvarchar(10), MedicalResults.AudioGramDate, 101)   AS [Hearing Test] , CONVERT(nvarchar(10), MedicalResults.EyeTestDate, 101)  AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE  MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND  EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND   MedicalResults.EmployeeID = EmployeeCodes.EmployeeID AND (Departments.ShortDescription = @ShortDescription)", conn)

            cmd.Parameters.AddWithValue("@ShortDescription", drplstDepartment.SelectedValue)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Using

    End Sub

</code>```

答:
Try this instead in your drplstDepartment_SelectedIndexChanged event:

Dim cmd As New SqlCommand("SELECT
...
FROM
...
WHERE
...
AND (Departments.Code = @Code)", conn)

cmd.Parameters.AddWithValue("@Code", drplstDepartment.SelectedItem.Value)
```

@Code matches drplstDepartment.SelectedItem.Value, @ShortDescription matches drplstDepartment.SelectedItem.Text.

Title: SelectedIndexChanging not firing

Body:
I have a drop down list that I am populating from the code behind and I have a Gridview control below the drop down list that I am also populating from code behind. My goal is to select a department from the drop down list and populate the Gridview control will all employees in that department

This is my code to populate my Gridview control:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        If Not Me.IsPostBack Then

            LoadDataGrid()
            FillWithDepartments()

        End If

    End Sub

 Private Sub LoadDataGrid()

        Try
            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)

                Using cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] ,  CostCentre AS [Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No]  , EmployeeCodes.Code AS [Clock No] ,MedicalResults.[DateTested] AS [Date Tested]  , MedicalResults.[NextDueDate] AS [Next Due Date] , MedicalResults.ECGDate AS [ECG] , MedicalResults.LungFunctionDate AS [Lungfunction] , MedicalResults.AudioGramDate AS [Hearing Test] , MedicalResults.EyeTestDate AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND  EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND   MedicalResults.EmployeeID = EmployeeCodes.EmployeeID Order By DateTested DESC", conn)
                    Dim sda As New SqlDataAdapter(cmd)
                    Dim dt As New DataTable()

                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()

                End Using

            End Using

        Catch ex As Exception

        End Try

    End Sub

This is the code to populate my drop down list from code behind:

    Protected Sub FillWithDepartments()

        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)
            'conn.Open()

            Dim cmd As New SqlCommand("SELECT Code , ShortDescription  FROM Departments", conn)
            Dim adapter As New SqlDataAdapter(cmd)
            Dim tbl As New DataTable()
            adapter.Fill(tbl)
            drplstDepartment.DataSource = tbl
            drplstDepartment.DataTextField = "ShortDescription"
            drplstDepartment.DataValueField = "Code"
            drplstDepartment.DataBind()

            ' conn.Close()

        End Using
    End Sub

Front End Code for Drop Down List

<asp:DropDownList ID="drplstDepartment" OnSelectedIndexChanged="drplstDepartment_SelectedIndexChanged"  CssClass="form-control mb-2 mr-sm-2" runat="server" AutoPostBack="true">
    </asp:DropDownList>

Front End Code Fro Grid View

     <asp:GridView  RowStyle-CssClass="text-center" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging"   AllowPaging="true" class="table table-default table-striped table-bordered table-condensed table-responsive table-hover" border="1" ID="GridView1" runat="server" HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Middle" HeaderStyle-BackColor="#6C6C6C" HeaderStyle-ForeColor="White"  RowStyle-BackColor="#eeeeee" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" RowStyle-ForeColor="#000"  AutoGenerateColumns="false" >
                 <Columns>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Department"     HeaderText = "Department"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Cost Centre"    HeaderText = "Cost Centre"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Name"           HeaderText = "Name" />
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Surname"        HeaderText = "Surname"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "ID No"          HeaderText = "ID No"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Clock No"       HeaderText = "Clock No"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Date Tested"    HeaderText = "Date Tested"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Next Due Date"  HeaderText = "Next Due Date"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "ECG"            HeaderText = "ECG"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Lungfunction"   HeaderText = "Lungfunction"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Hearing Test"   HeaderText = "Hearing Test"/>
                     <asp:ButtonField ItemStyle-Width = "150px"   DataTextFormatString="{0:dd/MM/yyyy}"  DataTextField= "Eye Test"       HeaderText = "Eye Test"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Other Problems" HeaderText = "Other Problems"/>
                     <asp:ButtonField ItemStyle-Width = "150px"                                         DataTextField= "Notes"          HeaderText = "Notes"/>

                 </Columns>

                </asp:GridView>

This is the code that is not firing

   Protected Sub drplstDepartment_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim dt As DataTable = New DataTable()
        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("#").ToString())

            Dim cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] ,  CostCentre AS [ Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No]  , EmployeeCodes.Code AS [Clock No] ,CONVERT(nvarchar(10), MedicalResults.[DateTested], 101) AS [Date Tested]  ,CONVERT(nvarchar(10), MedicalResults.[NextDueDate], 101)  AS [Next Due Date] , CONVERT(nvarchar(10), MedicalResults.ECGDate, 101) AS [ECG] , CONVERT(nvarchar(10), MedicalResults.LungFunctionDate, 101)  AS [Lungfunction] , CONVERT(nvarchar(10), MedicalResults.AudioGramDate, 101)   AS [Hearing Test] , CONVERT(nvarchar(10), MedicalResults.EyeTestDate, 101)  AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE  MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND  EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND   MedicalResults.EmployeeID = EmployeeCodes.EmployeeID AND (Departments.ShortDescription = @ShortDescription)", conn)

            cmd.Parameters.AddWithValue("@ShortDescription", drplstDepartment.SelectedValue)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Using

    End Sub

Body:
Try this instead in your drplstDepartment_SelectedIndexChanged event:

Dim cmd As New SqlCommand("SELECT
...
FROM
...
WHERE
...
AND (Departments.Code = @Code)", conn)

cmd.Parameters.AddWithValue("@Code", drplstDepartment.SelectedItem.Value)

@Code matches drplstDepartment.SelectedItem.Value, @ShortDescription matches drplstDepartment.SelectedItem.Text.


问:
How to remove duplicated words in csv rows in python?
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

```<code>userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.
</code>```

I would like to have the output as:

```<code>userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.
</code>```

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

答:
Answer taken from How can I tell if a string repeats itself in Python?

```<code>import pandas as pd
def principal_period(s):
    s+=' '
    i = (s + s).find(s, 1, -1)
    return None if i == -1 else s[:i]
df=pd.read_csv(r'path\to\filename_in.csv')
df['description'].apply(principal_period)
df.to_csv(r'output\path\filename_out.csv')
</code>```

Explanation:

I have added a space at the end to account for that the repeating strings are delimited by space. Then it looks for second occurring string (minus first and last character to avoid matching first, and last when there are no repeating strings, respectively) when the string is added to itself. This efficiently finds the position of string where the second occuring string starts, or the first shortest repeating string ends. Then this repeating string is returned.

Body:
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.

I would like to have the output as:

userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

Body:
Answer taken from How can I tell if a string repeats itself in Python?

import pandas as pd
def principal_period(s):
    s+=' '
    i = (s + s).find(s, 1, -1)
    return None if i == -1 else s[:i]
df=pd.read_csv(r'path\to\filename_in.csv')
df['description'].apply(principal_period)
df.to_csv(r'output\path\filename_out.csv')

Explanation:

I have added a space at the end to account for that the repeating strings are delimited by space. Then it looks for second occurring string (minus first and last character to avoid matching first, and last when there are no repeating strings, respectively) when the string is added to itself. This efficiently finds the position of string where the second occuring string starts, or the first shortest repeating string ends. Then this repeating string is returned.


答:
I figured out in the meantime how to do it. Applied on the database, the query looks like this:

```<code>DECLARE @Temp TABLE (ImageId INT, Id INT)

MERGE INTO Translation USING
  (
  SELECT Image.Name AS Name, Image.Id AS ImageId
  FROM Candidate
  INNER JOIN Candidacy ON Candidate.Id = Candidacy.CandidateId
  INNER JOIN Election ON Candidacy.ElectionId = Election.Id
  INNER JOIN SmartVoteCandidate ON Candidate.Id = SmartVoteCandidate.CandidateId
  INNER JOIN Image ON SmartVoteCandidate.SpiderImageId = Image.Id
  WHERE Election.Id = 1575) AS temp ON 1 = 0
WHEN NOT MATCHED THEN
  INSERT (De)
  VALUES (temp.Name)
  OUTPUT temp.ImageId, INSERTED.Id
  INTO @Temp (ImageId, Id);

UPDATE Image
SET Image.TranslationId = t.Id, Name = NULL
FROM @Temp t
WHERE Image.Id = t.ImageId
</code>```

The solution is heavily inspired by

Is it possible to for SQL Output clause to return a column not being inserted?

Using a join in a merge statement

Title: Insert on a child table and update FK on parent

Body:
I have a parent table with the following structure and data:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |          NULL |          Image1.jpg |
|   2 |          NULL |          Image7.jpg |
|   3 |          NULL |    Picture_Test.png |
---------------------------------------------

And the empty child table which holds the translated images:

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|     |                     |                     |                     |
-------------------------------------------------------------------------

Now I'm looking for a single query statement or at least few queries which I can run without any further programming. Doing this job with scripting or programming would be easy but I have often situations where I need this kind of insert / update. And developing each time a small console app is not feasible.

At the end the two tables should look like this:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |            28 |                NULL |
|   2 |            29 |                NULL |
|   3 |            30 |                NULL |
---------------------------------------------

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|  28 |          Image1.jpg |                NULL |               NULL  |
|  29 |          Image7.jpg |                NULL |               NULL  |
|  30 |    Picture_Test.png |                NULL |               NULL  |
-------------------------------------------------------------------------

Thank you for any advice.

Body:
I figured out in the meantime how to do it. Applied on the database, the query looks like this:

DECLARE @Temp TABLE (ImageId INT, Id INT)

MERGE INTO Translation USING
  (
  SELECT Image.Name AS Name, Image.Id AS ImageId
  FROM Candidate
  INNER JOIN Candidacy ON Candidate.Id = Candidacy.CandidateId
  INNER JOIN Election ON Candidacy.ElectionId = Election.Id
  INNER JOIN SmartVoteCandidate ON Candidate.Id = SmartVoteCandidate.CandidateId
  INNER JOIN Image ON SmartVoteCandidate.SpiderImageId = Image.Id
  WHERE Election.Id = 1575) AS temp ON 1 = 0
WHEN NOT MATCHED THEN
  INSERT (De)
  VALUES (temp.Name)
  OUTPUT temp.ImageId, INSERTED.Id
  INTO @Temp (ImageId, Id);

UPDATE Image
SET Image.TranslationId = t.Id, Name = NULL
FROM @Temp t
WHERE Image.Id = t.ImageId

The solution is heavily inspired by

Is it possible to for SQL Output clause to return a column not being inserted?

Using a join in a merge statement


问:
Filling columns of modified flags for old revisions in Hibernate Envers
I'm adding modified flags to an already existing audit table. The flags for new revisions added to the table are filled correctly but I want the flags for already existing revisions to be filled.

I could procedurally check revisions for changes and update the columns, but it would take a lot of time to write an specific procedure for each table.

For example, this is the data of a user from my user_aud table before adding the columns:

```<code>id  |rev  |revtype|username     |password
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4
</code>```

When I set withModifiedFlag to true in my User entity as this:

```<code>@Entity
@Audited(withModifiedFlag = true)
public class User {
   // Attributes, getters and setters...
}
</code>```

then, Hibernate adds the columns for the flags, but with null values on existing rows while working as expected for new revisions:

```<code>id  |rev  |revtype|username     |password                         |username_mod |password_mod
100 |60745|1      |pdacostaporto|4305664d643844973ccb52cbb7c369f8 |false        |true
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96 |null         |null
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4 |null         |null
</code>```

I would like to fill the null columns of already existing rows with the correct values, as this:

```<code>id  |rev  |revtype|username     |password                         |username_mod |password_mod
100 |60745|1      |pdacostaporto|4305664d643844973ccb52cbb7c369f8 |false        |true
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96 |false        |true
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4 |false        |false
</code>```

答:
Unfortunately there is currently no automated way that Envers will update existing audit history rows for that feature if you enable it after a table has existing data; that is something which you have to do manually.

If you decide to do this manually, here's the logic:

Rows with REVTYPE=0 will always have the _MOD columns equal to true or 1.  I noticed you had them set to false in your original question and that's incorrect and may create query problems.

Rows with REVTYPE!=0 will only be set to true or 1 if the value for the data column is different from the value in the same column in the prior revision.

Ideally, you should be able to make use of the database's metadata and write a single script that would take a table name and perform all the necessary operations regardless of the table.

Body:
I'm adding modified flags to an already existing audit table. The flags for new revisions added to the table are filled correctly but I want the flags for already existing revisions to be filled.

I could procedurally check revisions for changes and update the columns, but it would take a lot of time to write an specific procedure for each table.

For example, this is the data of a user from my user_aud table before adding the columns:

id  |rev  |revtype|username     |password
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4

When I set withModifiedFlag to true in my User entity as this:

@Entity
@Audited(withModifiedFlag = true)
public class User {
   // Attributes, getters and setters...
}

then, Hibernate adds the columns for the flags, but with null values on existing rows while working as expected for new revisions:

id  |rev  |revtype|username     |password                         |username_mod |password_mod
100 |60745|1      |pdacostaporto|4305664d643844973ccb52cbb7c369f8 |false        |true
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96 |null         |null
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4 |null         |null

I would like to fill the null columns of already existing rows with the correct values, as this:

id  |rev  |revtype|username     |password                         |username_mod |password_mod
100 |60745|1      |pdacostaporto|4305664d643844973ccb52cbb7c369f8 |false        |true
100 |51544|1      |pdacostaporto|420bed36a05fa4668b1baeff18ffce96 |false        |true
100 |46343|0      |pdacostaporto|286755fad04869ca523320acce0dc6a4 |false        |false


问:
Firebase realtime database : Does the user download the entire database every time?
I want the user to send some data to the database. But the downloaded data is a little high.
These are my rules:

```<code>{
  "rules": {
    ".read": false,
    ".write": true
  }
}
</code>```

In one day, the downloaded data has become 7.2 mb. The size of my database is around 320kb. This is my code where I'm using it.

```<code>String id = mDatabase.child(username).push().getKey();
Record r = new Record(calendar.getTimeInMillis(),sensorValue);
mDatabase.child(username).child(id).setValue(r);

</code>```

答:
No, Firebase doesn't download all the data any time you start your application if you don't need it (depends on the data you are querying).

So the correct answer is that it depends on the code of your app. For example if you have code like

```<code>db.ref('users/user_id').once((snap) => { ... })
</code>```

it means that only particular data, placed under user_id field is downloaded.

But if, for example, you write such code:

```<code>db.ref('users').once((snap) => { ... })
</code>```

the whole users object will be downloaded.

Hope, now it is clear for you that bandwidth depends on how much data is queried from your app code perspective.

Body:
I want the user to send some data to the database. But the downloaded data is a little high.
These are my rules:

{
  "rules": {
    ".read": false,
    ".write": true
  }
}

In one day, the downloaded data has become 7.2 mb. The size of my database is around 320kb. This is my code where I'm using it.

String id = mDatabase.child(username).push().getKey();
Record r = new Record(calendar.getTimeInMillis(),sensorValue);
mDatabase.child(username).child(id).setValue(r);

Body:
No, Firebase doesn't download all the data any time you start your application if you don't need it (depends on the data you are querying).

So the correct answer is that it depends on the code of your app. For example if you have code like

db.ref('users/user_id').once((snap) => { ... })

it means that only particular data, placed under user_id field is downloaded.

But if, for example, you write such code:

db.ref('users').once((snap) => { ... })

the whole users object will be downloaded.

Hope, now it is clear for you that bandwidth depends on how much data is queried from your app code perspective.