问:
jq: Turn json object values into arrays
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

```<code>[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]
</code>```

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

```<code>[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]
</code>```

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

Title: jq: Turn json object values into arrays

Body:
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

Body:
With 2-step reduce(it doesn't look beautiful but works):

jq 'reduce group_by(.ID)[] as $a ([]; . + [ reduce $a[] as $o
   ({"DATE":[],"VALUE_ONE":[],"VALUE_TWO":[]};
    .DATE |= .+ [$o.DATE] | .ID = $o.ID |.VALUE_ONE |= .+ [$o.VALUE_ONE]
    | .VALUE_TWO |= .+ [$o.VALUE_TWO]) ] )' input.json

The output:

[
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "VALUE_ONE": [
      20,
      30,
      25
    ],
    "VALUE_TWO": [
      5,
      7,
      2
    ],
    "ID": "X"
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "VALUE_ONE": [
      10,
      20,
      50
    ],
    "VALUE_TWO": [
      9,
      5,
      5
    ],
    "ID": "Y"
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "VALUE_ONE": [
      55,
      60,
      15
    ],
    "VALUE_TWO": [
      3,
      7,
      7
    ],
    "ID": "Z"
  }
]


来源: stackexchange

问:
angular material md-datepicker inside bootstrap modal
I am tring to use Angular material  md-datepicker inside a Bootstrap modal but, on clicking the date the modal popup hides. How can i solve that problem?

            <button type="button" class="close forVideoStop" data-dismiss="modal" aria-label="Close">×</button>

Introduction video for body composition ...

            <md-datepicker ng-model="myDob" md-placeholder="Enter date" name="dateField" max-date="maxDate"></md-datepicker>

```

<pre class="lang-html prettyprint-override"><code><div class="modal fade " tabindex="-1" role="dialog">
   <div class="modal-dialog" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <button type="button" class="close forVideoStop" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title">Introduction video for body composition ...</h4>
         </div>
         <div class="modal-body">
            <md-datepicker ng-model="myDob" md-placeholder="Enter date" name="dateField" max-date="maxDate"></md-datepicker>
         </div>
      </div>
   </div>
</div>
</code>```

How it is...

After disabling display: block in the modal class...

答:
The accepted answer doesn't work for @angular/material 5.0.0-rc0 .

Instead add in the <your_component>.component.scss file:

```<code>::ng-deep .cdk-overlay-container{
    z-index: 1200 !important;
}
</code>```

::ng-deep (or /deep/) prefix needs to be used because of the view encapsulation. Note that deep is marked as deprecated in the documentation and using cdk-overlay-container is probably not a good practice since future material module changes might break it.

ContentLicense: CC BY-SA 3.0

Body:
I am tring to use Angular material  md-datepicker inside a Bootstrap modal but, on clicking the date the modal popup hides. How can i solve that problem?

            <button type="button" class="close forVideoStop" data-dismiss="modal" aria-label="Close">×</button>

Introduction video for body composition ...

            <md-datepicker ng-model="myDob" md-placeholder="Enter date" name="dateField" max-date="maxDate"></md-datepicker>

            <button type="button" class="close forVideoStop" data-dismiss="modal" aria-label="Close">×</button>

Introduction video for body composition ...

            <md-datepicker ng-model="myDob" md-placeholder="Enter date" name="dateField" max-date="maxDate"></md-datepicker>

How it is...

After disabling display: block in the modal class...

Body:
The accepted answer doesn't work for @angular/material 5.0.0-rc0 .

Instead add in the <your_component>.component.scss file:

::ng-deep .cdk-overlay-container{
    z-index: 1200 !important;
}

::ng-deep (or /deep/) prefix needs to be used because of the view encapsulation. Note that deep is marked as deprecated in the documentation and using cdk-overlay-container is probably not a good practice since future material module changes might break it.


问:
Differences between arm64 and aarch64
I have two "unlocked" devices, an iPad mini 3, and a Galaxy Edge 6, both endowed with a terminal and a minimalistic set of unix commands. I thought both devices have arm64 processors but when I ran

```<code>uname -a
</code>```

on both devices I got the following :

for the iPad mini 3 :

```<code>xxxxs-iPad:/var/mobile root# uname -a
Darwin xxxx-iPad 14.0.0 Darwin Kernel Version 14.0.0: Wed Jun 24 00:50:15 PDT 2015; root:xnu-2784.30.7-30/RELEASE_ARM64_S5L8960X iPad4, **arm64**, J85mAP
</code>```

for the Samsung Galaxy s6 Edge :

```<code>u0_a203@zerolte:/ $ uname -a
Linux localhost 3.10.61-4497415 #1 SMP PREEMPT Thu Apr 9 15:06:40 KST 2015 **aarch64** GNU/Linux
</code>```

If I am not wrong, the last info in both case, J85mAP and GNU/Linux, stand for firmwares, and the antepenultimate infos, arm64 and aarch64, stand for the processors.

My questions are the following : obviously the strings "arm64" and "aarch64" are not the same, but I always thought arm64 and aarch64 were the same. (It's even told when you put the arm64 tag to a question here.)

So, are they really identical?

Especially, what should I worry about in case of cross-building libraries for both targets ? In fact, I have gcc 5.2.0 in mind, but maybe also lower versions. Can I just pass

```<code>-target=arm64
</code>```

or

```<code>-target=aarch64
</code>```

according to which device I target and just worry about the rest of options to configure?

EDIT Hum, look for this again, without success.

答:
"AArch64" and "ARM64" refer to the same thing.

AArch64 is the 64-bit state introduced in the Armv8-A architecture. The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32.
Therefore the GNU triplet for the 64-bit ISA is aarch64.
The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

The Apple-developed backend for AArch64 was called "ARM64" whereas the LLVM community-developed backend was called "AArch64" (as it is the canonical name for the 64-bit ISA). The two were merged in 2014 and the backend now is called "AArch64".

Title: Differences between arm64 and aarch64

Body:
I have two "unlocked" devices, an iPad mini 3, and a Galaxy Edge 6, both endowed with a terminal and a minimalistic set of unix commands. I thought both devices have arm64 processors but when I ran

uname -a

on both devices I got the following :

for the iPad mini 3 :

xxxxs-iPad:/var/mobile root# uname -a
Darwin xxxx-iPad 14.0.0 Darwin Kernel Version 14.0.0: Wed Jun 24 00:50:15 PDT 2015; root:xnu-2784.30.7-30/RELEASE_ARM64_S5L8960X iPad4, **arm64**, J85mAP

for the Samsung Galaxy s6 Edge :

u0_a203@zerolte:/ $ uname -a
Linux localhost 3.10.61-4497415 #1 SMP PREEMPT Thu Apr 9 15:06:40 KST 2015 **aarch64** GNU/Linux

If I am not wrong, the last info in both case, J85mAP and GNU/Linux, stand for firmwares, and the antepenultimate infos, arm64 and aarch64, stand for the processors.

My questions are the following : obviously the strings "arm64" and "aarch64" are not the same, but I always thought arm64 and aarch64 were the same. (It's even told when you put the arm64 tag to a question here.)

So, are they really identical?

Especially, what should I worry about in case of cross-building libraries for both targets ? In fact, I have gcc 5.2.0 in mind, but maybe also lower versions. Can I just pass

-target=arm64

or

-target=aarch64

according to which device I target and just worry about the rest of options to configure?

EDIT Hum, look for this again, without success.

ContentLicense: CC BY-SA 4.0


问:
How to click dynamic id button in selenium IDE?
I am searching it from 2 days but still unable to get satisfying answer..please help
I am using liferay, i want to open dropdown which name is "Add" and then want to click on submit button named as "Blank Site"..and both "Add" and "Blank site" button contains dynamic values/id which changes each time..attaching image for reference..

Image: Add
Image: blanksite

答:
Selenium supports wide range of different selectors besides byId. XPath is able to refer to text value inside the tag.

Also using almost any selector you can retrieve list that can be additionally filtered by any rules.


问:
What's the ugliest code you were forced to write by outside limitations?
What is the ugliest code that you wrote - not because you didn't know better, but because of limitations of the software, the hardware or the company policy?

Because of unusual choices in database layouts and programming languages, I once built a C program that read in a SQL database structure and generated another C program that'd read that database and back it up into a file, or copy it into a second database that shared more or less the same columns. It was a monster clunky code generator.

答: Any regular expression. :)</p>

ContentLicense: CC BY-SA 2.5

Body: Any regular expression. :)

OwnerDisplayName: Craig Stuntz


问:
Create a key value pair for both the current key and value
I currently have an array of simple objects:

```<code>data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]
</code>```

...to which I'd like to transform into

```<code>newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]
</code>```

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

答:
Im not familiar with loadsh, but with javascript you can do the following:</p>

```<code>var data = [{ "alternative hip hop": 3 }, { "escape room": 4 }]
var newData = [];

data.forEach((item)=>{ //loop over the array
  Object.keys(item) //get the object keys
    .map((keyName)=>{  //loop over each key
        newData.push({name:keyName, count:item[keyName]}) //insert it into the new array
     })
})
console.log(newData)
</code>```

Body:
I currently have an array of simple objects:

data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]

...to which I'd like to transform into

newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

Body:
Im not familiar with loadsh, but with javascript you can do the following:

