问:
fill color svg created with PhotoShop
I got this icon that was created in photoshop and saved in svg format.

How can I change the color fill?

-- EDIT --

I made this JS bin: https://jsbin.com/kazujoq/

SO seems to cut out this code: xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC".

```<code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65">
  <metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""/>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?></metadata>
<image id="Vector_Smart_Object" data-name="Vector Smart Object" x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC"/>
</svg>
</code>```

Title: fill color svg created with PhotoShop

Body:
I got this icon that was created in photoshop and saved in svg format.

How can I change the color fill?

-- EDIT --

I made this JS bin: https://jsbin.com/kazujoq/

SO seems to cut out this code: xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC".

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65">
  <metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""/>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?></metadata>
<image id="Vector_Smart_Object" data-name="Vector Smart Object" x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC"/>
</svg>

Body:
As others have said, if you use Illustrator to export the SVG code can then have control over its style. For instance, using fill to alter the color.

Here's an example in JSFiddle - https://jsfiddle.net/ks1k2us6/2/

HTML -

<div class="wrapper">
  <div class="icon">

    <?xml version="1.0" encoding="utf-8"?>
      <!-- Generator: Adobe Illustrator 16.0.4, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
      <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
      <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="80px" height="70px" viewBox="0 0 1190.549 841.891" enable-background="new 0 0 1190.549 841.891" xml:space="preserve">
        <g>
          <g>
            <path d="M356.739,473.29c-38.684,0-70.158,31.473-70.158,70.158c0,38.685,31.473,70.158,70.158,70.158
            c38.685,0,70.158-31.473,70.158-70.158C426.897,504.764,395.425,473.29,356.739,473.29z M356.739,585.543
            c-23.208,0-42.095-18.887-42.095-42.095s18.887-42.095,42.095-42.095s42.095,18.887,42.095,42.095
            S379.947,585.543,356.739,585.543z" />
          </g>
        </g>
        <g>
          <g>
            <path d="M1002.189,473.29v-84.188c0-6.033-3.859-11.408-9.598-13.316l-79.166-26.393
            c-29.816-50.498-70.803-98.557-161.376-114.426c-0.168-0.028-0.337-0.056-0.505-0.084
            c-167.271-23.124-292.852,14.606-373.477,112.182c-60.013,0.87-121.275,13.414-157.308,36.482
            c-18.661,11.954-29.732,32.763-30.771,54.905l-1.628,34.84c-7.744,0-14.031,6.286-14.031,14.031v56.125
            c0,7.745,6.287,14.031,14.031,14.031h56.126c7.787,0,14.018-6.398,14.03-14.186c0-0.071,0.016-0.14,0.016-0.226
            c0.21-54.063,44.087-97.842,98.206-97.842c54.246,0,98.22,43.975,98.22,98.22c-1.009,8.518,5.711,14.031,14.031,14.031h252.567
            c7.787,0,14.018-6.397,14.03-14.186c0-0.07,0.014-0.14,0.014-0.226c0.21-54.063,44.087-97.842,98.207-97.842
            c54.245,0,98.22,43.975,98.22,98.221c-1.01,8.518,5.711,14.03,14.031,14.03h56.125c7.744,0,14.031-6.286,14.031-14.03v-56.126
            C1016.22,479.576,1009.934,473.29,1002.189,473.29z M623.338,339.992c0,3.872-3.143,7.017-7.017,7.017H433.337
            c-6.481,0-9.429-7.971-4.645-12.334c48.689-44.382,110.609-69.766,186.914-76.514c4.11-0.365,7.731,2.946,7.731,7.072V339.992z
             M791.912,340.062c-0.043,3.844-3.172,6.945-7.017,6.945H658.416c-3.872,0-7.016-3.143-7.016-7.017v-76.612
            c0-3.887,3.101-7.085,6.973-7.085c27.979-0.028,57.586,2.006,89.059,6.357c14.986,2.638,28.343,6.258,40.494,10.706
            c2.792,1.024,4.574,3.733,4.547,6.708L791.912,340.062z M865.143,347.007h-38.151c-3.9,0-7.057-3.186-7.016-7.086l0.364-38.024
            c0.057-5.794,6.665-8.938,11.338-5.515c15.169,11.084,27.782,24.289,39.021,39.275
            C874.206,340.327,870.979,347.007,865.143,347.007z" />
          </g>
        </g>
        <g>
          <g>
            <path d="M833.811,473.29c-38.685,0-70.158,31.473-70.158,70.158c0,38.685,31.473,70.158,70.158,70.158
            c38.684,0,70.158-31.473,70.158-70.158C903.967,504.764,872.494,473.29,833.811,473.29z M833.811,585.543
            c-23.208,0-42.095-18.887-42.095-42.095s18.887-42.095,42.095-42.095s42.095,18.887,42.095,42.095
            S857.019,585.543,833.811,585.543z" />
          </g>
        </g>
      </svg>

  </div>
  <h1>Cars</h1>
</div>

CSS -

.wrapper {
  display: flex;
}

svg {
  fill: green;
}


来源: stackexchange

问:
React.js : Proxy that I set in package.json does not work in made by webpack
```<code>"proxy": {
  "/auth/google": {
    "target": "http://localhost:5001"
  },
  "/api/user": {
    "target": "http://localhost:5001"
  }
},
</code>```

答:
Solved the problem , I should have set proxy in webpack.config.js file</p>