var data = [{ "alternative hip hop": 3 }, { "escape room": 4 }]
var newData = [];

data.forEach((item)=>{ //loop over the array
  Object.keys(item) //get the object keys
    .map((keyName)=>{  //loop over each key
        newData.push({name:keyName, count:item[keyName]}) //insert it into the new array
     })
})
console.log(newData)


问:
copy file from one bucket to another in different account still set the s3 file owner to the source one
I have a bucket in one account and I am trying to copy the content from this bucket to another bucket in another account:

Here I found: AWS S3 copy files and folders between two buckets

The following command:

```<code>aws s3 sync s3://mybucket-src s3://mybucket-target
</code>```

does the trick. But the problem is when I copy an image in the destination bucket I see:

So as you can see the encryption is changed to access denied from none. So now when I even try to make the image public manually it does not work and I cannot even open the image.

Can anyone help what my problem is?

Here is my policy on target:

```<code>{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAll", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::xxxxxxxxxxxx:root", "" ] }, "Action": "", "Resource": [ "arn:aws:s3:::test", "arn:aws:s3:::test/*" ] } ] }
</code>```

Also the default encryption is none on both buckets

Update:
One more thing that might give a clue: I tested on another account with the same s3 set up and worked but those two accounts the same issue. I am not sure though what would be the issue since I am not even using encryption on s3. I think something is going on on account set up or maybe it is a bug in aws

Update:

One more thing I also noticed that the owner of the file copied in the new account is still the last account. So it is referencing to the last owner

答:
My answer assumes that you have the S3 objects encrypted using KMS Managed Keys (SSE-KMS).

You have two choices:

Redo the copy decrypting the files before storing unencrypted in the destination bucket.

Share encryption keys between accounts.

How to enable cross-account access to existing custom keys.

In the KMS console, click the custom key alias for which you want to enable cross-account access.

In the Key Usage section, look for the External Accounts subsection, and click Add External Account. Type the 12-digit AWS account ID of the account that you want to be able to use this key. Repeat this process for each additional external account you want to add. Click Save Changes when you are done.

Share Custom Encryption Keys

Body:
I have a bucket in one account and I am trying to copy the content from this bucket to another bucket in another account:

Here I found: AWS S3 copy files and folders between two buckets

The following command:

aws s3 sync s3://mybucket-src s3://mybucket-target

does the trick. But the problem is when I copy an image in the destination bucket I see:

So as you can see the encryption is changed to access denied from none. So now when I even try to make the image public manually it does not work and I cannot even open the image.

Can anyone help what my problem is?

Here is my policy on target:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAll", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::xxxxxxxxxxxx:root", "" ] }, "Action": "", "Resource": [ "arn:aws:s3:::test", "arn:aws:s3:::test/*" ] } ] }

Also the default encryption is none on both buckets

Update:
One more thing that might give a clue: I tested on another account with the same s3 set up and worked but those two accounts the same issue. I am not sure though what would be the issue since I am not even using encryption on s3. I think something is going on on account set up or maybe it is a bug in aws

Update:

One more thing I also noticed that the owner of the file copied in the new account is still the last account. So it is referencing to the last owner


问:
Got 'One of the sources for assign has an enumerable key on the prototype chain' on React native app
I am using react-native for Android app. And use axios as http library. When I try to send a Blob object through http post I will get below error:

```<code>HTTP Failure in Axios TypeError: One of the sources for assign has an enumerable key on the prototype chain. Are you trying to assign a prototype property? We don't allow it, as this is an edge case that we do not support. This error is a performance optimization and not spec compliant.
</code>```

Below is the code I used to add blob object on form data:

```<code>let data = new FormData()
  data.append('image', decodeBase64Image(image));
</code>```

below is the code to decode base64 image. And below code works fine in one of my website application.

```<code>export const decodeBase64Image = (dataURI) => {
  let byteString;
  if (dataURI === undefined) {
    return undefined
  }
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(dataURI.split(',')[1]);
  else
    byteString = unescape(dataURI.split(',')[1]);

  // separate out the mime component
  let mimeString = ''
  if (dataURI.split(',')[0] != undefined && dataURI.split(',')[0].split(':')[1] != undefined) {
    mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
  }
  // write the bytes of the string to a typed array
  let ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
     ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: mimeString});
}
</code>```

答:
The root of the problem is that the React Native devs made a performance optimization that is not spec-compliant (which is why the code works on your website, but not your React Native app). For more details, see the issue I opened here: https://github.com/facebook/react-native/issues/16814

As a workaround, you can use react-native-fetch-blob. I ran into the same error you did, and react-native-fetch-blob solved it for me.

Body:
I am using react-native for Android app. And use axios as http library. When I try to send a Blob object through http post I will get below error:

HTTP Failure in Axios TypeError: One of the sources for assign has an enumerable key on the prototype chain. Are you trying to assign a prototype property? We don't allow it, as this is an edge case that we do not support. This error is a performance optimization and not spec compliant.

Below is the code I used to add blob object on form data:

let data = new FormData()
  data.append('image', decodeBase64Image(image));

below is the code to decode base64 image. And below code works fine in one of my website application.

export const decodeBase64Image = (dataURI) => {
  let byteString;
  if (dataURI === undefined) {
    return undefined
  }
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(dataURI.split(',')[1]);
  else
    byteString = unescape(dataURI.split(',')[1]);

  // separate out the mime component
  let mimeString = ''
  if (dataURI.split(',')[0] != undefined && dataURI.split(',')[0].split(':')[1] != undefined) {
    mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
  }
  // write the bytes of the string to a typed array
  let ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
     ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: mimeString});
}


问:
Expand environment variable for My Documents
I know I can read environment variables like this:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

However, it would be really helpful to me if I could do something like this:

```<code>Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");
</code>```

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

```<code>Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");
</code>```

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

答:
Is there an environment variable that equals SpecialFolder.MyDocuments?

Short answer: No.

Long answer:

Still no. You can type "set" into a Command Prompt to see all you current environment variables. I couldn't find any for my documents folder on my profile (tried on WinXP and Win7).

Also, expanding "%USERPROFILE%\My Documents" would be incorrect since the user's documents folder could be anywhere else (e.g., on my home PC I always change mine to D:\Documents).

If you really need to use environment variables, one solution might be to set the variable yourself:

```<code>// this environment variable is created for the current process only
string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Environment.SetEnvironmentVariable("MYDOCUMENTS", documents);
</code>```

Another solution might be to use a "fake" environment variable in the path and expand it yourself, something like:

```<code>string path = "%MYDOCUMENTS%\\Foo"; // read from config

// expand real env. vars
string expandedPath1 = Environment.ExpandEnvironmentVariables(path);

// expand our "fake" env. var
string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string expandedPath2 = path.Replace("%MYDOCUMENTS%", documents);
</code>```

Body:
I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

Body:
Is there an environment variable that equals SpecialFolder.MyDocuments?

Short answer: No.

Long answer:

Still no. You can type "set" into a Command Prompt to see all you current environment variables. I couldn't find any for my documents folder on my profile (tried on WinXP and Win7).

Also, expanding "%USERPROFILE%\My Documents" would be incorrect since the user's documents folder could be anywhere else (e.g., on my home PC I always change mine to D:\Documents).

If you really need to use environment variables, one solution might be to set the variable yourself:

// this environment variable is created for the current process only
string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Environment.SetEnvironmentVariable("MYDOCUMENTS", documents);

Another solution might be to use a "fake" environment variable in the path and expand it yourself, something like:

string path = "%MYDOCUMENTS%\\Foo"; // read from config

// expand real env. vars
string expandedPath1 = Environment.ExpandEnvironmentVariables(path);

// expand our "fake" env. var
string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string expandedPath2 = path.Replace("%MYDOCUMENTS%", documents);


问:
WPF: ListView: Display a default value instead of an empty string
I have a Listview that's ItemSource is bound to a ObservableCollection and that's SelectedItem is bound to a string. It is possible that the observable collection contains an empty string; in that case, I want the listview to display some special string instead of just an empty item without text.

This is how I imagine it should work:

```<code><ListView ItemSource="{Binding AvailableTags}" SelectedItem="{Binding SelectedTag}">
<ListView.ItemContainerStyle>
     <Style TargetType="ListViewItem">
          <Setter Property="Content" Value="Untagged" />
              <Style.Triggers>
                   <DataTrigger Binding="-> Which binding to use?" Value="">
                       <Setter Property="Content" Value="-> How to get the Default value?" />
                   </DataTrigger>
              </Style.Triggers>
     </Style>
</ListView.ItemContainerStyle>
</ListView>
</code>```

As you can see, in this dummy source code, there are two place holders. How can I make it working? Or am I on the wrong track?

答:
You can modify the ListView ItemTemplate, and use an IValueConverter as such:

```<code><ListView
        ItemsSource="{Binding AvailableTags}"
        SelectedItem="{Binding SelectedTag}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Converter={StaticResource TagConverter}}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

The converter:

```<code>public class TagConverter : IValueConverter
{
    #region IValueConverter Members

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string tag = (string)value;

        return string.IsNullOrEmpty(tag) ? "Your custom string display" : tag;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
</code>```

Remember to add the converter as a resource in scope.

Body:
I have a Listview that's ItemSource is bound to a ObservableCollection and that's SelectedItem is bound to a string. It is possible that the observable collection contains an empty string; in that case, I want the listview to display some special string instead of just an empty item without text.

This is how I imagine it should work:

<ListView ItemSource="{Binding AvailableTags}" SelectedItem="{Binding SelectedTag}">
<ListView.ItemContainerStyle>

     </Style>
</ListView.ItemContainerStyle>
</ListView>

As you can see, in this dummy source code, there are two place holders. How can I make it working? Or am I on the wrong track?

Body:
You can modify the ListView ItemTemplate, and use an IValueConverter as such:

<ListView
        ItemsSource="{Binding AvailableTags}"
        SelectedItem="{Binding SelectedTag}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Converter={StaticResource TagConverter}}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

The converter:

public class TagConverter : IValueConverter
{
    #region IValueConverter Members

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string tag = (string)value;

        return string.IsNullOrEmpty(tag) ? "Your custom string display" : tag;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Remember to add the converter as a resource in scope.


问:
Gulp watch not working - cannot find module connect
Trying to run my project using gulp (havent used gulp before and have inherited an exisiting project).

I install the dependencies into the wordpress theme directory.

Running gulp watch throws this error:

```<code>Error: Cannot find module 'connect'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\dev\projects\romac-website\web\app\themes\romac\node_modules\browser-sync\lib\utils.js:307:31)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
</code>```

I have tried to update npm but not sure if it is fine or the problem (still).

I also tried to ins install this module with npm -g install connect

What should I try next?

答: Try deleting the node-modules folder then reinstall npm install connect --save-dev Then retry running gulp

Body:
Trying to run my project using gulp (havent used gulp before and have inherited an exisiting project).

I install the dependencies into the wordpress theme directory.

Running gulp watch throws this error:

Error: Cannot find module 'connect'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\dev\projects\romac-website\web\app\themes\romac\node_modules\browser-sync\lib\utils.js:307:31)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

I have tried to update npm but not sure if it is fine or the problem (still).

I also tried to ins install this module with npm -g install connect

What should I try next?


问:
Download mp3 file
I would like to use a website from R. The website is http://soundoftext.com/ where I can download WAV. files with audios from a given text and a language (voice).

There are two steps to download the voice in WAV:
1) Insert text and Select language. And Submit
2) On the new window, click Save and select folder.

Until now, I could get the xml tree, convert it to list and modify the values of text and language. However, I don't know how to convert the list to XML (with the new values) and execute it. Then, I would need to do the second step too.

Here is my code so far:

```<code>require(RCurl)
require(XML)
webpage <- getURL("http://soundoftext.com/")
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
x<-xmlToList(pagetree)
# Inserting word
x$body$div$div$div$form$div$label$.attrs[[1]]<-"Raúl"
x$body$div$div$div$form$div$label$.attrs[[1]]

# Select language
x$body$div$div$div$form$div$select$option$.attrs<-"es"
x$body$div$div$div$form$div$select$option$.attrs
</code>```

I have follow this approach but there is an error with "tag".

UPDATED: I just tried to use rvest to download the audio file, however, it does not respond or trigger anything. What am I doing wrong (missing)?

```<code>url <- "http://soundoftext.com/"
s <- html_session(url)
f0 <- html_form(s)
f1 <- set_values(f0[[1]], text="Raúl", lang="es")
attr(f1, "type") <- "Submit"
s[["fields"]][["submit"]] <- f1
attr(f1, "Class") <- "save"