```<code>devServer: {
 historyApiFallback:true,
 proxy:{
        "/api/user":"http://localhost:5001"
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Solved the problem , I should have set proxy in webpack.config.js file

devServer: {
 historyApiFallback:true,
 proxy:{
        "/api/user":"http://localhost:5001"
    }
}


问:
Getting a fatal error in cuda using visual studio 2008, code, logs, attached
I'm trying to write a cuda program for my school project. There seems to an error when I try to debug the project(cuda works fine, as I've run the examples and some of my previous code works fine too). I get a fatal error and the degugger points me to dgbhook.c and exits.
Here is my code, am I doing something really stupid? Screen shots and code attached here(code is a pastie, linked at the end)

Code attached

答:
Before you even get to CUDA code you have the following:

```<code>#define N 15
//...
int main( void ) {
    float a[N], c[N];
    int i,m=3,n=18;
    //...
    for(i=m;i<=m+n-1;i++)
        a[i] = 0;
</code>```

So you're writing up to a[20] and b[20] which seems like a likely source of problems...

You should make sure you're building with debug symbols then step into the code to track down the source of a problem like this.

ContentLicense: CC BY-SA 2.5

Body:
Before you even get to CUDA code you have the following:

#define N 15
//...
int main( void ) {
    float a[N], c[N];
    int i,m=3,n=18;
    //...
    for(i=m;i<=m+n-1;i++)
        a[i] = 0;

So you're writing up to a[20] and b[20] which seems like a likely source of problems...

You should make sure you're building with debug symbols then step into the code to track down the source of a problem like this.


问:
multi-user cluster: IBM Platform LSF: user changing priority of jobs
I am user of a multi-user cluster that uses IBM Platform LSF (on Linux). I would like to change the priority of my jobs with respect to my same jobs (not the absolute priority of the jobs in the queue).

An example: I have launched 500 jobs in the queues that will take 4 days to complete, and later I would like submit another job that I would like to run before the 500 jobs that I have already submitted.

答:
Couple of ways I can think of here:

Use user assigned priority on your job (-sp option) when you submit it with bsub, a higher number means more important.  Some notes:

This only works if your administrator has defined MAX_USER_PRIORITY in configuration (I can't for the life of me remember if this is set out of the box). To check if it's enabled run bparams -a | grep MAX_USER_PRIORITY, if it returns something you're good to go.

By default jobs have a priority of $MAX_USER_PRIORITY / 2, so if MAX_USER_PRIORITY = 100 and you've submitted 500 jobs without -sp and you want to submit one job that jumps the queue, use bsub -sp with a priority greater than 50.

Another way to do it is by using btop which usually works out of the box.  Basically you submit your job normally, then use btop <jobid> to move a particular job to the front of the line relative to your other jobs.

Some links for you:

bsub -sp documentation: https://www.ibm.com/support/knowledgecenter/en/SSWRJV_10.1.0/lsf_command_ref/bsub.sp.1.html

btop documentation: https://www.ibm.com/support/knowledgecenter/en/SSWRJV_10.1.0/lsf_command_ref/btop.1.html

blog post on user-assigned priority: http://www-01.ibm.com/support/docview.wss?uid=isg3T1013109


问:
Azure Classic vs. New Portal: how do I assign a user to an API in the NEW portal?
In the almost phasing-out Azure Classic Portal one could assign users to an API application by selecting the API from AD, then go to the tab "users", select the user and then choose the menu-item "assign".

What is the equivalent action in the new Azure Portal??

答:
Using the Azure Active Directory blade:

Enterprise applications > All applications > select App > Users & Groups

https://learn.microsoft.com/en-us/azure/active-directory/active-directory-coreapps-assign-user-azure-portal


问:
How to prevent [Authorize (Roles = "xxx")] to verify in openidconnect when using webform authentification
In my login web page, I have a webform (Identity 2.0) you can use to create an account in a database or you can use Azure Active Directory to authenticate with a corporate email. (External auth)

I've put the [Authorize] attribute to decorate the Index() action in UserController. My List() action in the same controller is decorated like this : [Authorize (Roles = "Admin")]

When logged in with my webform login, if I go to /MyController/List/ I'm redirected to the Microsoft account Login page. When going to /MyController/Index I'm not redirected.

What is causing this behavior? I don't want to check in Azure when the user is logged in with webform. How can I prevent this from happening?

Here's my Startup.Auth.cs

```<code>    public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    public static readonly string Authority = aadInstance + tenantId;

    // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
    string graphResourceId = "https://graph.windows.net";

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Pour Azure
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = Authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                AuthorizationCodeReceived = (context) =>
                {
                    var code = context.Code;
                    ClientCredential credential = new ClientCredential(clientId, appKey);
                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                    Task<AuthenticationResult> result = authContext.AcquireTokenByAuthorizationCodeAsync(
                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                    return Task.FromResult(0);
                }
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication(
        //    clientId: "",
        //    clientSecret: "");
    }
}
</code>```

EDIT

Here's the controller code

```<code>using System.Web.Mvc;

namespace MyApp.Controllers
{

    public class AccueilController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult List()
        {
            return View();
        }
    }
}
</code>```

I'm logged in with Cookie Authenticatoin (email/password).

I hit the Index action, I see the content of that page inside my app.

If I hit the List() action, I'm redirected to OpenIdConnect login page.

答:
The webforms user doesn't have the Admin role, but your AD user seems to have the Admin role. You can verify this by quickly querying the AspNetUserRoles table.

Decorating an action with [Authorize(Roles="Admin")] will make it accessible only to users with the role. The default behaviour for unauthorized users (irrespective of whether the user's authentication status) is to redirect them to the login page.

Your options are:

Subclass the AuthorizeAttribute and override the default behavior.

Redirect the user somewhere else (perhaps a forbidden page with the right status code set) from the login page if he's authenticated.

As far as I know, the default redirect behavior cannot be overriden without subclassing the AuthorizeAttribute like you can in ASP.NET Core.

Body:
In my login web page, I have a webform (Identity 2.0) you can use to create an account in a database or you can use Azure Active Directory to authenticate with a corporate email. (External auth)

I've put the [Authorize] attribute to decorate the Index() action in UserController. My List() action in the same controller is decorated like this : [Authorize (Roles = "Admin")]

When logged in with my webform login, if I go to /MyController/List/ I'm redirected to the Microsoft account Login page. When going to /MyController/Index I'm not redirected.

What is causing this behavior? I don't want to check in Azure when the user is logged in with webform. How can I prevent this from happening?

Here's my Startup.Auth.cs

    public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    public static readonly string Authority = aadInstance + tenantId;

    // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
    string graphResourceId = "https://graph.windows.net";

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Pour Azure
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = Authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                AuthorizationCodeReceived = (context) =>
                {
                    var code = context.Code;
                    ClientCredential credential = new ClientCredential(clientId, appKey);
                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                    Task<AuthenticationResult> result = authContext.AcquireTokenByAuthorizationCodeAsync(
                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                    return Task.FromResult(0);
                }
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication(
        //    clientId: "",
        //    clientSecret: "");
    }
}

EDIT

Here's the controller code

using System.Web.Mvc;

namespace MyApp.Controllers
{

    public class AccueilController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult List()
        {
            return View();
        }
    }
}

I'm logged in with Cookie Authenticatoin (email/password).

I hit the Index action, I see the content of that page inside my app.

If I hit the List() action, I'm redirected to OpenIdConnect login page.


问:
How to convert json string into a dictionary with swift 3?
Im trying to covert this string into a dictionary

```<code>{
    "sender_id": 7,
    "Sender_name": Testchumthree Tester,
    "message": 42,
    "Sender_image": https://graph.facebook.com/v2.10/281359099024687/picture?type=normal,
    "timestamp": "0",
    "group_id": 50
}
</code>```

Below is what i found so far.

```<code>func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}
</code>```

But this i get an error saying the data  is not in the correct format. Any help would be much appreciated.

答:
The problem with your JSON is that strings are not properly formatted. There must be quotes around them and depending on the library "/" must also be escaped.

Try using this:

```<code>{
    "sender_id": 7,
    "Sender_name": "Testchumthree Tester",
    "message": 42,
    "Sender_image": "https:\/\/graph.facebook.com\/v2.10\/281359099024687\/picture?type=normal",
    "timestamp": "0",
    "group_id": 50
}
</code>```

Body:
Im trying to covert this string into a dictionary

{
    "sender_id": 7,
    "Sender_name": Testchumthree Tester,
    "message": 42,
    "Sender_image": https://graph.facebook.com/v2.10/281359099024687/picture?type=normal,
    "timestamp": "0",
    "group_id": 50
}

Below is what i found so far.

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

But this i get an error saying the data  is not in the correct format. Any help would be much appreciated.

Body:
The problem with your JSON is that strings are not properly formatted. There must be quotes around them and depending on the library "/" must also be escaped.

Try using this:

{
    "sender_id": 7,
    "Sender_name": "Testchumthree Tester",
    "message": 42,
    "Sender_image": "https:\/\/graph.facebook.com\/v2.10\/281359099024687\/picture?type=normal",
    "timestamp": "0",
    "group_id": 50
}


问:
In SASS, can I define property as argument in mixin?
I would like to write something like this:

```<code>$widthXl: 1000px
$widthSm: 500px
@mixin med ($prop, $xl, $sm)
  @media (max-width: $widthXl)
    &
      $prop: $xl
  @media (max-width: $widthSm)
    &
      $prop: $sm
a
  @include med(width, 600px, 300px)