test <- submit_form(s, f1)
</code>```

答:
Creator of Sound of Text here. Sorry it took so long for me to find this post.

I just redesigned Sound of Text, so your html parsing probably won't work anymore.
However, there is now an API that you can use which should make things considerably easier for you.

You can find the documentation here: https://soundoftext.com/docs

I apologize if it's not very good. Please let me know if you have any questions.

Title: Download mp3 file

Body:
I would like to use a website from R. The website is http://soundoftext.com/ where I can download WAV. files with audios from a given text and a language (voice).

There are two steps to download the voice in WAV:
1) Insert text and Select language. And Submit
2) On the new window, click Save and select folder.

Until now, I could get the xml tree, convert it to list and modify the values of text and language. However, I don't know how to convert the list to XML (with the new values) and execute it. Then, I would need to do the second step too.

Here is my code so far:

require(RCurl)
require(XML)
webpage <- getURL("http://soundoftext.com/")
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
x<-xmlToList(pagetree)
# Inserting word
x$body$div$div$div$form$div$label$.attrs[[1]]<-"Raúl"
x$body$div$div$div$form$div$label$.attrs[[1]]

# Select language
x$body$div$div$div$form$div$select$option$.attrs<-"es"
x$body$div$div$div$form$div$select$option$.attrs

I have follow this approach but there is an error with "tag".

UPDATED: I just tried to use rvest to download the audio file, however, it does not respond or trigger anything. What am I doing wrong (missing)?

url <- "http://soundoftext.com/"
s <- html_session(url)
f0 <- html_form(s)
f1 <- set_values(f0[[1]], text="Raúl", lang="es")
attr(f1, "type") <- "Submit"
s[["fields"]][["submit"]] <- f1
attr(f1, "Class") <- "save"

test <- submit_form(s, f1)


问:
search filter using regex similar to sql Like 'a%'
i have this search filter, how do i implement a regex to make it work like the sql ( Like 'a%' ) that finds any values that starts with a ?

```<code>function SFName() {

    var input, filter, table, tr, td, i;
    input = document.getElementById("SFNameInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";

            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
</code>```

this is what i tried :

```<code>function SFName() {

    var input, regex, table, tr, td, i;
    input = document.getElementById("SFNameInput").value;
    regex = /^/gi;
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[2];
        if (td) {
            if (regex.exec(td.innerHTML).indexOf(input) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
</code>```

https://jsfiddle.net/j7t5d9ud/

答:
If you want to check starts with you can use myStr.indexOf(value) === 0.  The regex doesn't appear to be necessary here.

This line

if (regex.exec(td.innerHTML).indexOf(input) > -1) {

becomes

if (td.innerHTML.indexOf(input) === 0) {

Body:
i have this search filter, how do i implement a regex to make it work like the sql ( Like 'a%' ) that finds any values that starts with a ?

function SFName() {

    var input, filter, table, tr, td, i;
    input = document.getElementById("SFNameInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i
 -1) {
                tr[i].style.display = "";

            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

this is what i tried :

function SFName() {

    var input, regex, table, tr, td, i;
    input = document.getElementById("SFNameInput").value;
    regex = /^/gi;
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i
 -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

https://jsfiddle.net/j7t5d9ud/


问:
securing passwords in code
Even with https enabled, you can write a password to the event log in code-behind.  Any way to keep that password encrypted in code while you're checking it against a data store?

(using Login control)

(couldn't add comment to Andrew's answer, so I'm putting it here)

NTLM uses the username/password of the machine the user is logged into right?  For this, I was thinking using ActiveDirectory on the server as the data store.  It would have a diferrent un/pw than what the user is currently signed in to their machine as.

答:
Check the SecureString class.

Represents text that should be kept confidential. The text is encrypted for privacy when being used, and deleted from computer memory when no longer needed.

Title: securing passwords in code


问:
How to make a Ajax search with Symfony and Jquery
hi guys i'm working in symfony project and i would like to do a realtime search using ajax.
I tried but its not working, for some reason, returns all datas from the database and not the data that i'm searching using keyup.
Can anyone help me please.
here is my code

```<code><div id="div">
    </div>

    <table border="1">
    <tr>
        <td>Id</td><td>Libelle</td><td>pays</td>
    </tr>
    {% for i in voitures %}
            <tr>
            <td>{{ i.id}}</td>
            <td>{{ i.libelle}}</td>
            <td>{{ i.pays}}</td>

           </tr>
     {% endfor %}
    </table>
    {{ form_start(form) }}
    {{ form(form) }}
    {{ form_errors(form) }}
    {{ form_end(form) }}

     <script src="{{ asset('js/jquery.js') }}"></script>
     <script>
     $("#myapp_parcbundle_marque_libelle").keyup(
            function(){
                 var serie=$('#myapp_parcbundle_marque_libelle').val();
                var DATA = 'serie=' + serie;
                $.ajax({
                    type: "POST",
                    url: "{{ path('demo_create')}}",
                    data:DATA,
                    success: function (msg) {
                        $( "#div" ).html( msg );
                    }
                });
            });

</script>
</code>```

Controller

```<code>function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);

    if($request->isXmlHttpRequest()&&($Form->isValid())){

        $voitures = $em->getRepository("MyAppParcBundle:Marque")
            ->findBy(array('serie'=>$voiture->getSerie()));
        return new JsonResponse($voitures);

    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}
</code>```

答:
When you POST a form, Symfony fills in the data for you. In AJAX, you have to handle the POST yourself.

The problem:

You're using $voiture = new Marque(); instead of serie; // sent by your $.ajax().

You've POST'd only one piece of data to Symfony, not the whole form, so $form->handleRequest(); (which fills in $voiture with the POST data) won't work.

```<code>// function testAction()
// ...
if ($request->isXmlHttpRequest() && $Form->isValid()) {
    $voitures = $em->getRepository("MyAppParcBundle:Marque")
        ->findBy(array(
            'serie' => $voiture->getSerie() // Not connected to the POST data.
        ));

    return new JsonResponse($voitures);
}
</code>```

The solution (you're very close):

Get the data from the $request (more info):

```<code>if ($request->isXmlHttpRequest()) {
    $voitures = $em->getRepository("MyAppParcBundle:Marque")
        ->findBySerie( // shorthand findBy(), it's optional.
            $request->get('serie')
        );

    return new JsonResponse($voitures);
}
</code>```

Body:
hi guys i'm working in symfony project and i would like to do a realtime search using ajax.
I tried but its not working, for some reason, returns all datas from the database and not the data that i'm searching using keyup.
Can anyone help me please.
here is my code

        Id	Libelle	pays

    {% for i in voitures %}

            {{ i.id}}
            {{ i.libelle}}
            {{ i.pays}}

     {% endfor %}

    {{ form_start(form) }}
    {{ form(form) }}
    {{ form_errors(form) }}
    {{ form_end(form) }}

Controller

function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);

    if($request->isXmlHttpRequest()&&($Form->isValid())){

        $voitures = $em->getRepository("MyAppParcBundle:Marque")
            ->findBy(array('serie'=>$voiture->getSerie()));
        return new JsonResponse($voitures);

    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}

Body:
When you POST a form, Symfony fills in the data for you. In AJAX, you have to handle the POST yourself.

The problem:

You're using $voiture = new Marque(); instead of serie; // sent by your $.ajax().

You've POST'd only one piece of data to Symfony, not the whole form, so $form->handleRequest(); (which fills in $voiture with the POST data) won't work.

// function testAction()
// ...
if ($request->isXmlHttpRequest() && $Form->isValid()) {
    $voitures = $em->getRepository("MyAppParcBundle:Marque")
        ->findBy(array(
            'serie' => $voiture->getSerie() // Not connected to the POST data.
        ));

    return new JsonResponse($voitures);
}

The solution (you're very close):

Get the data from the $request (more info):

if ($request->isXmlHttpRequest()) {
    $voitures = $em->getRepository("MyAppParcBundle:Marque")
        ->findBySerie( // shorthand findBy(), it's optional.
            $request->get('serie')
        );

    return new JsonResponse($voitures);
}


问:
Fitting a segment in a two-dimensional plane
I'm having troubles with the following problem

Given N x S grid and m segments parallel to the horizontal axis (all of them are tuples (x', x'', y)), answer Q online queries of form (x', x''). The answer to such a query is the smallest y (if there is one) such that we can place a segment (x', x'', y).  All segments are non-overlapping yet beginning of one segment can be the ending of another i.e. segments (x', x'', y) and (x'', x''', y) are allowed. Being able to place a segment means there could exist a segment (x', x'', y) that wouldn't violate stated rules, segment isn't actually placed(board with initial segments isn't modified) but we only state there could be one.

Constraints

```<code>1 ≤ Q, S, m ≤ 10^5
1 ≤ N ≤ 10^9

Time: 1s
Memory: 256 Mb
</code>```

Here is an example from the link below. Input segments are (2, 5, 1), (1, 2, 2), (4, 5, 2), (2, 3, 3), (3, 4, 3).

Answer for queries

1) (1, 2)  → 1

2) (2, 3)  → 2

3) (3, 4)  → 2

4) (4, 5)  → 3

5) (1, 3)  → can't place a segment

A visualized answer for the third query (blue segment):

I don't quite understand how to approach the problem. It is supposed to be solved with persistent segment tree, but I am still unable to come up with something.

Could you help me please.

This is not my homework. The source problem can be found here http://informatics.mccme.ru/mod/statements/view3.php?chapterid=111614 . There's no English version of the statement avaliable and the test case presents input data in a different way, so don't mind the souce.

答:
Here is an O(N log N) time solution.

Preliminaries (a good tutorial available here): segment tree, persistent segment tree.

Part 0. Original problem statement

I briefly describe the original problem statement as later I'm going to speak in its terms rather than in terms of abstract segments.

There is a train with S seats (S <= 10^5). It is known that seat s_i is occupied from time l_i to time r_i (no more than 10^5 such constraints, or passengers). Then we have to answer 10^5 queries of kind "find the lowest number of a seat with is free from time l_i to time r_i or say if there is none". All queries must be answered online, that is, you have to answer the previous query before seeing the next.

Throughout the text I denote with N both the number of seats, the number of passengers, and the number of queries, assuming they are the same order of magnitude. You can do more accurate analysis if needed.

Part 1. Answering a single query

Let's answer a query [L, R] assuming that there are no occupied places after time R. For each seat we maintain the last time when it is occupied. Call it last(S). Now the answer for the query is minimum S such that last(S) <= L. If we build a segment tree on seats then we'll be able to answer this query in O(log^2 N) time: binary search the value of S, check if range minimum on segment [0, S] is at most L.

However, it might be not enough to get Accepted. We need O(log N). Recall that each node of a segment tree stores minimum in corresponding range. We start at the root. If the minimum there is >= L then there is no available seat for such query. Otherwise either minimum in the left child or in the right child is <= L (or in both). In the first case we descend to the left child, in the second – to the right, and repeat until we reach a leaf. This leaf will correspond to the minimum seat with last(S) <= L.

Part 2. Solving the problem

We maintain a persistent tree on seats, storing last(S) for each seat (same as in the previous part). Let's process initial passengers one by one sorted by their left endpoint in increasing order. For a passenger (s_i, l_i, r_i) we update the segment tree at position s_i with value r_i. The tree is persistent, so we store the new copy somewhere.

To answer a query [L, R], find a latest version of the segment tree such that the update happened before R. If you do a binary search on versions, it takes O(log N) time.

In the version of the segment tree only passengers with their left endpoint < R are considered (even more, exactly such passengers are). So we can use the algorithm from the Part 1 to answer the query using this segment tree.

Body:
I'm having troubles with the following problem

Given N x S grid and m segments parallel to the horizontal axis (all of them are tuples (x', x'', y)), answer Q online queries of form (x', x''). The answer to such a query is the smallest y (if there is one) such that we can place a segment (x', x'', y).  All segments are non-overlapping yet beginning of one segment can be the ending of another i.e. segments (x', x'', y) and (x'', x''', y) are allowed. Being able to place a segment means there could exist a segment (x', x'', y) that wouldn't violate stated rules, segment isn't actually placed(board with initial segments isn't modified) but we only state there could be one.

Constraints

1 ≤ Q, S, m ≤ 10^5
1 ≤ N ≤ 10^9

Time: 1s
Memory: 256 Mb

Here is an example from the link below. Input segments are (2, 5, 1), (1, 2, 2), (4, 5, 2), (2, 3, 3), (3, 4, 3).

Answer for queries

1) (1, 2)  → 1

2) (2, 3)  → 2

3) (3, 4)  → 2

4) (4, 5)  → 3

5) (1, 3)  → can't place a segment

A visualized answer for the third query (blue segment):

I don't quite understand how to approach the problem. It is supposed to be solved with persistent segment tree, but I am still unable to come up with something.

Could you help me please.

This is not my homework. The source problem can be found here http://informatics.mccme.ru/mod/statements/view3.php?chapterid=111614 . There's no English version of the statement avaliable and the test case presents input data in a different way, so don't mind the souce.


问:
sbt-assembly multimodule project?
My project is separated on multiple parts:
 * core project
 * utils (as example) project

Both of them have some unit-tests, and "core project" relies on code in "utils" project by "dependsOn" mechanism of sbt.

I am using sbt-assembly plugin for building "uber-jar"/"fat-jar", but sbt assembly task does`t run test on utils project - which is what I am trying to achieve (I can not see any tests from "utils project" in logs)

Changing "dependsOn" to "aggregate" introduce new problem:

sbt assembly aggregate deduplicate

something similar to this issue-on-github

So my question is how to organize multimodule project which can be assembled by sbt-assembly and all of the tests are executed during assembly task?

答:
My guess is that you should have both dependsOn and aggregate relationships between your subprojects. They are not mutually exclusive, only serve different purposes.

DependsOn introduces code dependency, so if core depends on utils it means that you can reference types from utils in core.

Aggregate introduces task dependency. That means if you execute compile or test on core and it aggregates utils then the task will be executed on both subprojects.

Problems with deduplicate are another beast - it means, that there are duplicates in resources or classes when attempting to create one jar. The reasons for this may be various and you can tackle them by verifying the library dependencies in the build or creating MergeStrategy - https://github.com/sbt/sbt-assembly#merge-strategy

Title: sbt-assembly multimodule project?


问:
Python GPIO write to set GPIO power output failing
I am attempting to control the GPIO pins on a single-board computer (Vocore v2) running Open-Wrt Linux. The script attempts to control the GPIO pins via the file system. However, while the pins export flawlessly, the value (or power) of the pin is never set! Does anyone know why powerPin() never sets the power value of the GPIO pin? How can I fix this problem?

Thank you.

My Python script:

```<code> '''
This script is an introductory attempt to create a global Python GPIO control program.

The pinAction class requires several variables to be set:
[pin number]
[direction (read or write)]
[output value (if write is set)]
[read value (if read is set; updates on interval flag)]
[read update interval (if read is set, this is an integer value indicating the frequency of which pin values are read)]
'''

#Import all modules necessary for the script...
from subprocess import call
import sys

class pinAction:

    def __init__(self,pin,direction):
        #Set object properties...
        self.pin = int(pin)
        #Test direction argument...
        self.direction = "in" if direction == "in" else "out" if direction == "out" else False
        if not self.direction:
            #Incorrect argument: terminate the program...
            print "Error: pin direction must be 'in' or 'out'. Terminating program..."
            sys.exit()
        else:
            call('echo '+self.direction+' > direction',shell=True)

        #Initialize the GPIO pin through the file system...
        call("cd /sys/class/gpio && echo "+str(self.pin)+" > export",shell=True)
        print "Successfully initialized pin "+str(self.pin)+"."

    def powerPin(self, power):
        if self.direction == "out":
            print "Setting pin power output..."
            power = 0 if int(power) == 0 else 1 if int(power) == 1 else False
            if not power:
                print "Error: power argument must be an integer or string of '0' or '1'."
            else:
                call("echo "+str(power)+" > value && cat value",shell=True)
                #call("ls && echo "+str(power)+" > value",shell=True)
        else:
            print "Error: pin is not an output pin!"

x = pinAction(1,"out")
#Set pin power to be on...
x.powerPin(1)
</code>```

The script outputs the following in the terminal:

Successfully initialized pin 1.

Setting pin power output...

1

答:
The problem is that every time you invoke the call() function your current working directory is reset to the directory at which the script lies.

In your powerPin() function, update the line:

```<code>call("echo "+str(power)+" > value && cat value",shell=True)
</code>```

to be

```<code>call("cd /sys/class/gpio/gpio{0} && echo {1} > value".format(str(self.pin), str(power)))
</code>```

so that the value file is created in the directory /sys/class/gpio/gpio${x} :: where ${x} is the number of the pin

Body:
I am attempting to control the GPIO pins on a single-board computer (Vocore v2) running Open-Wrt Linux. The script attempts to control the GPIO pins via the file system. However, while the pins export flawlessly, the value (or power) of the pin is never set! Does anyone know why powerPin() never sets the power value of the GPIO pin? How can I fix this problem?

Thank you.

My Python script:

 '''
This script is an introductory attempt to create a global Python GPIO control program.

The pinAction class requires several variables to be set:
[pin number]
[direction (read or write)]
[output value (if write is set)]
[read value (if read is set; updates on interval flag)]
[read update interval (if read is set, this is an integer value indicating the frequency of which pin values are read)]
'''

#Import all modules necessary for the script...
from subprocess import call
import sys

class pinAction:

    def __init__(self,pin,direction):
        #Set object properties...
        self.pin = int(pin)
        #Test direction argument...
        self.direction = "in" if direction == "in" else "out" if direction == "out" else False
        if not self.direction:
            #Incorrect argument: terminate the program...
            print "Error: pin direction must be 'in' or 'out'. Terminating program..."
            sys.exit()
        else:
            call('echo '+self.direction+' > direction',shell=True)

        #Initialize the GPIO pin through the file system...
        call("cd /sys/class/gpio && echo "+str(self.pin)+" > export",shell=True)
        print "Successfully initialized pin "+str(self.pin)+"."

    def powerPin(self, power):
        if self.direction == "out":
            print "Setting pin power output..."
            power = 0 if int(power) == 0 else 1 if int(power) == 1 else False
            if not power:
                print "Error: power argument must be an integer or string of '0' or '1'."
            else:
                call("echo "+str(power)+" > value && cat value",shell=True)
                #call("ls && echo "+str(power)+" > value",shell=True)
        else:
            print "Error: pin is not an output pin!"

x = pinAction(1,"out")
#Set pin power to be on...
x.powerPin(1)

The script outputs the following in the terminal:

Successfully initialized pin 1.

Setting pin power output...

1

Body:
The problem is that every time you invoke the call() function your current working directory is reset to the directory at which the script lies.

In your powerPin() function, update the line:

call("echo "+str(power)+" > value && cat value",shell=True)

to be

call("cd /sys/class/gpio/gpio{0} && echo {1} > value".format(str(self.pin), str(power)))

so that the value file is created in the directory /sys/class/gpio/gpio${x} :: where ${x} is the number of the pin


问:
A-frame inspector tool has little to no functionality in Glitch
Disclaimer: I am brand new to a-frame and Stack Overflow.

I have been messing around with A-frame templates like this one:
https://a-frobot.github.io/aframe/examples/test/text/sizes.html#

When I run the inspector on the above (ctrl-alt-i) the inspector loads and I can move bits and pieces around.

Copy the code and move it to Glitch or CodePen, the script runs but when you open the inspector you cannot interact with the entities like the text, etc. Everything is static and you can only make changes  by changing the values in the side panel.

Something must be missing but I am so new to this I have no idea what it is. Any help is appreciated.

Here is the code I have been putting into Glitch and CodePen:

```<code><html>
<head>
<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<script src="https://unpkg.com/aframe-text-geometry-
    component@^0.5.0/dist/aframe-text-geometry-component.min.js"></script>
<title>Text Sizes</title>
<meta name="description" content="Text Sizes - A-Frame" />
<script src="../../../dist/aframe-master.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?
    family=Roboto%7CRoboto+Mono" media="all" />
</head>
  <body class="a-body ">
    <a-scene class="fullscreen" inspector="" keyboard-shortcuts=""
    screenshot="" vr-mode-ui=""><canvas class="a-canvas" data-aframe-
    canvas="true" width="600" height="300"></canvas>
  <a-assets>
    <a-mixin id="text" text="align: center; width: 6;
           value: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  Ut enim ad minim veniam"></a-mixin>
  </a-assets>

  <a-text mixin="text" position="-3 0 0" wrap-count="20" text=""></a-text>
  <a-text mixin="text" position="-3 2 0" wrap-count="30" text=""></a-text>
  <a-text mixin="text" position="-3 3 0" wrap-count="40" text=""></a-text>
  <a-text mixin="text" position="-3 3.5 0" wrap-count="50" text=""></a-text>
  <a-text mixin="text" position="-3 4 0" wrap-count="60" text=""></a-text>
  <a-text mixin="text" position="-3 4.5 0" wrap-count="70" text=""></a-text>
  <a-text mixin="text" position="-3 5 0" wrap-count="80" text=""></a-text>

  <a-text mixin="text" font="kelsonsans" position="3 0 0" wrap-count="20"
    text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 2 0" wrap-count="30"
    text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 3 0" wrap-count="40"
    text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 3.5 0" wrap-count="50"
      text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 4 0" wrap-count="60"
    text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 4.5 0" wrap-count="70"
    text=""></a-text>
  <a-text mixin="text" font="kelsonsans" position="3 5 0" wrap-count="80"
    text=""></a-text>

  <a-sky color="#3CF" material="" geometry=""></a-sky>
  <a-entity position="0 2 3.7">
    <a-entity camera="" look-controls="" wasd-controls="" data-aframe-
inspector-original-camera=""></a-entity>
  </a-entity>
</a-scene>

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

答:
Don't add the canvas manually, a-frame does it for you. And apparently it gets buggy once you put it inside the scene element.

Check it out working properly: https://like-mistake.glitch.me/

Body:
Disclaimer: I am brand new to a-frame and Stack Overflow.

I have been messing around with A-frame templates like this one:
https://a-frobot.github.io/aframe/examples/test/text/sizes.html#

When I run the inspector on the above (ctrl-alt-i) the inspector loads and I can move bits and pieces around.

Copy the code and move it to Glitch or CodePen, the script runs but when you open the inspector you cannot interact with the entities like the text, etc. Everything is static and you can only make changes  by changing the values in the side panel.

Something must be missing but I am so new to this I have no idea what it is. Any help is appreciated.

Here is the code I have been putting into Glitch and CodePen:

<title>Text Sizes</title>
<meta name="description" content="Text Sizes - A-Frame" />

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?
    family=Roboto%7CRoboto+Mono" media="all" />

    <canvas class="a-canvas" data-aframe-
    canvas="true" width="600" height="300"></canvas>


问:
How to delete a word from an array in swift?
I have the following variable:

```<code>var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
</code>```

For any of those fruits I have another variable: apple = 1 or 0, appricot = 1 or 0 ...

My question is how to make, for example, the word "Apple" be in the list just if apple == 1? and if apple == 0 my list would be:

```<code>var fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
</code>```

答:
If I understand your question you want you fruits array to be Apple if apple == 1 or the array of fruits without Apple. You can use the code below. If I didn't understand the question and this is not what you want to reach, please post more code and be more explicit.

```<code> var fruits : [String] = []

        if apple == 0 {
         fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
        } else {
        fruits = ["Apple"]
        }
</code>```

Later edit:

Alright so I understand your question better. You want to build an array of fruits, if the variable for fruit is 1, you want it in array.

To begin with, you must use a Bool type of variable instead of Int.

You can use 2 arrays, one with Bool and your fruits variable. Match their indexes, for example fruitsIncluded[0] will match for fruits[0] which is "Apple" in your case. Then create a final array of fruits (finalArrayOfFruits) where you have the fruits that are true

```<code>var fruits = [ "Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruitsIncluded = [true, false, false, true, false, true, true, false]

var finalArrayOfFruits : [String] = []

for i in 0..<fruits.count {
if fruitsIncluded[i] {
finalArrayOfFruits.append(fruits[i])
}
}
</code>```

Body:
I have the following variable:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

For any of those fruits I have another variable: apple = 1 or 0, appricot = 1 or 0 ...

My question is how to make, for example, the word "Apple" be in the list just if apple == 1? and if apple == 0 my list would be:

var fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

Body:
If I understand your question you want you fruits array to be Apple if apple == 1 or the array of fruits without Apple. You can use the code below. If I didn't understand the question and this is not what you want to reach, please post more code and be more explicit.

 var fruits : [String] = []

        if apple == 0 {
         fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
        } else {
        fruits = ["Apple"]
        }

Later edit:

Alright so I understand your question better. You want to build an array of fruits, if the variable for fruit is 1, you want it in array.

To begin with, you must use a Bool type of variable instead of Int.

You can use 2 arrays, one with Bool and your fruits variable. Match their indexes, for example fruitsIncluded[0] will match for fruits[0] which is "Apple" in your case. Then create a final array of fruits (finalArrayOfFruits) where you have the fruits that are true

var fruits = [ "Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruitsIncluded = [true, false, false, true, false, true, true, false]

var finalArrayOfFruits : [String] = []

for i in 0..<fruits.count {
if fruitsIncluded[i] {
finalArrayOfFruits.append(fruits[i])
}
}


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答: Typically what you have is try, catch, finally.  In that case, it's advantageous to use the standard SUN approach because you can capture any errors that occured in acquireStream() inside of the try, catch.

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.


问:
Angular Material DatePicker Calendar Shows Behind Angular Modal
I have the following simple code:

```<code>                <md-content>
                <md-datepicker ng-model="startDate" md-placeholder="Enter date">
                </md-datepicker>
                </md-content>
</code>```

It populates fine, but when you click on it, the calendar I can see pops up in the shadow behind angular modal window.

*I'm using this datepicker:
https://material.angularjs.org/latest/demo/datepicker

答:
The accepted answer is outdated. For @angular/material 5.0.0-rc0 have used with success:

```<code>.cdk-overlay-container{ z-index: 1200 !important; }
</code>```

https://stackoverflow.com/a/47274694/1225421

Body:
I have the following simple code:

                <md-content>
                <md-datepicker ng-model="startDate" md-placeholder="Enter date">
                </md-datepicker>
                </md-content>

It populates fine, but when you click on it, the calendar I can see pops up in the shadow behind angular modal window.

*I'm using this datepicker:
https://material.angularjs.org/latest/demo/datepicker

Body:
The accepted answer is outdated. For @angular/material 5.0.0-rc0 have used with success:

.cdk-overlay-container{ z-index: 1200 !important; }

https://stackoverflow.com/a/47274694/1225421


问:
jQuery call function outside of defined plugin
Hey all I have the following jQuery code that I am using for a tooltip type of thing:

```<code>$(function () {
    /* popModal */
    $('#pop-overlay').on('click', function () {
        popModalClose();
    });

    (function ($) {
        $.fn.popModal = function (method) {
            var elem                    = $(this),
            [ect,......etc...]
        function popModalClose() {
            elemObj = $('div[' + elemData + ']');
            elem.removeAttr(elemData + '_id');
            $('[data-item-id="' + elem.attr('data-item-id') + '"]').css({ 'z-index': '50' });
            $('#currentUsers').select3({ showDropdown: true });

            if (elemObj.length) {
                reverseEffect();
                $('.' + elemClass + '_source').replaceWith($('.' + elemClass + '_content').children());
                elemObj.remove();
                $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open');
                $('#pop-overlay').clearQueue().stop().fadeOut('slow');
                clickedAlready = false;
            }
        }
        [ect,......etc...]
     };
   })(jQuery);
});
</code>```

What I am wanting to do is call the popModalClose when I click on the overlay that's called pop-overlay.

Currently, using the code above, it gives me an error that it can not find the function popModalClose().

Ive tried:

```<code>$.fn.popModal.popModalClose();
$.fn.popModalClose();
$popModal.popModalClose();
$popModalClose();
$.popModal.popModalClose();
</code>```

答:
The plugin has a hide method that calls popModalClose:

```<code>$('html').popModal("hide");
</code>```

Body:
Hey all I have the following jQuery code that I am using for a tooltip type of thing:

$(function () {
    /* popModal */
    $('#pop-overlay').on('click', function () {
        popModalClose();
    });

    (function ($) {
        $.fn.popModal = function (method) {
            var elem                    = $(this),
            [ect,......etc...]
        function popModalClose() {
            elemObj = $('div[' + elemData + ']');
            elem.removeAttr(elemData + '_id');
            $('[data-item-id="' + elem.attr('data-item-id') + '"]').css({ 'z-index': '50' });
            $('#currentUsers').select3({ showDropdown: true });

            if (elemObj.length) {
                reverseEffect();
                $('.' + elemClass + '_source').replaceWith($('.' + elemClass + '_content').children());
                elemObj.remove();
                $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open');
                $('#pop-overlay').clearQueue().stop().fadeOut('slow');
                clickedAlready = false;
            }
        }
        [ect,......etc...]
     };
   })(jQuery);
});

What I am wanting to do is call the popModalClose when I click on the overlay that's called pop-overlay.

Currently, using the code above, it gives me an error that it can not find the function popModalClose().

Ive tried:

$.fn.popModal.popModalClose();
$.fn.popModalClose();
$popModal.popModalClose();
$popModalClose();
$.popModal.popModalClose();

Body:
The plugin has a hide method that calls popModalClose:

$('html').popModal("hide");


问:
Fading in and Fading Out in AngularsJs?
i am new in Angulars, i am using the 1.6.5 version ..

i want my element to fadeIn on click not just showing up, and fading out on click instead of just being hidden, here is my code HTML :

```<code><ul>
            <li class="try" ng-if="bool"><label>email</label> : taoufiq.benallah@gmail.com</li>
            <li ng-click="bool=false"><label>téléphone</label> : +2126-13-85-98-34 </li>
            <li ng-click="bool=true"><label>website</label> : oujda.ma.taoufiq.com</li>
</ul>
</code>```

And here is my CSS File :

```<code>.try.ng-enter {
transition: 2s all;
opacity: 1;
}

.try.ng-enter.ng-enter-active {
transition: 2s all;
opacity: 1;
 }

.try.ng-leave {
transition: 2s all;
opacity : 1;
 }
.try.ng-leave.ng-leave-active {
transition: 2s all;
opacity: 1;
 }
</code>```

The problem i am having is that my element doesnt appear in 2s but immediatly ..
Thank for any help.

答:
You can also use ngAnimate which is the Angular way:

var app = angular.module('taskApp', ['ngAnimate']);

app.controller('taskCtrl', function($scope) {
  $scope.tasks = [
    { title: 'Go to the Zoo'},
    { title: 'Take a Nap'},
    { title: 'Start Learning AngularJS'},
    { title: 'Meet Susan at the Gym'}
  ];

  $scope.addtask = function() {
    $scope.tasks.push($scope.task);
    $scope.task = {};
  };

  $scope.removeItem = function(index) {
    $scope.tasks.splice(index, 1);
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Lato';
  margin: 10px auto;
  max-width: 800px;
}

ul {
  padding: 0;
  margin-top: 40px;
  margin-left: 10px;
  font-size: 1.1em;
  position: relative;
}

form {
  margin-left: 10px;
}

ul li {
  list-style: none;
  margin: 15px auto;
  position: relative;
}

h1 {
  margin: 10px;
  text-align: center;
}

h2 {
  margin: 10px;
}

p {
  margin-left: 10px;
}

form {
  margin-top: 50px;
}

input {
  border: none;
  border-bottom: 1px solid orange;
  padding: 4px 10px;
  outline: none;
}

button {
  border: none;
  background: cornflowerblue;
  color: white;
  padding: 5px 12px;
  margin-left: 20px;
  border-radius: 4px;
}

.done {
  font-size: 0.7em;
  font-weight: bold;
  background: black;
  color: white;
  padding: 1px 5px;
  position: relative;
  top: -3px;
  border-radius: 2px;
  margin-right: 10px;
  cursor: pointer;
}

.done:hover {
  background: rgb(200, 0, 0);
}

@keyframes added {
  from {
    opacity: 0;
    top: -500px;
  }
  to {
    opacity: 1;
    top: 0px;
  }
}

@keyframes deleted {
  from {
    top: 0;
    opacity: 1;
  }
  to {
    top: 200px;
    opacity: 0;
  }
}

.task-item.ng-enter {
  animation: 0.25s linear added;
}

.task-item.ng-leave {
  animation: 0.25s linear deleted;
}</code>```

A Random List of Tasks

    <form ng-submit="addtask()">
      <input type="text" ng-model="task.title">
      <button type="submit">Add Task</button>

    </form>

        X
        {{task.title}}

```

Title: Fading in and Fading Out in AngularsJs?

Body:
i am new in Angulars, i am using the 1.6.5 version ..

i want my element to fadeIn on click not just showing up, and fading out on click instead of just being hidden, here is my code HTML :

email : taoufiq.benallah@gmail.com

téléphone : +2126-13-85-98-34

website : oujda.ma.taoufiq.com

And here is my CSS File :

.try.ng-enter {
transition: 2s all;
opacity: 1;
}

.try.ng-enter.ng-enter-active {
transition: 2s all;
opacity: 1;
 }

.try.ng-leave {
transition: 2s all;
opacity : 1;
 }
.try.ng-leave.ng-leave-active {
transition: 2s all;
opacity: 1;
 }

The problem i am having is that my element doesnt appear in 2s but immediatly ..
Thank for any help.

Body:
You can also use ngAnimate which is the Angular way:

var app = angular.module('taskApp', ['ngAnimate']);

app.controller('taskCtrl', function($scope) {
  $scope.tasks = [
    { title: 'Go to the Zoo'},
    { title: 'Take a Nap'},
    { title: 'Start Learning AngularJS'},
    { title: 'Meet Susan at the Gym'}
  ];

  $scope.addtask = function() {
    $scope.tasks.push($scope.task);
    $scope.task = {};
  };

  $scope.removeItem = function(index) {
    $scope.tasks.splice(index, 1);
  };
});

body {
  font-family: 'Lato';
  margin: 10px auto;
  max-width: 800px;
}

ul {
  padding: 0;
  margin-top: 40px;
  margin-left: 10px;
  font-size: 1.1em;
  position: relative;
}

form {
  margin-left: 10px;
}

ul li {
  list-style: none;
  margin: 15px auto;
  position: relative;
}

h1 {
  margin: 10px;
  text-align: center;
}

h2 {
  margin: 10px;
}

p {
  margin-left: 10px;
}

form {
  margin-top: 50px;
}

input {
  border: none;
  border-bottom: 1px solid orange;
  padding: 4px 10px;
  outline: none;
}

button {
  border: none;
  background: cornflowerblue;
  color: white;
  padding: 5px 12px;
  margin-left: 20px;
  border-radius: 4px;
}

.done {
  font-size: 0.7em;
  font-weight: bold;
  background: black;
  color: white;
  padding: 1px 5px;
  position: relative;
  top: -3px;
  border-radius: 2px;
  margin-right: 10px;
  cursor: pointer;
}

.done:hover {
  background: rgb(200, 0, 0);
}

@keyframes added {
  from {
    opacity: 0;
    top: -500px;
  }
  to {
    opacity: 1;
    top: 0px;
  }
}

@keyframes deleted {
  from {
    top: 0;
    opacity: 1;
  }
  to {
    top: 200px;
    opacity: 0;
  }
}

.task-item.ng-enter {
  animation: 0.25s linear added;
}

.task-item.ng-leave {
  animation: 0.25s linear deleted;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-animate.js"></script>

<body ng-app="taskApp">
  <h2>A Random List of Tasks</h2>
  <div ng-controller="taskCtrl">
    <form ng-submit="addtask()">
      <input type="text" ng-model="task.title">
      <button type="submit">Add Task</button>
      <br>
    </form>
    <ul>
      <li class="task-item" ng-repeat="task in tasks">
        <span class="done" ng-click="removeItem($index)">X</span>
        <span>{{task.title}}</span>
      </li>
    </ul>
  </div>
</body>


问:
Selectively deleting large amounts data from Sybase table
Using Sybase ASE 15 for this - I have about a large amount of rows (up to 10 mil) to delete from a table on a regular basis, but I want to keep a selection of the latest added data to the table, so that rules out using truncate directly on the table.

```<code>delete from master_table where...
</code>```

Using the above delete is very slow, so my strategy is to move the data I want to keep into a temp table, truncate the master table and move the data back in again from the temp table i.e.

```<code>1) select * into #temp_table from master_table where date_updated > dateadd(mi, -15, getdate()) and node_type != 'X'
2) truncate table master_table
3) insert into master_table select * from #temp_table
</code>```

This is almost good enough - 1 & 2 have great performance, but the insert back into the master is too slow.

So my question really boils down to whether there a quick way of doing either of:

```<code>delete from master_table where...
insert into xyz select * from...
</code>```

Or I'm open to alternative approaches!

答:
Copying out of the master_table (into temp_table) is fast, but copying those rows back to the master_table is slow. So, you have indexes, constraints and triggers on the master_table. You may need to look at those to see if they are really needed for a table that is used in bulk inserts and deletes "on a regular basis", and find alternatives based on your business need.

Below solution assumes master_table does not have any dependencies or constraints. Since you are doing this "on a regular basis", and you delete most of the master_table rows anyway, it will be faster to use a permanent temp_table.

```<code>-- Create the copy table, for the first run
-- if not exists
create table master_table_copy         -- This is your permanent temp_table
as select * from master_table where 1=2

-- Copy rows you want to keep
insert into master_table_copy
select * from master_table
where date_updated > dateadd(mi, -15, getdate())
and node_type != 'X'

truncate table master_table

-- Rename the tables
exec sp_rename 'master_table', 'master_table_orig'
exec sp_rename 'master_table_copy', 'master_table'
exec sp_rename 'master_table_orig', 'master_table_copy'   -- use for next time
</code>```

Body:
Using Sybase ASE 15 for this - I have about a large amount of rows (up to 10 mil) to delete from a table on a regular basis, but I want to keep a selection of the latest added data to the table, so that rules out using truncate directly on the table.

delete from master_table where...

Using the above delete is very slow, so my strategy is to move the data I want to keep into a temp table, truncate the master table and move the data back in again from the temp table i.e.

1) select * into #temp_table from master_table where date_updated > dateadd(mi, -15, getdate()) and node_type != 'X'
2) truncate table master_table
3) insert into master_table select * from #temp_table

This is almost good enough - 1 & 2 have great performance, but the insert back into the master is too slow.

So my question really boils down to whether there a quick way of doing either of:

delete from master_table where...
insert into xyz select * from...

Or I'm open to alternative approaches!

Body:
Copying out of the master_table (into temp_table) is fast, but copying those rows back to the master_table is slow. So, you have indexes, constraints and triggers on the master_table. You may need to look at those to see if they are really needed for a table that is used in bulk inserts and deletes "on a regular basis", and find alternatives based on your business need.

Below solution assumes master_table does not have any dependencies or constraints. Since you are doing this "on a regular basis", and you delete most of the master_table rows anyway, it will be faster to use a permanent temp_table.

-- Create the copy table, for the first run
-- if not exists
create table master_table_copy         -- This is your permanent temp_table
as select * from master_table where 1=2

-- Copy rows you want to keep
insert into master_table_copy
select * from master_table
where date_updated > dateadd(mi, -15, getdate())
and node_type != 'X'

truncate table master_table

-- Rename the tables
exec sp_rename 'master_table', 'master_table_orig'
exec sp_rename 'master_table_copy', 'master_table'
exec sp_rename 'master_table_orig', 'master_table_copy'   -- use for next time


问:
Multithread wrapper
In my program there is lot of loops that can be easily rewritten into multithread. Basically for each function which should be multithreadd I am writing following function:

```<code>void func_to_threaded(int i_from, int i_to, int num_th, ...other_parameters)
{
    int i_min = i_from;
    int i_max = i_to;
    int i_inc = i_max / num_th;
    i_max = i_max % num_th + i_inc;
    thread* th_dens = new thread[num_th];
    for (int i = 0; i < num_th; i++)
    {
        th_dens[i] = thread(func_one_thread, i_min, i_max, ...other_parameters);
        i_min = i_max;
        i_max += i_inc;
    }
    for (int i = 0; i < num_th; i++) th_dens[i].join();
    delete[] th_dens;
}
</code>```

Is there a way to rewrite this to be generic for every function of form

```<code>void func_one_thread(int i_min, int i_max, ...other_parameters)
</code>```

答:
It`s been a while since I asked this question and I moved a while back from boost threadpool to much more elegant and simple OpenMP as originally suggested Mark Setchell. So my code now looks very simple</p>

```<code>omp_set_num_threads(num_thread);

#pragma omp parallel for private(private_params)
for(int i = i_min; i < i_max; i++){
    some_func(parameters);
}
</code>```

Title: Multithread wrapper

Body:
In my program there is lot of loops that can be easily rewritten into multithread. Basically for each function which should be multithreadd I am writing following function:

void func_to_threaded(int i_from, int i_to, int num_th, ...other_parameters)
{
    int i_min = i_from;
    int i_max = i_to;
    int i_inc = i_max / num_th;
    i_max = i_max % num_th + i_inc;
    thread* th_dens = new thread[num_th];
    for (int i = 0; i < num_th; i++)
    {
        th_dens[i] = thread(func_one_thread, i_min, i_max, ...other_parameters);
        i_min = i_max;
        i_max += i_inc;
    }
    for (int i = 0; i < num_th; i++) th_dens[i].join();
    delete[] th_dens;
}

Is there a way to rewrite this to be generic for every function of form

void func_one_thread(int i_min, int i_max, ...other_parameters)

Body:
It`s been a while since I asked this question and I moved a while back from boost threadpool to much more elegant and simple OpenMP as originally suggested Mark Setchell. So my code now looks very simple

omp_set_num_threads(num_thread);

#pragma omp parallel for private(private_params)
for(int i = i_min; i < i_max; i++){
    some_func(parameters);
}


问:
Pull images and file owner through PowerShell to ImageMagick 'Montage'
I am trying to build a PowerShell script that will pull jpgs from particular directories recursively and run them through ImageMagick montage to create a Contact Sheet with the filenames as the labels. As of now, my $filename code is broken, as it only provides the last file's name and labels for all the images with the same filename.

Currently I have:

```<code>foreach ($dailyPhotoBay in $dailyServerPath)
{
$dailyImage = Get-ChildItem -Path $dailyPhotoBay -Include *.jpg -Recurse | Where-Object {$_.PSParentPath -like "*Output*"}

foreach ($image in $dailyImage)
{
    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($dailyImage)
    }
    echo $fileName

    montage -verbose -label $fileName -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage.FullName D:\Contact_Sheet\Sheet.jpg
}
</code>```

With this code all images are pulled and the contact sheet looks correct, except all the images are labeled the same - the name of the very last image.

As always, any help is appreciated.

Thanks!

答:
In ImageMagick, use %f to show the filename with suffix in montage or %t to show the filename (without suffix). ImageMagick should strip the paths. So create a variable $filenames that contains a list of files with different names.suffix with or without the paths.

For example:

```<code>convert logo: /Users/fred/desktop/logo.png
</code>```

To get the filename.suffx:

```<code>montage -label "%f" /Users/fred/desktop/logo.png montage1.png
</code>```

Or to get just the filename without suffix

```<code>montage -label "%t" /Users/fred/desktop/logo.png montage2.png
</code>```

So for your montage do the following if you want the filename with suffix to show:

```<code>montage -verbose -label "%f" -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage D:\Contact_Sheet\Sheet.jpg
</code>```

or do the following if you want the filename without suffix:

```<code>montage -verbose -label "%t" -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage D:\Contact_Sheet\Sheet.jpg
</code>```

Sorry I do not know PowerShell. So I cannot tell you how to get the list of filenames from your directory.

See
http://www.imagemagick.org/script/escape.php
http://www.imagemagick.org/Usage/montage/#label

Body:
I am trying to build a PowerShell script that will pull jpgs from particular directories recursively and run them through ImageMagick montage to create a Contact Sheet with the filenames as the labels. As of now, my $filename code is broken, as it only provides the last file's name and labels for all the images with the same filename.

Currently I have:

foreach ($dailyPhotoBay in $dailyServerPath)
{
$dailyImage = Get-ChildItem -Path $dailyPhotoBay -Include *.jpg -Recurse | Where-Object {$_.PSParentPath -like "*Output*"}

foreach ($image in $dailyImage)
{
    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($dailyImage)
    }
    echo $fileName

    montage -verbose -label $fileName -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage.FullName D:\Contact_Sheet\Sheet.jpg
}

With this code all images are pulled and the contact sheet looks correct, except all the images are labeled the same - the name of the very last image.

As always, any help is appreciated.

Thanks!

Body:
In ImageMagick, use %f to show the filename with suffix in montage or %t to show the filename (without suffix). ImageMagick should strip the paths. So create a variable $filenames that contains a list of files with different names.suffix with or without the paths.

For example:

convert logo: /Users/fred/desktop/logo.png

To get the filename.suffx:

montage -label "%f" /Users/fred/desktop/logo.png montage1.png

Or to get just the filename without suffix

montage -label "%t" /Users/fred/desktop/logo.png montage2.png

So for your montage do the following if you want the filename with suffix to show:

montage -verbose -label "%f" -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage D:\Contact_Sheet\Sheet.jpg

or do the following if you want the filename without suffix:

montage -verbose -label "%t" -pointsize 20 -background '#FFFFFF' -tile '5x40' -fill 'black' -define jpeg:size=600x780 -geometry 600x780+40+150 -quality 90  -auto-orient $dailyImage D:\Contact_Sheet\Sheet.jpg

Sorry I do not know PowerShell. So I cannot tell you how to get the list of filenames from your directory.

See
http://www.imagemagick.org/script/escape.php
http://www.imagemagick.org/Usage/montage/#label


问:
Create a key value pair for both the current key and value
I currently have an array of simple objects:

```<code>data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]
</code>```

...to which I'd like to transform into

```<code>newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]
</code>```

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

答:
I hope I didn't write it false on my Mobile, but here is a way:</p>

```<code>let newData = data.map(e => {
    for(let key in e) {
       return {
           name: key,
           count: e[key]
       };
    }
});
</code>```

Body:
I currently have an array of simple objects:

data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]

...to which I'd like to transform into

newData = [
    { "name": "alternative hip hop", "count": 3 },
    { "name": "escape room", "count" 4 }
]

Is this doable with a map? I've failed at figuring out how to do so with one.

lodash responses are welcome as well

Body:
I hope I didn't write it false on my Mobile, but here is a way:

let newData = data.map(e => {
    for(let key in e) {
       return {
           name: key,
           count: e[key]
       };
    }
});


问:
Difference between () and $()
What's the difference between

```<code>Write-Host (Get-Date) # just paren
</code>```

and

```<code>Write-Host $(Get-Date) # dollar-paren
</code>```

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

答:
The () helps with order of operations

The $() helps with evaluating values inside of the ()

For instance, if you're trying to find today's date in a string you could do the following:

```<code>echo "The length of Bryce is (Get-Date)"
echo "The length of Bryce is $(Get-Date)"
</code>```

You'll see that the output is different (in one it gives you literally "(Get-Date)" whereas in the other it gives you the evaluated expression of Get-Date)

You can read more about syntax operators here

Title: Difference between () and $()

Body:
What's the difference between

Write-Host (Get-Date) # just paren

and

Write-Host $(Get-Date) # dollar-paren

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

Body:
The () helps with order of operations

The $() helps with evaluating values inside of the ()

For instance, if you're trying to find today's date in a string you could do the following:

echo "The length of Bryce is (Get-Date)"
echo "The length of Bryce is $(Get-Date)"

You'll see that the output is different (in one it gives you literally "(Get-Date)" whereas in the other it gives you the evaluated expression of Get-Date)

You can read more about syntax operators here


问:
How to reference SQL Server in another resource Group
I have an application which consists of 2 web applications with a SQL database for each. The plan is to put each web application and its DB into a separate resource group. The shared SQL Server will be in its own resource group.

How can I reference the shared SQL Server in the Azure Resource Manager template of a web application?

I already tried the following:

```<code>    {
      "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": { },
      "variables": { },
      "resources": [
        {
          "name": "Microsoft.Sql/servers/sqlserver-dev/databases/app1db",
          "type": "Microsoft.Sql/servers/databases",
          "location": "[resourceGroup().location]",
          "apiVersion": "2014-04-01-preview",
          "dependsOn": [ ],
          "properties": {
            "collation": "SQL_Latin1_General_CP1_CI_AS",
            "edition": "Basic",
            "maxSizeBytes": "1073741824",
            "requestedServiceObjectiveName": "Basic"
           }
        }
      ]
    }
</code>```

But this approach gives me the error:

```<code>Deployment template validation failed: 'The template resource 'Microsoft.Sql/servers/sqlserver-dev/databases/app1db' for type 'Microsoft.Sql/servers/databases' at line '1' and column '202' has incorrect segment lengths. A nested resource type must have identical number of segments as its resource name. A root resource type must have segment length one greater than its resource name. Please see https://aka.ms/arm-template/#resources for usage details.'.
</code>```

When I use the resourceId of the SQL server:

```<code>/subscriptions/{GUID}/resourceGroups/sql-server-group/providers/Microsoft.Sql/servers/sqlserver-dev/databases/app1db
</code>```

I get the same error.

Any ideas how to establish the cross-resource-group link?

答: You cannot assign an Azure SQL server and its databases to different resource groups.</p>

Body:
I have an application which consists of 2 web applications with a SQL database for each. The plan is to put each web application and its DB into a separate resource group. The shared SQL Server will be in its own resource group.

How can I reference the shared SQL Server in the Azure Resource Manager template of a web application?

I already tried the following:

    {
      "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": { },
      "variables": { },
      "resources": [
        {
          "name": "Microsoft.Sql/servers/sqlserver-dev/databases/app1db",
          "type": "Microsoft.Sql/servers/databases",
          "location": "[resourceGroup().location]",
          "apiVersion": "2014-04-01-preview",
          "dependsOn": [ ],
          "properties": {
            "collation": "SQL_Latin1_General_CP1_CI_AS",
            "edition": "Basic",
            "maxSizeBytes": "1073741824",
            "requestedServiceObjectiveName": "Basic"
           }
        }
      ]
    }

But this approach gives me the error:

Deployment template validation failed: 'The template resource 'Microsoft.Sql/servers/sqlserver-dev/databases/app1db' for type 'Microsoft.Sql/servers/databases' at line '1' and column '202' has incorrect segment lengths. A nested resource type must have identical number of segments as its resource name. A root resource type must have segment length one greater than its resource name. Please see https://aka.ms/arm-template/#resources for usage details.'.

When I use the resourceId of the SQL server:

/subscriptions/{GUID}/resourceGroups/sql-server-group/providers/Microsoft.Sql/servers/sqlserver-dev/databases/app1db

I get the same error.

Any ideas how to establish the cross-resource-group link?