b
  @include med(color, #000, #888)
</code>```

And get this:

```<code>@media (max-width: 1000px) {
  a {width: 600px}
  b {color: #000}
}
@media (max-width: 500px) {
  a {width: 300px}
  b {color: #888}
}
</code>```

But my code doesn't compile it. Is it possible?

It would be interesting to know whether someone faced the same problem.

If I remove property, code works fine. But I want to create complex solution.

答:
You can use variable "interpolation" like #{$prop}.

My code sample is in scss instead of sass, I like braces. It should compile the same.

```<code>$widthXl: 1000px;
$widthSm: 500px;

@mixin med ($prop, $xl, $sm) {
    @media (max-width: $widthXl) {
        & {
            #{$prop}: $xl;
        }
    }
    @media (max-width: $widthSm) {
        & {
            #{$prop}: $sm
        }
    }
}
body {
    @include med(color, red, blue)
}
</code>```

Some information can be found in the docs

Body:
I would like to write something like this:

$widthXl: 1000px
$widthSm: 500px
@mixin med ($prop, $xl, $sm)
  @media (max-width: $widthXl)
    &
      $prop: $xl
  @media (max-width: $widthSm)
    &
      $prop: $sm
a
  @include med(width, 600px, 300px)
b
  @include med(color, #000, #888)

And get this:

@media (max-width: 1000px) {
  a {width: 600px}
  b {color: #000}
}
@media (max-width: 500px) {
  a {width: 300px}
  b {color: #888}
}

But my code doesn't compile it. Is it possible?

It would be interesting to know whether someone faced the same problem.

If I remove property, code works fine. But I want to create complex solution.

Body:
You can use variable "interpolation" like #{$prop}.

My code sample is in scss instead of sass, I like braces. It should compile the same.

$widthXl: 1000px;
$widthSm: 500px;

@mixin med ($prop, $xl, $sm) {
    @media (max-width: $widthXl) {
        & {
            #{$prop}: $xl;
        }
    }
    @media (max-width: $widthSm) {
        & {
            #{$prop}: $sm
        }
    }
}
body {
    @include med(color, red, blue)
}

Some information can be found in the docs


问:
How to check if template argument is a callable with a given signature
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

答:
C++20 with concepts

Since few years already, we have concepts that make such checks easy. This case is straight usage of std::invocable.

#include <concepts>

struct B {
using Signature = void(int, double);

template <typename Callable>
void Register(Callable &&callable)
    requires std::invocable<Callable, int, double>
{
    callback = callable;
}

std::function<Signature> callback;
};

```
<h3>C++17</h3>
<p>In C++17 there is trait <code>std::is_invocable<Callable, Args...></code>, which does exactly what you ask for. Its advantage over <code>std::is_convertible<std::function<Signature>,...></code> is that you don't have to specify return type.</p>
<blockquote>
<p>It might sound like overkill but I had encountered problem that had to use it. Exactly my wrapper function deduced its return type from passed Callable, but I've passed templated lambda like this one <code>[](auto& x){return 2*x;}</code>, so return type of it was deduced in subcall. I couldn't convert it into <code>std::function</code> and I ended up using local implementation of <code>is_invocable</code> for C++14.</p>
</blockquote>
<h3>Backport for C++14</h3>
<p>I cannot find the to credit the original author. Anyway, the code:</p>
<pre class="lang-cpp prettyprint-override"><code>template <class F, class... Args>
struct is_invocable
{
    template <class U>
    static auto test(U* p) -> decltype((*p)(std::declval<Args>()...), void(), std::true_type());
    template <class U>
    static auto test(...) -> decltype(std::false_type());

    static constexpr bool value = decltype(test<F>(0))::value;
};
</code>```

and for your example:

struct A {
using Signature = void(int, double);

template <typename Callable>
void Register(Callable &&callable) {
    static_assert(is_invocable<Callable,int,double>::value, "not foo(int,double)");
    callback = callable;
}

std::function<Signature> callback;
};
```

Body:
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};

Body:
C++20 with concepts

Since few years already, we have concepts that make such checks easy. This case is straight usage of std::invocable.

#include <concepts>

struct B {
using Signature = void(int, double);

template <typename Callable>
void Register(Callable &&callable)
    requires std::invocable<Callable, int, double>
{
    callback = callable;
}

std::function<Signature> callback;
};

C++17

In C++17 there is trait std::is_invocable<Callable, Args...>, which does exactly what you ask for. Its advantage over std::is_convertible<std::function<Signature>,...> is that you don't have to specify return type.

It might sound like overkill but I had encountered problem that had to use it. Exactly my wrapper function deduced its return type from passed Callable, but I've passed templated lambda like this one [](auto& x){return 2*x;}, so return type of it was deduced in subcall. I couldn't convert it into std::function and I ended up using local implementation of is_invocable for C++14.

Backport for C++14

I cannot find the to credit the original author. Anyway, the code:

template <class F, class... Args>
struct is_invocable
{
    template <class U>
    static auto test(U* p) -> decltype((*p)(std::declval<Args>()...), void(), std::true_type());
    template <class U>
    static auto test(...) -> decltype(std::false_type());

    static constexpr bool value = decltype(test<F>(0))::value;
};

and for your example:

struct A {
using Signature = void(int, double);

template <typename Callable>
void Register(Callable &&callable) {
    static_assert(is_invocable<Callable,int,double>::value, "not foo(int,double)");
    callback = callable;
}

std::function<Signature> callback;
};

ContentLicense: CC BY-SA 4.0


问:
Best practices for CRUD operations on database and UI
The question I have in mind is a design choice, best practice question. A user has a user interface which contains an HTML table showcasing all the data in a MYSQL table. After viewing the information through this HTML table he is given several input fields allowing him to perform CRUD operations on this table. Should I change the content of the HTML table emulating what has been deleted using Javascript or should I return all the new content from the database and dynamically create a new table. In the second case the tradeoff is more queries to the database, but purer data. However in the first situation there is a risk that the code I will write to update this HTML table is not perfect and causes issues, however reducing query time to the database.

Consider the folowing example for a delete operation

```<code>DELETE FROM OBJECTS WHERE ID=1;
DELETE FROM SUBJECTS_OBJECTS_RELATIONSHIP WHERE ID=1;
</code>```

and several complex queries

vs in jquery

$("#object_id_1").parent("tr").remove()

As you can see I can simply delete the row where object_id is 1 using jquery without making queries to the databsae

答:
Your question is very broad, and there can be many approaches to your predicament. First I would suggest learning an MVC Framework such as Laravel Or CodeIgniter. Both have their benefits and drawbacks. For example Laravel has a steeper learning curve, but can be a great framework. It has an awesome community behind it as well. CI (codeigniter) On the other hand can be picked up fairly easily. Both provide Database Manipulation "Libraries".

Both follow MVC design patterns. And are "Backend" Frameworks. Basically these are frameworks that work with your serverside code. (PHP)

The trend these days is to pair up Backend with Frontend frameworks. So a good framework that comes to mind would be VueJS.

Laravel and VueJS work incredibly well together. You can make a restful backend and use VueJS to send requests via a framework like Axios or even jQuery.

This is a lot of information to take in, so be sure to get ready for long nights of reading up.

Body:
The question I have in mind is a design choice, best practice question. A user has a user interface which contains an HTML table showcasing all the data in a MYSQL table. After viewing the information through this HTML table he is given several input fields allowing him to perform CRUD operations on this table. Should I change the content of the HTML table emulating what has been deleted using Javascript or should I return all the new content from the database and dynamically create a new table. In the second case the tradeoff is more queries to the database, but purer data. However in the first situation there is a risk that the code I will write to update this HTML table is not perfect and causes issues, however reducing query time to the database.

Consider the folowing example for a delete operation

DELETE FROM OBJECTS WHERE ID=1;
DELETE FROM SUBJECTS_OBJECTS_RELATIONSHIP WHERE ID=1;

and several complex queries

vs in jquery

$("#object_id_1").parent("tr").remove()

As you can see I can simply delete the row where object_id is 1 using jquery without making queries to the databsae


问:
FedACHdir.txt download
We had an automated process to download FedACHDir.txt at href="https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt.

This download page now has a pop-up form appearing to inform the availability of the data in 2018 and to input information to get notified.

The download process we had was working so far (until couple of weeks back) and is not working now after this pop-up form starts appearing.

Does anyone face similar issues and any ideas/suggestion on how to overcome this?

i tried with few options like the curl script below (and wget and also java process):
curl  -s -c fcookie.txt https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt

curl -b fcookie.txt -d "agreementValue=Agree" -H "Referer:https://www.frbservices.org/EPaymentsDirectory/agreement.html" https://www.frbservices.org/EPaymentsDirectory/submitAgreement

curl -b fcookie.txt "https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt"  -o ./FedACHdir.txt

thanks,

答:
It sounds like www.frbservices.org changed their spec.  If you're accessing a tool that isn't documented as for public consumption, that can happen, and when it does you need to handle the new form.  frbservices, may have thought this through already.

If you want to write a script without contacting them, you need to know what the flow is supposed to be (were it being accessed the way they expect it, such as via a browser).

If you wget the url, what do you get?  Normally popups are javascript, and you can ignore them.  Alternatively the page may now only be the popup, and it may be javascript that is directing you elsewhere to get the file.   Basically you need a web developer to code this, hence best ask frbservices how best you should download this file.

Title: FedACHdir.txt download


问:
Updating Master / Details in MVC
I am trying to update a Master / Details relationship. At the moment my code only updates the master table but does not add anything to the details page.
I can add records to both tables fine but I want to be able to update the master and add new entries to the details at the same time.
Screenshots show the data being passed to my Controller.

```<code>    [HttpPost]
    public JsonResult saveEdit(OMR_OrderMaster order)
    {
        bool status = false;

        {
            using (PPPEntities dc = new PPPEntities())
            {
                {

                    db.Entry(order).State = EntityState.Modified;
                    db.SaveChanges();
                    status = true;
                }
            }
        }
        return new JsonResult { Data = new { status = status } };
    }
</code>```

At Present no errors are returned but just the Master tabel is being updated

```<code>namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderMaster
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public OMR_OrderMaster()
    {
        this.OMR_OrderDetails = new HashSet<OMR_OrderDetails>();
    }

    public int OrderID { get; set; }
    public string OrderNo { get; set; }
    public System.DateTime OrderDate { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OMR_OrderDetails> OMR_OrderDetails { get; set; }
}
</code>```

}

```<code>namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderDetails
{
    public int OrderDetialsID { get; set; }
    public int OrderID { get; set; }
    public decimal Rate { get; set; }
    public int Quantity { get; set; }
    public int StockID { get; set; }

    public virtual OMR_OrderMaster OMR_OrderMaster { get; set; }
    }
}
</code>```

答:
Because you are in EDMX context you have to use Attach function like :

```<code>using (PPPEntities dc = new PPPEntities())
{
     foreach(var details in order.OMR_OrderDetails)
          dc.ORM_OrderDetails.Attach(details);
     dc.Entry(order).State = EntityState.Modified;
     dc.SaveChanges();
     status = true;
 }
</code>```

Be careful in your code you are declaring a PPPEntities context but you don't use it. Your code is calling an undefined db var.

Title: Updating Master / Details in MVC

Body:
I am trying to update a Master / Details relationship. At the moment my code only updates the master table but does not add anything to the details page.
I can add records to both tables fine but I want to be able to update the master and add new entries to the details at the same time.
Screenshots show the data being passed to my Controller.

    [HttpPost]
    public JsonResult saveEdit(OMR_OrderMaster order)
    {
        bool status = false;

        {
            using (PPPEntities dc = new PPPEntities())
            {
                {

                    db.Entry(order).State = EntityState.Modified;
                    db.SaveChanges();
                    status = true;
                }
            }
        }
        return new JsonResult { Data = new { status = status } };
    }

At Present no errors are returned but just the Master tabel is being updated

namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderMaster
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public OMR_OrderMaster()
    {
        this.OMR_OrderDetails = new HashSet<OMR_OrderDetails>();
    }

    public int OrderID { get; set; }
    public string OrderNo { get; set; }
    public System.DateTime OrderDate { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OMR_OrderDetails> OMR_OrderDetails { get; set; }
}

}

namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderDetails
{
    public int OrderDetialsID { get; set; }
    public int OrderID { get; set; }
    public decimal Rate { get; set; }
    public int Quantity { get; set; }
    public int StockID { get; set; }

    public virtual OMR_OrderMaster OMR_OrderMaster { get; set; }
    }
}

Body:
Because you are in EDMX context you have to use Attach function like :

using (PPPEntities dc = new PPPEntities())
{
     foreach(var details in order.OMR_OrderDetails)
          dc.ORM_OrderDetails.Attach(details);
     dc.Entry(order).State = EntityState.Modified;
     dc.SaveChanges();
     status = true;
 }

Be careful in your code you are declaring a PPPEntities context but you don't use it. Your code is calling an undefined db var.


问:
JavaFx: Label text doesn't wrap
I have a BorderPane with Panes for left, right and center elements and HBox for top element. On the right Pane there is a Label. The Label contains some text, which doesn't wrap and therefore gets cut.

```<code>public class Main extends Application implements EventHandler<ActionEvent> {
    private static BorderPane gamePane;
    private static Pane cellsPane;
    private static HBox buttonsPane;
    private static Pane statsPane;
    private static Pane setupsPane;

    Label cellsCountLabel;

    static int  gameWidth= 700;
    static int gameHeight=600;

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Hello World");

        gamePane = new BorderPane();

        buttonsPane = new HBox(5);
        statsPane = new Pane();
        cellsPane = makeGrid(20);
        setupsPane = new Pane();

        cellsPane.setStyle("-fx-background-color:  #ffffff; -fx-border-color: black");
        buttonsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");
        statsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");
        setupsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");

        cellsPane.setMaxWidth(400);
        statsPane.setMaxWidth((gameWidth-400)/2);
        setupsPane.setMaxWidth((gameWidth-400)/2);

        createCellButton = new Button();
        deleteCellsButton = new Button();

        createCellButton.setText("Create a cell");
        deleteCellsButton.setText("Delete cells");

        ...

        buttonsPane.setSpacing(10);
        buttonsPane.setPadding(new Insets(10, 10, 10, 10));
        buttonsPane.getChildren().add(createCellButton);
        buttonsPane.getChildren().add(deleteCellsButton);

        gamePane.setTop(buttonsPane);
        gamePane.setCenter(cellsPane);

        ...

        cellsCountLabel = new Label("Cells Count: " + (cellId + 1));
        statsPane.getChildren().add(cellsCountLabel);
        gamePane.setLeft(statsPane);

        setupsPane.getChildren().add(new Label("Setups Panel1111115552222222133331111"));
        gamePane.setRight(setupsPane);

        gamePane.setMargin(statsPane, new Insets(0, 0, 0, 0));
        gamePane.setMargin(cellsPane, new Insets(0,0,0,0));
        gamePane.setMargin(setupsPane, new Insets(0,0,0,0));

        statsPane.setPrefWidth(150);
        setupsPane.setPrefWidth(150);

        cellsCountLabel.setWrapText(true);  //doesn't work

        Scene scene = new Scene(gamePane, gameWidth, gameHeight);
        primaryStage.setScene(scene);

        ...

        primaryStage.show();
}
...
}
</code>```

However, there exists space between left, center and right Panes. The space gets smaller as the content in those Panes get larger, however, when it gets too large it messes with the center Pane.

I tried using cellsCountLabel.setWrapText(true), but it didn't work.

答:
Try this

```<code>Label label = new Label("Setups Panel1111115552222222133331111");
label.setWrapText(true);
label.setMaxWidth((gameWidth-400)/2);
setupsPane.getChildren().add(label);
</code>```

Also if you go this route you may want to declare something like this

```<code>static double sidePaneWidth = (gameWidth-400)/2;
</code>```

for later use

You can also make this into a function like so if necessary

```<code>private Label newSidePaneLabel(String labelString){
    Label label = new Label(labelString);
    label.setWrapText(true);
    label.setMaxWidth(sidePaneWidth);
    return label;
}
</code>```

Title: JavaFx: Label text doesn't wrap

Body:
I have a BorderPane with Panes for left, right and center elements and HBox for top element. On the right Pane there is a Label. The Label contains some text, which doesn't wrap and therefore gets cut.

public class Main extends Application implements EventHandler<ActionEvent> {
    private static BorderPane gamePane;
    private static Pane cellsPane;
    private static HBox buttonsPane;
    private static Pane statsPane;
    private static Pane setupsPane;

    Label cellsCountLabel;

    static int  gameWidth= 700;
    static int gameHeight=600;

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Hello World");

        gamePane = new BorderPane();

        buttonsPane = new HBox(5);
        statsPane = new Pane();
        cellsPane = makeGrid(20);
        setupsPane = new Pane();

        cellsPane.setStyle("-fx-background-color:  #ffffff; -fx-border-color: black");
        buttonsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");
        statsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");
        setupsPane.setStyle("-fx-background-color:  #f2f2f2; -fx-border-color: black");

        cellsPane.setMaxWidth(400);
        statsPane.setMaxWidth((gameWidth-400)/2);
        setupsPane.setMaxWidth((gameWidth-400)/2);

        createCellButton = new Button();
        deleteCellsButton = new Button();

        createCellButton.setText("Create a cell");
        deleteCellsButton.setText("Delete cells");

        ...

        buttonsPane.setSpacing(10);
        buttonsPane.setPadding(new Insets(10, 10, 10, 10));
        buttonsPane.getChildren().add(createCellButton);
        buttonsPane.getChildren().add(deleteCellsButton);

        gamePane.setTop(buttonsPane);
        gamePane.setCenter(cellsPane);

        ...

        cellsCountLabel = new Label("Cells Count: " + (cellId + 1));
        statsPane.getChildren().add(cellsCountLabel);
        gamePane.setLeft(statsPane);

        setupsPane.getChildren().add(new Label("Setups Panel1111115552222222133331111"));
        gamePane.setRight(setupsPane);

        gamePane.setMargin(statsPane, new Insets(0, 0, 0, 0));
        gamePane.setMargin(cellsPane, new Insets(0,0,0,0));
        gamePane.setMargin(setupsPane, new Insets(0,0,0,0));

        statsPane.setPrefWidth(150);
        setupsPane.setPrefWidth(150);

        cellsCountLabel.setWrapText(true);  //doesn't work

        Scene scene = new Scene(gamePane, gameWidth, gameHeight);
        primaryStage.setScene(scene);

        ...

        primaryStage.show();
}
...
}

However, there exists space between left, center and right Panes. The space gets smaller as the content in those Panes get larger, however, when it gets too large it messes with the center Pane.

I tried using cellsCountLabel.setWrapText(true), but it didn't work.

Body:
Try this

Label label = new Label("Setups Panel1111115552222222133331111");
label.setWrapText(true);
label.setMaxWidth((gameWidth-400)/2);
setupsPane.getChildren().add(label);

Also if you go this route you may want to declare something like this

static double sidePaneWidth = (gameWidth-400)/2;

for later use

You can also make this into a function like so if necessary

private Label newSidePaneLabel(String labelString){
    Label label = new Label(labelString);
    label.setWrapText(true);
    label.setMaxWidth(sidePaneWidth);
    return label;
}


问:
AesManaged determine if password is wrong
I've been working with the AesManaged class to encrypt some data and I have everything working properly when the correct password is provided.  However, if the wrong password is supplied for decrypt, even if it's the same length, I get the error "Padding is invalid and cannot be removed".

My question is: If I supply the wrong password, will I always get this message?  If not, is there a way to tell if the data was decrypted properly without knowing what the original data was?

答:
If I supply the wrong password, will I always get this message?

No, 1 in 256 keys will result in garbage with valid PKCS#7 padding.  (Really 1/2^8 + 1/2^16 + 1/2^24 + ... + 1/2^128).  So the exception always means "the key is wrong" (assuming you somehow know everything else to be right), but not all "the key is wrong" produce the exception.

If not, is there a way to tell if the data was decrypted properly without knowing what the original data was?

If you don't consider there to be an attack vector of a chosen ciphertext padding oracle then you can solve this with an in-the-message prefix.  The odds of a 4 byte prefix aligning AND a 1+ byte padding aligning start at 1/2^40.

Or you can (as zaph pointed out) MAC the encrypted message using a different key derived from the same password.  If the MAC works out then the contents are not tampered with, and the password is correct.

Protecting the message via a MAC is the better option, though it's slightly more complex.


问:
SQL Server script to remove replication?
I have been asked to write a SQL script that can be run, which will stop replication and remove the subscriber/subscription.

Is this at all possible? Or do you have to use the GUI?

答:
If you're look to completely remove replication, including all the "bits". Or your server only has one publication and this is the one you're trying to remove.

I would recommend:

Connect to the Publisher or Distributor you want to disable in Microsoft SQL Server Management Studio, and then expand the server node.

Right-click the Replication folder, and then click Disable Publishing and Distribution.

Follow the steps in the Disable Publishing and Distribution Wizard, and instead of processing select the option to generate scripts.

This has the advantage of not only completely cleaning things up. But also removing the distribution database, which if you've ever dealt with before is known to become littered with remnants of replications past.

Full documentation can be found here.


答:
You can do either way...

If you go the 'update' method, then your server after the deletion should return a javascript call that would perform the operation in jQuery:

$("#object_id_1").parent("tr").remove()

If you go the full update way then first clear the table and then upload all the data, less efficient but also less error-prone. Personally, I would go with the 'update' method.

Title: Best practices for CRUD operations on database and UI


问:
How to create a customized colormap and use it for different ranges of data?
Let's say I have data like this:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# for reproducibility purposes
np.random.seed(0)

# generate some data
n = 30
x = np.array(range(n))

a1 = np.random.rand(n)
a2 = a1 * 100
</code>```

and I want to plot these data in two subplots, I can do (variation of this answer)

```<code>cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", [(0., '#9696ff'), (0.2, '#f0ffff'), (1.0, '#ff0000')])

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, a1, c=a1, cmap=cmap)
ax2.scatter(x, a2, c=a2, cmap=cmap)
plt.show()
</code>```

which gives

The problem I have is that it now looks like these data are identical although the values on the right are 100 times larger.

So, what I would like to have is a colormap which I can use for both plots; instead of

```<code>matplotlib.colors.LinearSegmentedColormap.from_list("", [(0., '#9696ff'), (0.2, '#f0ffff'), (1.0, '#ff0000')])
</code>```

I would like to use something like

```<code>min_a1_a2 = min(min(a1), min(a2))
max_a1_a2 = max(max(a1), max(a2))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", [(min_a1_a2, '#9696ff'), ((min_a1_a2 + max_a1_a2) / 2., '#f0ffff'), (max_a1_a2, '#ff0000')])
</code>```

but this always results in the error

ValueError: data mapping points must start with x=0. and end with x=1

when I pass it to scatter (using the same commands as above).

Is there a way to pass arbitrary (value, color) tuples to matplotlib.colors.LinearSegmentedColormap.from_list and then the resulting colormap to e.g. scatter and if so how would one do this?

答:
A matplotlib colormap maps the numerical range between 0 and 1 to a range of colors.

If the data ranges over an interval other than [0,1] (which is almost always the case of course), one would normalize to that interval first. This normalization is done internally by the ScalarMappable in use (e.g. the scatter plot in this case).

In cases where a custom normalization is needed, as when two different plots need to share a colorcoding, this can be specified when creating the ScalarMappable.

Either using vmin and vmax

```<code>plt.scatter(x,y, c=c, cmap=cmap, vmin=0, vmax=100)
</code>```

or via a Normalization instance

```<code>plt.scatter(x,y, c=c, cmap=cmap, norm=plt.Normalize(0,100))
</code>```

Body:
Let's say I have data like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# for reproducibility purposes
np.random.seed(0)

# generate some data
n = 30
x = np.array(range(n))

a1 = np.random.rand(n)
a2 = a1 * 100

and I want to plot these data in two subplots, I can do (variation of this answer)

cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", [(0., '#9696ff'), (0.2, '#f0ffff'), (1.0, '#ff0000')])

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, a1, c=a1, cmap=cmap)
ax2.scatter(x, a2, c=a2, cmap=cmap)
plt.show()

which gives

The problem I have is that it now looks like these data are identical although the values on the right are 100 times larger.

So, what I would like to have is a colormap which I can use for both plots; instead of

matplotlib.colors.LinearSegmentedColormap.from_list("", [(0., '#9696ff'), (0.2, '#f0ffff'), (1.0, '#ff0000')])

I would like to use something like

min_a1_a2 = min(min(a1), min(a2))
max_a1_a2 = max(max(a1), max(a2))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", [(min_a1_a2, '#9696ff'), ((min_a1_a2 + max_a1_a2) / 2., '#f0ffff'), (max_a1_a2, '#ff0000')])

but this always results in the error

ValueError: data mapping points must start with x=0. and end with x=1

when I pass it to scatter (using the same commands as above).

Is there a way to pass arbitrary (value, color) tuples to matplotlib.colors.LinearSegmentedColormap.from_list and then the resulting colormap to e.g. scatter and if so how would one do this?

Body:
A matplotlib colormap maps the numerical range between 0 and 1 to a range of colors.

If the data ranges over an interval other than [0,1] (which is almost always the case of course), one would normalize to that interval first. This normalization is done internally by the ScalarMappable in use (e.g. the scatter plot in this case).

In cases where a custom normalization is needed, as when two different plots need to share a colorcoding, this can be specified when creating the ScalarMappable.

Either using vmin and vmax

plt.scatter(x,y, c=c, cmap=cmap, vmin=0, vmax=100)

or via a Normalization instance

plt.scatter(x,y, c=c, cmap=cmap, norm=plt.Normalize(0,100))


问:
How to set icons for all TabBarItem
I'm new to iOS, but I will try to explain what is my problem.

So I have, Navigation controller, TabBar Controller, and in TabBar Controller I have three viewcontroller.

So in the tab bar, I have three tabbarIcon.

Programmatically I set icons for tab bar items in their view controllers, in viewdidload method. So yes I know that when I  will start my application, icons will not load because it needs to call viewdidload.
So...

How can I set icons for all tabbarItem automatically, when the application will start?

答: The tab bar items should be configured in the init or awakeFromNib' functions of your view controllers, not in viewDidLoad as the tab bar has already been displayed before this is called.

Title: How to set icons for all TabBarItem


问:
Transaction stuck in "local transactions" with status "In queue: Future" - Parity Ethereum Node
I'm reaching out for help as I've become as stuck as my transactions which are showing up in Parity TxQueueViewer under local transactions as status:

```<code>In queue: Future
</code>```

As pictured in the below screenshot as tx: 0x0e97a4c

I'm setting tx: 0x0e97a4c up with https://github.com/ethereumjs/ethereumjs-tx and sending with https://github.com/ethereum/web3.js/ as below:

```<code>var Web3 = require('web3');
var Transaction = require('ethereumjs-tx');
var data = contract.method.getData(some, data);
console.log("Data: " + data);
var gasEstimate = web3.eth.estimateGas({
    to: web3.env.SENDER_ADDRRESS,
    data: data
});
console.log("GasEstimate: " + gasEstimate);
var nonce = web3.eth.getTransactionCount(process.env.SENDER_ADDRRESS);
console.log("Transation Count: " + nonce);
var rawTx = {
    nonce: web3.toHex(nonce),
    gasPrice: web3.toHex(process.env.GAS_PRICE),
    gasLimit: web3.toHex(gasEstimate),
    to: web3.toHex(process.env.CONTRACT_ADDRESS),
    value: web3.toHex(provider.toWei('1', 'ether')),
    data: data,
    chainId: 3
};
console.log("RawTx: " + JSON.stringify(rawTx));
var tx = new Transaction(rawTx);
console.log(tx.getChainId());
tx.sign(new Buffer(process.env.KEY, 'hex'));
web3.eth.sendRawTransaction("0x".concat(tx.serialize().toString('hex')), function(error, txHash) {
    if (error) {
        console.log(error); // an error occurred
        callback(error);
    }
    else {
        callback(null,{"error":0,"tx":txHash});
    }
});
</code>```

I know the node is syncing and propagating transactions, which are subsequently mined, as transactions setup and sent from the Parity UI succeed as pictured below (which shows as mined in the image above):

As some background, I've been developing a project for Ethereum using Solidity and Javascript and utilising Truffle and Web3js. Testing against TestRPC. After some research, I selected Parity over Geth and am using the Ropsten network to run tests.

I have Parity version:

```<code>Parity/v1.6.8-beta-c396229-20170608/x86_64-macos/rustc1.17.0
</code>```

running on:

```<code>MacOS Sierra 10.12.5.
</code>```

I'm starting parity with the following:

```<code>parity --pruning fast --chain ropsten --warp --mode active --jsonrpc-interface all --jsonrpc-hosts all --allow-ips public
</code>```

What does status "In queue: Future" mean?

Is there some sort of transaction release mechanism with Parity?

Or am I not setting up the transaction correctly for this type of node?

答: I just resolved this issue by stopping the Parity process and deleting Parity's cache (~/.local/share/io.parity.ethereum/cache). This problem occurs when there is a transaction that gets "stuck" locally. Once this "stuck" transaction is in the local queue, other transactions from the same address will not be propagated until the "stuck" transaction propagates. </p>

Body:
I'm reaching out for help as I've become as stuck as my transactions which are showing up in Parity TxQueueViewer under local transactions as status:

In queue: Future

As pictured in the below screenshot as tx: 0x0e97a4c

I'm setting tx: 0x0e97a4c up with https://github.com/ethereumjs/ethereumjs-tx and sending with https://github.com/ethereum/web3.js/ as below:

var Web3 = require('web3');
var Transaction = require('ethereumjs-tx');
var data = contract.method.getData(some, data);
console.log("Data: " + data);
var gasEstimate = web3.eth.estimateGas({
    to: web3.env.SENDER_ADDRRESS,
    data: data
});
console.log("GasEstimate: " + gasEstimate);
var nonce = web3.eth.getTransactionCount(process.env.SENDER_ADDRRESS);
console.log("Transation Count: " + nonce);
var rawTx = {
    nonce: web3.toHex(nonce),
    gasPrice: web3.toHex(process.env.GAS_PRICE),
    gasLimit: web3.toHex(gasEstimate),
    to: web3.toHex(process.env.CONTRACT_ADDRESS),
    value: web3.toHex(provider.toWei('1', 'ether')),
    data: data,
    chainId: 3
};
console.log("RawTx: " + JSON.stringify(rawTx));
var tx = new Transaction(rawTx);
console.log(tx.getChainId());
tx.sign(new Buffer(process.env.KEY, 'hex'));
web3.eth.sendRawTransaction("0x".concat(tx.serialize().toString('hex')), function(error, txHash) {
    if (error) {
        console.log(error); // an error occurred
        callback(error);
    }
    else {
        callback(null,{"error":0,"tx":txHash});
    }
});

I know the node is syncing and propagating transactions, which are subsequently mined, as transactions setup and sent from the Parity UI succeed as pictured below (which shows as mined in the image above):

As some background, I've been developing a project for Ethereum using Solidity and Javascript and utilising Truffle and Web3js. Testing against TestRPC. After some research, I selected Parity over Geth and am using the Ropsten network to run tests.

I have Parity version:

Parity/v1.6.8-beta-c396229-20170608/x86_64-macos/rustc1.17.0

running on:

MacOS Sierra 10.12.5.

I'm starting parity with the following:

parity --pruning fast --chain ropsten --warp --mode active --jsonrpc-interface all --jsonrpc-hosts all --allow-ips public

What does status "In queue: Future" mean?

Is there some sort of transaction release mechanism with Parity?

Or am I not setting up the transaction correctly for this type of node?


问:
MSQL before insert, update trigger
Trying to make a befor update, insert trigger that would set the Age column's value based on calculation from the DateOfBirth. But I seem to be missing something</p>

```<code>create trigger calcAge before insert on BoardMember
for each row
begin
set NEW.Age = YEAR(CURRDATE()) - YEAR(BoardMember.DateOfBirth)
end;
</code>```

答:
You are trying to calculate the age automatically from the date of birth in the row of data before insertion. So your code should be like:

```<code>delimiter //
create trigger calcAge before insert on BoardMember
for each row
begin
set NEW.Age = YEAR(CURRDATE()) - YEAR(IFNULL(NEW.DateOfBirth,CURRDATE()));
end//
delimiter ;
</code>```

I used IFNULL to get the current date if the date of birth is null.
Noticed how BoardMember.DateOfBirth is replaced with NEW.DateOfBirth you made an error here. New is used to reference the row of data which is to be inserted into the table.

For more information see Create Trigger in MySQL

Title: MSQL before insert, update trigger

Body:
Trying to make a befor update, insert trigger that would set the Age column's value based on calculation from the DateOfBirth. But I seem to be missing something

create trigger calcAge before insert on BoardMember
for each row
begin
set NEW.Age = YEAR(CURRDATE()) - YEAR(BoardMember.DateOfBirth)
end;

Body:
You are trying to calculate the age automatically from the date of birth in the row of data before insertion. So your code should be like:

delimiter //
create trigger calcAge before insert on BoardMember
for each row
begin
set NEW.Age = YEAR(CURRDATE()) - YEAR(IFNULL(NEW.DateOfBirth,CURRDATE()));
end//
delimiter ;

I used IFNULL to get the current date if the date of birth is null.
Noticed how BoardMember.DateOfBirth is replaced with NEW.DateOfBirth you made an error here. New is used to reference the row of data which is to be inserted into the table.

For more information see Create Trigger in MySQL


答:
Sorry, cant comment yet.

I dont think there is a direct answer, but making some assumptions:

if you will not load same data again (you probably load data to table with something like for item in data), probably its ok to just remove on client side. But if you will rerender same data over and over again with removing what was removed on client side, so queries will be heavier anyway as it would in other case. Alsow you would perform this .remove() again and again


问:
Getting an index from a column, then using it in to get a value from the other columns for a large file
I have a very large file consisting of many lines and rows. To simplify my question, let's assume that there are 201 columns. The first column is like that AB:CD:EF:GH and other columns are like that 1:2:3:4. The delimiters are the same, as it is seen. The pattern of all columns are supposed to be same. If there are 3 delimiter for the first column, it means there are 3 delimiters for all other in a given line.

For example I would like to know the index of EF in first column of the line and use that index to get the 3 from the all of columns. The index of EF varies across the lines.

I used two split methods. However, since my file is really big, it generates a great bottleneck for my code. There are more than ten millions lines by the way.

```<code>with open("amkhepinizin.txt", "r") as theFile:
    for line in theFile:
        ind = line[0].split(":").index("EF")
        theList = []
        for j in range(1,202):
            theList.append(line[j].split(":")[ind])
        foo(theList)  # some processes
</code>```

It works but it is kind of slow. I found out that split methods which is called about 200 times for each line cause the code to work slowly. I thought that I can fasten this by using regular expressions, which I had no idea at first. I tried to find out how I can use regex, but I could not.

Here is an small example of my file.

```<code>EF:AD:DP:GQ:PL    0/0:95,0:96:99:0,214,2836    0/1:103,0:103:99:0,229,3036
AD:EF:DP:GQ:PL    0/1:16,7:25:99:242:5,1,6     0/0:32,0:33:93:0,93,1102
DP:GQ:EF          99:533,0,422:1               99:310,0,1129:6
::EF:DP:          ::::                         0::0::
</code>```

So basically, I would like to get 0/0 and 0/1 from first line; then 16,7 and 32,0 from the second line and 1 and 6 from the third line. "" and 0 from the fourth line.

Could you please help me how to implement regex in my code.

If you think regex does not fasten my code, I would appreciate other suggestions.

答:
It might speed up your code to use some generators:

```<code>import re

data = """
EF:AD:DP:GQ:PL    0/0:95,0:96:99:0,214,2836    0/1:103,0:103:99:0,229,3036
AD:EF:DP:GQ:PL    0/1:16,7:25:99:242:5,1,6     0/0:32,0:33:93:0,93,1102
DP:GQ:EF          26:99:533,0,422:1            39:99:310,0,1129:6
::EF:DP:          ::::                         0::0::
"""

rx_needle = 'EF'

rx_lines = re.compile(r'.+')
rx_split = re.compile(r'\s{2,}')

def item_getter(line, needle):
    parts = rx_split.split(line)

    try:
        ind = parts[0].split(':').index(needle)
        values = (p[ind] for part in parts[1:] for p in [part.split(':')])
        return values
    except ValueError:
        return None

for line in rx_lines.finditer(data):
    values = item_getter(line.group(0), rx_needle)
    # do whatever you want to do with values here
    print(list(values))
</code>```

Here, the idea is to use a generator to find the next line with re.finditer() and use another generator to get the specific values from that line (given the needle is found).

Advantage is that you can stop at a specific time in the future (let's say after 1000 lines or something) and that only small(er) amounts of memory are used.

A speed example:

```<code>def t():
    for line in rx_lines.finditer(data):
        values = item_getter(line.group(0), rx_needle)

import timeit
s = timeit.timeit(t, number=10**5)
print(s)
# 3.28 s
</code>```

So to run the function against 400k lines, it takes about 3 seconds.

Body:
I have a very large file consisting of many lines and rows. To simplify my question, let's assume that there are 201 columns. The first column is like that AB:CD:EF:GH and other columns are like that 1:2:3:4. The delimiters are the same, as it is seen. The pattern of all columns are supposed to be same. If there are 3 delimiter for the first column, it means there are 3 delimiters for all other in a given line.

For example I would like to know the index of EF in first column of the line and use that index to get the 3 from the all of columns. The index of EF varies across the lines.

I used two split methods. However, since my file is really big, it generates a great bottleneck for my code. There are more than ten millions lines by the way.

with open("amkhepinizin.txt", "r") as theFile:
    for line in theFile:
        ind = line[0].split(":").index("EF")
        theList = []
        for j in range(1,202):
            theList.append(line[j].split(":")[ind])
        foo(theList)  # some processes

It works but it is kind of slow. I found out that split methods which is called about 200 times for each line cause the code to work slowly. I thought that I can fasten this by using regular expressions, which I had no idea at first. I tried to find out how I can use regex, but I could not.

Here is an small example of my file.

EF:AD:DP:GQ:PL    0/0:95,0:96:99:0,214,2836    0/1:103,0:103:99:0,229,3036
AD:EF:DP:GQ:PL    0/1:16,7:25:99:242:5,1,6     0/0:32,0:33:93:0,93,1102
DP:GQ:EF          99:533,0,422:1               99:310,0,1129:6
::EF:DP:          ::::                         0::0::

So basically, I would like to get 0/0 and 0/1 from first line; then 16,7 and 32,0 from the second line and 1 and 6 from the third line. "" and 0 from the fourth line.

Could you please help me how to implement regex in my code.

If you think regex does not fasten my code, I would appreciate other suggestions.

Body:
It might speed up your code to use some generators:

import re

data = """
EF:AD:DP:GQ:PL    0/0:95,0:96:99:0,214,2836    0/1:103,0:103:99:0,229,3036
AD:EF:DP:GQ:PL    0/1:16,7:25:99:242:5,1,6     0/0:32,0:33:93:0,93,1102
DP:GQ:EF          26:99:533,0,422:1            39:99:310,0,1129:6
::EF:DP:          ::::                         0::0::
"""

rx_needle = 'EF'

rx_lines = re.compile(r'.+')
rx_split = re.compile(r'\s{2,}')

def item_getter(line, needle):
    parts = rx_split.split(line)

    try:
        ind = parts[0].split(':').index(needle)
        values = (p[ind] for part in parts[1:] for p in [part.split(':')])
        return values
    except ValueError:
        return None

for line in rx_lines.finditer(data):
    values = item_getter(line.group(0), rx_needle)
    # do whatever you want to do with values here
    print(list(values))

Here, the idea is to use a generator to find the next line with re.finditer() and use another generator to get the specific values from that line (given the needle is found).

Advantage is that you can stop at a specific time in the future (let's say after 1000 lines or something) and that only small(er) amounts of memory are used.

A speed example:

def t():
    for line in rx_lines.finditer(data):
        values = item_getter(line.group(0), rx_needle)

import timeit
s = timeit.timeit(t, number=10**5)
print(s)
# 3.28 s

So to run the function against 400k lines, it takes about 3 seconds.


问:
Open video stream on VLC Player through the browser
Is it possible to add a type of link on a webpage that will open up VLC Player and start playing a stream video? Like this one:

Alternatively, is it possible to embed VLC Player in the browser?

答:
You can open a streaming site, view the source of the page and find the URL of the video (sometimes you have to play the video in order to be able to see the URL). Then copy and paste this link on "Open network stream..." (Ctrl+N) and here you go.

I wrote a little script that automates this process finding the URL in the streaming site and then opening it with VLC using a custom protocol. It's a really simple JS script that find the videos URL in the page and redirect to vlcs:URL; the custom protocol opens another script that delete the vlcs: from the string and send the resulting URL to VLC. All this simply by opening the streaming site.

It works with some streaming sites but I will upgrade the script with also others. Feel free read the code and add your favorite streaming site or send pull requests for new sites.

Here's the link with the instructions: https://github.com/giuseppe-dandrea/Stream-to-VLC

Hope it could help you!


问:
How to catch exception when creating MongoClient instance
I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.

```<code>try {
            new MongoClient("localhost", 1111);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

If the hostname or port number is not correct, I will get below exceptions. I wander how I can catch that exceptions. MongoDB connecting is happening in an internal thread which can't be catched by client code. I want to know whether the MongoClient has connected correctly or not. How can I get that information?

```<code>INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more
</code>```

EDIT1

The exceptions shown above is not catch by my code. It may be catch by Mongo code. So I don't know whether the instance is created correctly or not.

答:
It's pretty simple and elegant:

Redirect System.err to a file:

```<code>ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setErr(new PrintStream(file));
</code>```

Connect to the server with your MongoClient and your MongoCredentials:

```<code>MongoCredential credenciales=MongoCredential.createCredential("root", "admin", "root".toCharArray());
MongoClient client = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credenciales));
</code>```

Read the error output, which is in the ByteArrayOutputStream object:

```<code>String texto=new String(file.toByteArray());
</code>```

Check whether the Autentication failed string is present:

```<code>if (texto.contains("'Authentication failed.'"))
   // do something;
else
  ...
</code>```

Body:
I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.

try {
            new MongoClient("localhost", 1111);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

If the hostname or port number is not correct, I will get below exceptions. I wander how I can catch that exceptions. MongoDB connecting is happening in an internal thread which can't be catched by client code. I want to know whether the MongoClient has connected correctly or not. How can I get that information?

INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

EDIT1

The exceptions shown above is not catch by my code. It may be catch by Mongo code. So I don't know whether the instance is created correctly or not.

Body:
It's pretty simple and elegant:

Redirect System.err to a file:

ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setErr(new PrintStream(file));

Connect to the server with your MongoClient and your MongoCredentials:

MongoCredential credenciales=MongoCredential.createCredential("root", "admin", "root".toCharArray());
MongoClient client = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credenciales));

Read the error output, which is in the ByteArrayOutputStream object:

String texto=new String(file.toByteArray());

Check whether the Autentication failed string is present:

if (texto.contains("'Authentication failed.'"))
   // do something;
else
  ...


问:
Python inserting spaces in string
Alright, I'm working on a little project for school, a 6-frame translator. I won't go into too much detail, I'll just describe what I wanted to add.
The normal output would be something like:

```<code>TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD
</code>```

The important part of this string are the M and the _ (the start and stop codons, biology stuff). What I wanted to do was highlight these like so:

```<code>TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSD
</code>```

Now here is where (for me) it gets tricky, I got my output to look like this (adding a space and a ' to highlight the start and stop). But it only does this once, for the first start and stop it finds. If there are any other M....._ combinations it won't highlight them.

Here is my current code, attempting to make it highlight more than once:

```<code>def start_stop(translation):
index_2 = 0
while True:
    if 'M' in translation[index_2::1]:
        index_1 = translation[index_2::1].find('M')
        index_2 = translation[index_1::1].find('_') + index_1
        new_translation = translation[:index_1] + " '" + \
                          translation[index_1:index_2 + 1] + "' " +\
                          translation[index_2 + 1:]
    else:
        break
    return new_translation
</code>```

I really thought this would do it, guess not. So now I find myself being stuck.
If any of you are willing to try and help, here is a randomly generated string with more than one M....._ set:

```<code>'TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLYMPPARRLATKSRFLTPVISSG_DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI'
</code>```

Thank you to anyone willing to help :)

答:
Regular expressions are pretty handy here:

```<code>import re
sequence = "TTCP...."
highlighted = re.sub(r"(M\w*?_)", r" '\1' ", sequence)

# Output:
"TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLY 'MPPARRLATKSRFLTPVISSG_' DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI"
</code>```

Regex explanation:

We look for an M followed by any number of "word characters" \w* then an _, using the ? to make it a non-greedy match (otherwise it would just make one group from the first M to the last _).

The replacement is the matched group (\1 indicates "first group", there's only one), but surrounded by spaces and quotes.

Title: Python inserting spaces in string

Body:
Alright, I'm working on a little project for school, a 6-frame translator. I won't go into too much detail, I'll just describe what I wanted to add.
The normal output would be something like:

TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD

The important part of this string are the M and the _ (the start and stop codons, biology stuff). What I wanted to do was highlight these like so:

TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSD

Now here is where (for me) it gets tricky, I got my output to look like this (adding a space and a ' to highlight the start and stop). But it only does this once, for the first start and stop it finds. If there are any other M....._ combinations it won't highlight them.

Here is my current code, attempting to make it highlight more than once:

def start_stop(translation):
index_2 = 0
while True:
    if 'M' in translation[index_2::1]:
        index_1 = translation[index_2::1].find('M')
        index_2 = translation[index_1::1].find('_') + index_1
        new_translation = translation[:index_1] + " '" + \
                          translation[index_1:index_2 + 1] + "' " +\
                          translation[index_2 + 1:]
    else:
        break
    return new_translation

I really thought this would do it, guess not. So now I find myself being stuck.
If any of you are willing to try and help, here is a randomly generated string with more than one M....._ set:

'TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLYMPPARRLATKSRFLTPVISSG_DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI'

Thank you to anyone willing to help :)

Body:
Regular expressions are pretty handy here:

import re
sequence = "TTCP...."
highlighted = re.sub(r"(M\w*?_)", r" '\1' ", sequence)

# Output:
"TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLY 'MPPARRLATKSRFLTPVISSG_' DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI"

Regex explanation:

We look for an M followed by any number of "word characters" \w* then an _, using the ? to make it a non-greedy match (otherwise it would just make one group from the first M to the last _).

The replacement is the matched group (\1 indicates "first group", there's only one), but surrounded by spaces and quotes.