问:
git - pushing only the top most commit to server
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

```<code>git push origin HEAD:refs/for/mybranch
</code>```

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?

答:
Second revision:

```<code>git reset --soft HEAD^ (to undo your commit)
git stash (to stash away your changes)
git reset --soft HEAD^ (to undo the merge commit from X)
git stash (stash away X)
git stash apply stash@{1} (apply your changes)
git add . (add and commit and push ..)
git commit -m "some changes"
git push
git stash apply stash@{0}
</code>```

Revised answer:

Ok, then you need to reset one step more back in the history:

```<code>git reset --soft HEAD^ (to undo your commit)
git stash (to stash away your changes)
git reset --hard HEAD^ (to undo the merge commit from X)
git stash apply (apply your changes)
git add . (add and commit and push ..)
git commit -m "some changes"
git push
git merge featureX (re merge the changes from X)
</code>```

Original answer:

You could reset your head so your commit is moved to the index:

```<code>git reset --soft HEAD^
</code>```

Now git will be in the state of the merged code and your changes uncommitted and ready to be staged again. Now you can stash these changes:

```<code>git stash save "stashing commit for changes from X"
</code>```

Now you can push up the merged changes from X and after that apply the stash, add and commit:

```<code>git push
git stash apply
git add .
git commit -m "some stuff"
</code>```

Body:
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

git push origin HEAD:refs/for/mybranch

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?

Body:
Second revision:

git reset --soft HEAD^ (to undo your commit)
git stash (to stash away your changes)
git reset --soft HEAD^ (to undo the merge commit from X)
git stash (stash away X)
git stash apply stash@{1} (apply your changes)
git add . (add and commit and push ..)
git commit -m "some changes"
git push
git stash apply stash@{0}

Revised answer:

Ok, then you need to reset one step more back in the history:

git reset --soft HEAD^ (to undo your commit)
git stash (to stash away your changes)
git reset --hard HEAD^ (to undo the merge commit from X)
git stash apply (apply your changes)
git add . (add and commit and push ..)
git commit -m "some changes"
git push
git merge featureX (re merge the changes from X)

Original answer:

You could reset your head so your commit is moved to the index:

git reset --soft HEAD^

Now git will be in the state of the merged code and your changes uncommitted and ready to be staged again. Now you can stash these changes:

git stash save "stashing commit for changes from X"

Now you can push up the merged changes from X and after that apply the stash, add and commit:

git push
git stash apply
git add .
git commit -m "some stuff"


来源: stackexchange

问:
Best way to show and hide GUI when click occurs
I want a dat.GUI() instance to show up when a click occurs inside a mesh, and when its clicked again to disapear.
Obviosouly, when it is reclicked, i want to it reapper.
I tried many different things but i cannot get the behaviour i want...

For example chick this code:

```<code> function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xF7F7F7 );

            var params = {
                textField: "Enter value:"
            }

            var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                console.log(value);
            });

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
           dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }
</code>```

Now when i click the mesh, the GUi is created, when i reclick it dissaperas, but when i click again weird stuff happens.

Sometimes the hide button does not work, but ultimately i end up with many different GUIS, where i only want one.

And have the option to make it appear / dissapear.

答:
You can do it this way:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

params = {
  zAxis: "1"
}
var gui = new dat.GUI();
gui.add(params, "zAxis").onFinishChange(val => {
  cube.scale.z = parseFloat(val);
});

var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var intersects;

window.addEventListener("click", event => {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);
  intersects = raycaster.intersectObject(cube);
  if (intersects.length > 0) {
    let vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";
  }
});

var animate = function() {
  requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render(scene, camera);
};

animate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
I want a dat.GUI() instance to show up when a click occurs inside a mesh, and when its clicked again to disapear.
Obviosouly, when it is reclicked, i want to it reapper.
I tried many different things but i cannot get the behaviour i want...

For example chick this code:

 function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xF7F7F7 );

            var params = {
                textField: "Enter value:"
            }

            var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                console.log(value);
            });

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
           dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

Now when i click the mesh, the GUi is created, when i reclick it dissaperas, but when i click again weird stuff happens.

Sometimes the hide button does not work, but ultimately i end up with many different GUIS, where i only want one.

And have the option to make it appear / dissapear.

Body:
You can do it this way:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

params = {
  zAxis: "1"
}
var gui = new dat.GUI();
gui.add(params, "zAxis").onFinishChange(val => {
  cube.scale.z = parseFloat(val);
});

var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var intersects;

window.addEventListener("click", event => {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);
  intersects = raycaster.intersectObject(cube);
  if (intersects.length > 0) {
    let vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";
  }
});

var animate = function() {
  requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render(scene, camera);
};

animate();

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/libs/dat.gui.min.js"></script>


问:
Having trouble coding a REACT onChange
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

```<code>handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}
</code>```

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

```<code>npx create-react-app test --template typescript
</code>```

with no changes to the generated configuration files.

The state was declared as

```<code>state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}
</code>```

Any ideas ?

答:
First of all, Welcome to the awesome React world.

Advice: You can include on your ticket the react version that you are using on your code.

It seems that you are using an old React version because now we have React hooks that allow us to use useState and other interesting stuff.

This is the React hooks documentation: https://reactjs.org/docs/hooks-intro.html

Related to your problem I think that you should take a look at the setState documentation: https://reactjs.org/docs/react-component.html#setstate

setState method receives a function that provides the updated state, below I have included a little example using your code, on this way you are making sure that the state that you are updating the proper state.

class TestComponent extends React.Component {
  constructor() {
    this.state = {
      test: true,
      data: {},
    };
  }

  handleSubmit(e) {
    this.setState((state) => ({
      ...state,
      data: {
        ...state.data,
        [e.target.name]: e.target.value,
      },
    }));
  }

  render(){
      return
Test

  }
}
```

Title: Having trouble coding a REACT onChange

Body:
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

npx create-react-app test --template typescript

with no changes to the generated configuration files.

The state was declared as

state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}

Any ideas ?

Body:
First of all, Welcome to the awesome React world.

Advice: You can include on your ticket the react version that you are using on your code.

It seems that you are using an old React version because now we have React hooks that allow us to use useState and other interesting stuff.

This is the React hooks documentation: https://reactjs.org/docs/hooks-intro.html

Related to your problem I think that you should take a look at the setState documentation: https://reactjs.org/docs/react-component.html#setstate

setState method receives a function that provides the updated state, below I have included a little example using your code, on this way you are making sure that the state that you are updating the proper state.

class TestComponent extends React.Component {
  constructor() {
    this.state = {
      test: true,
      data: {},
    };
  }

  handleSubmit(e) {
    this.setState((state) => ({
      ...state,
      data: {
        ...state.data,
        [e.target.name]: e.target.value,
      },
    }));
  }

  render(){
      return <div>Test</div>
  }
}


问:
How do I get an image and paragraph to wait before showing up after clicking for web development
I'm trying to create some lag time from when an one of my images is clicked to when the image and accompanying paragraph show up. In my code, you see the four images. When you click on them, an expanded version of the image and a paragraph shows up. I want it so after you click on an image, there is a lag time of about one second between your click and the image-paragraph duo showing up, but I only want this to happen for the first click on any image. For the second click on any image, I want it to show up instantaneously. I'm new to programming and I'm having a lot of trouble with this. I would love any help I can get. Let me know if you guys need more info. Thanks

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

答:
I've added a check to make the function know if it needs to wait, if not you can click and render immediately, else (on the first click) we wait 1 second before rendering anything

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

Body:
I'm trying to create some lag time from when an one of my images is clicked to when the image and accompanying paragraph show up. In my code, you see the four images. When you click on them, an expanded version of the image and a paragraph shows up. I want it so after you click on an image, there is a lag time of about one second between your click and the image-paragraph duo showing up, but I only want this to happen for the first click on any image. For the second click on any image, I want it to show up instantaneously. I'm new to programming and I'm having a lot of trouble with this. I would love any help I can get. Let me know if you guys need more info. Thanks

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

Body:
I've added a check to make the function know if it needs to wait, if not you can click and render immediately, else (on the first click) we wait 1 second before rendering anything

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 600px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />
    <script src='../Javascript/script.js'></script>
    <title>Projects</title>
</head>
<body class='totalbody'>

  <header class="topnav" id="topnav">
    <a class="link" href="../index.html">Home</a>
    <a class="link" href="#Academics">Academics</a>
    <a class="active-menu" href="projects.html">Projects</a>
    <a class="link" href="communityservice.html">Community Service</a>
  </header>

  <div>
    <div id="expanded-wrapper">
      <img id="expandedImg">
      <p id="img-paragraph"></p>
    </div>
  </div>

  <div class="row">
    <div class="column">
      <img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" alt="Nature" style="width:100%" yeep="<p class='yeep1'> Parapraph #1 </p>" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://s.yimg.com/ny/api/res/1.2/Petngc9GmDGVfvqWtZW1uw--/YXBwaWQ9aGlnaGxhbmRlcjt3PTcwNTtoPTM4MC43/https://s.yimg.com/uu/api/res/1.2/p2FH9i2oATkHA6O0ucuC9A--~B/aD0yMTY7dz00MDA7c209MTthcHBpZD15dGFjaHlvbg--/https://media.zenfs.com/en/prnewswire.com/d908212583d777d158af74cb171ec897"
        alt="Snow" style="width:100%" yeep="<p class='yeep2'> Parapraph #2 </p>" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://engineering.wustl.edu/news/PublishingImages/141020_jwb_brookings_007-1915x768.jpg?RenditionID=1" alt="Mountains" style="width:100%" yeep="<p class='yeep3'> Parapraph #3 </p>" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://techcrunch.com/wp-content/uploads/2019/01/McKelvey-courtyard.jpg" alt="Lights" style="width:100%" yeep="<p class='yeep4'> Parapraph #4 </p>" onclick="myFunction(this);">

    </div>
  </div>
</body>
</html>


问:
How to position a Text/TextSpan inside a class
How can I position my Text like this? I check the docs and I only see texts that are on each of the other side of the row but not someone like this which is the other way around.

I just wanted to have my first column takes about 30% of the row inside a card with text alignment of right and my second column takes about 70% of the row inside a card with text alignment of left. I also wanted to have it like a sort of table where in everything is in proper alignment with regards to column. Thank you

```<code>         Date:   Today
      Address:   Sample
       Gender:   Male
       Status:   Active
</code>```

答:
You can use this code:

```<code>Table(
 children: [
   buildTableRow("Date:", "Today"),
   buildTableRow("Address:", "Sample"),
   buildTableRow("Gender:", "Male"),
   buildTableRow("Status:", "Active"),
 ],
),

TableRow buildTableRow(String _title, String _value) {
 return TableRow(
  children: [
    Container(child: Text(_title), alignment: Alignment.centerRight),
    Container(
      child: Padding(padding: const EdgeInsets.only(left: 15), child: Text(_value)),
      alignment: Alignment.centerLeft,
    ),
  ],
 );
}
</code>```

Code output:

Body:
How can I position my Text like this? I check the docs and I only see texts that are on each of the other side of the row but not someone like this which is the other way around.

I just wanted to have my first column takes about 30% of the row inside a card with text alignment of right and my second column takes about 70% of the row inside a card with text alignment of left. I also wanted to have it like a sort of table where in everything is in proper alignment with regards to column. Thank you

         Date:   Today
      Address:   Sample
       Gender:   Male
       Status:   Active

Body:
You can use this code:

Table(
 children: [
   buildTableRow("Date:", "Today"),
   buildTableRow("Address:", "Sample"),
   buildTableRow("Gender:", "Male"),
   buildTableRow("Status:", "Active"),
 ],
),

TableRow buildTableRow(String _title, String _value) {
 return TableRow(
  children: [
    Container(child: Text(_title), alignment: Alignment.centerRight),
    Container(
      child: Padding(padding: const EdgeInsets.only(left: 15), child: Text(_value)),
      alignment: Alignment.centerLeft,
    ),
  ],
 );
}

Code output:


问:
dplyr: Subtracting values group-wise by group that matches given condition
right now I'm refactoring an 'base'-based R script by using 'dplyr' instead.

Basically, I want to group_by Gene and subtract the values group-wise by a group that matches a given condition. In this case, I want values of Gene == 'C' and subtract them from all others.

Simplified data:

```<code>x <- data.frame('gene' = c('A','A','A','B','B','B','C','C','C'),
                'sample' = rep_len(c('wt','mut1','mut2'),3),
                'value' = c(32.3,31,30.5,25,25.3,22.1,20.5,21.2,19.8))

  gene sample value
1    A     wt  32.3
2    A   mut1  31.0
3    A   mut2  30.5
4    B     wt  25.0
5    B   mut1  25.3
6    B   mut2  22.1
7    C     wt  20.5
8    C   mut1  21.2
9    C   mut2  19.8
</code>```

Desired output:

```<code>  gene sample value deltaC
1    A     wt  32.3   11.8
2    A   mut1  31.0    9.8
3    A   mut2  30.5   10.7
4    B     wt  25.0    4.5
5    B   mut1  25.3    4.1
6    B   mut2  22.1    2.3
7    C     wt  20.5    0.0
8    C   mut1  21.2    0.0
9    C   mut2  19.8    0.0
</code>```

I base, it's not a big deal, but I'm wondering whether there is a simple solution using dplyr.

'Pseudo'code:

```<code>df %>%
    group_by(Gene) %>%
    mutate(deltaC = Value - Value(where Gene == 'C'))
</code>```

Is there any kind of function that allows me to access only those values of Gene == 'C'? Of course I could also do a subset before, but I would like to do it in one step :)

答:
If you wanted to avoid the $ completely, you could use dplyr::pull like so:

```<code>df %>%
  group_by(gene) %>%
  mutate(deltaC = value - filter(., gene == 'C') %>% pull(value))
</code>```

dplyr::pull is basically just the pipe friendly, dplyr equivalent to df$value or df$[["value"]]

Also, using the . inside of the filter statement represents the data that is being piped into the mutate statement.

ContentLicense: CC BY-SA 3.0

Body:
right now I'm refactoring an 'base'-based R script by using 'dplyr' instead.

Basically, I want to group_by Gene and subtract the values group-wise by a group that matches a given condition. In this case, I want values of Gene == 'C' and subtract them from all others.

Simplified data:

x <- data.frame('gene' = c('A','A','A','B','B','B','C','C','C'),
                'sample' = rep_len(c('wt','mut1','mut2'),3),
                'value' = c(32.3,31,30.5,25,25.3,22.1,20.5,21.2,19.8))

  gene sample value
1    A     wt  32.3
2    A   mut1  31.0
3    A   mut2  30.5
4    B     wt  25.0
5    B   mut1  25.3
6    B   mut2  22.1
7    C     wt  20.5
8    C   mut1  21.2
9    C   mut2  19.8

Desired output:

  gene sample value deltaC
1    A     wt  32.3   11.8
2    A   mut1  31.0    9.8
3    A   mut2  30.5   10.7
4    B     wt  25.0    4.5
5    B   mut1  25.3    4.1
6    B   mut2  22.1    2.3
7    C     wt  20.5    0.0
8    C   mut1  21.2    0.0
9    C   mut2  19.8    0.0

I base, it's not a big deal, but I'm wondering whether there is a simple solution using dplyr.

'Pseudo'code:

df %>%
    group_by(Gene) %>%
    mutate(deltaC = Value - Value(where Gene == 'C'))

Is there any kind of function that allows me to access only those values of Gene == 'C'? Of course I could also do a subset before, but I would like to do it in one step :)

Body:
If you wanted to avoid the $ completely, you could use dplyr::pull like so:

df %>%
  group_by(gene) %>%
  mutate(deltaC = value - filter(., gene == 'C') %>% pull(value))

dplyr::pull is basically just the pipe friendly, dplyr equivalent to df$value or df$[["value"]]

Also, using the . inside of the filter statement represents the data that is being piped into the mutate statement.


问:
Best way to implement HTML5 video
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

```<code>    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />
        <!-- Fallback (either Flash, an image, or a "Video not supported" message, etc.) -->
    </video>
</code>```

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.

答:
```<code><video id="movie" width="320" height="320" preload controls>
  <source src="pr6.mp4" type='video/mp4; codecs=avc1.42E01E, mp4a.40.2"' />
  <source src="pr6.webm" type='video/webm; codecs="vp8, vorbis"' />
  <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"' />
  <object width="320" height="240" type="application/x-shockwave-flash" data="flowplayer-3.2.1.swf">
    <param ... />
  </object>
</video>
</code>```

This example is taken from the book HTML5 Up and Running.  You list each supported video encoding separately within a single <video> tag.  The browser will try each one, starting with the first. This example shows three encodings.  You will need do the actual video encoding yourself.  To support multiple browsers, you'll need multiple encodings.

The final entry is a fallback for browsers that don't support the new HTML5 video tag.  In the example, I used flash, but you can use whatever old-school format you prefer.

Title: Best way to implement HTML5 video

Body:
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />

    </video>

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.

Body:
<video id="movie" width="320" height="320" preload controls>
  <source src="pr6.mp4" type='video/mp4; codecs=avc1.42E01E, mp4a.40.2"' />
  <source src="pr6.webm" type='video/webm; codecs="vp8, vorbis"' />
  <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"' />
  <object width="320" height="240" type="application/x-shockwave-flash" data="flowplayer-3.2.1.swf">
    <param ... />
  </object>
</video>

This example is taken from the book HTML5 Up and Running.  You list each supported video encoding separately within a single <video> tag.  The browser will try each one, starting with the first. This example shows three encodings.  You will need do the actual video encoding yourself.  To support multiple browsers, you'll need multiple encodings.

The final entry is a fallback for browsers that don't support the new HTML5 video tag.  In the example, I used flash, but you can use whatever old-school format you prefer.


问:
Telegram-Bot does not respond correctly
I am doing a telegram bot, I have a merger that is to divide that does not work but to add if it does, does anyone know why?

```<code>import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def start(update, context):
    update.message.reply_text('Hola!')

def help(update, context):
    update.message.reply_text('Help!')

def sumar(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def dividir(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        div= numero1 / numero2
        update.message.reply_text('La division da '+str(div))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("1225696978:AAFsJYex51HMRbKL814tLJJPczJMu3nLlYY", use_context=True)

    # Get the dispatcher to register handlers
    botm3 = updater.dispatcher

    # on different commands - answer in Telegram
    botm3.add_handler(CommandHandler("start", start))
    botm3.add_handler(CommandHandler("help", help))
    botm3.add_handler(CommandHandler("Sumar", sumar))
    botm3.add_handler(CommandHandler("Division", dividir))

    # on noncommand i.e message - echo the message on Telegram
    botm3.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    botm3.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

I have two functions for the bot, one works the other does not and they are the same structure but it does not take effect.
I leave you my token so you can do the tests if you want the name of the bot is:
@ moha_m03_1bot

答:
I think the name of the command is confusing:

'/Sumar 2 2' -> La suma es 4

'/Division 4 2' -> La division da 2.0

'/Dividir 2 2' -> doesnt match any command

The commands are called Sumar and Division, maybe you meant them to be called Sumar and Dividir

Title: Telegram-Bot does not respond correctly

Body:
I am doing a telegram bot, I have a merger that is to divide that does not work but to add if it does, does anyone know why?

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def start(update, context):
    update.message.reply_text('Hola!')

def help(update, context):
    update.message.reply_text('Help!')

def sumar(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def dividir(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])

        div= numero1 / numero2
        update.message.reply_text('La division da '+str(div))

    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("1225696978:AAFsJYex51HMRbKL814tLJJPczJMu3nLlYY", use_context=True)

    # Get the dispatcher to register handlers
    botm3 = updater.dispatcher

    # on different commands - answer in Telegram
    botm3.add_handler(CommandHandler("start", start))
    botm3.add_handler(CommandHandler("help", help))
    botm3.add_handler(CommandHandler("Sumar", sumar))
    botm3.add_handler(CommandHandler("Division", dividir))

    # on noncommand i.e message - echo the message on Telegram
    botm3.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    botm3.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

I have two functions for the bot, one works the other does not and they are the same structure but it does not take effect.
I leave you my token so you can do the tests if you want the name of the bot is:
@ moha_m03_1bot


问:
Python/Windows doesn't let numpy allocate RAM "numpy.core._exceptions.MemoryError"
I know this question was already asked, but this is special:
I am using Windows and I am trying to allocate a 250000*200 Array (via numpy.random.normal) out of float64 variables. Those add up to 50000000 float64 variables, which (when they each take 4 Byte) need 200.000.000 Bytes, which are approx. 190 MB.

I have 8GB RAM and always AT LEAST 2 GB RAM free and I still get the same error. AND I actually allocated 10GB RAM from my SSD, that means that I should have at least 12GB RAM free.

Using Windows 10 64bit

答:
I got it working! I had the 32 Bit Version of Python (I should be ashamed of me :D) and now I installed the 64 bit version and it works fine.

THANKS for everyone who had liked to help me though!


问:
Can`t get preventDefault to work: item.preventDefault is not a function
I  try to create a js script That firstly block default and only second time let go to link for mobile menus, but I can not get preventDefault to work, the error is: item.preventDefault is not a function. the others are ok, the .setAttribute is working.

this is my script i tried with no luck:

var hasChild = document.querySelectorAll(".menu-item-has-children a");
hasChild.forEach(setPrevent);

function setPrevent(item) {
  item.setAttribute('data-active', 'false');
  item.addEventListener("click", respButAction);
  item.preventDefault();
  // this.preventDefault();
}

function respButAction(item) {
  isaActive = this.getAttribute('data-active');
  console.log(isaActive);

  if (isaActive == 'false') {
    this.setAttribute('data-active', 'true');
    // item.setAttribute('data-active', 'true');
    item.stopPropagation();
    // this.stopPropagation();
  }
  if (isaActive == 'true') {
    this.setAttribute('data-active', 'false');
    // item.setAttribute('data-active', 'false');
    item.preventDefault();
    //this.preventDefault();
  }
}
```

答:
as I mentioned in the comment.

The issue is in the method setPrevent(item), here you can't call item.preventDefault(); because the item variable is the actual DOM element.

I would suggest 2 changes:
 1. remove the call in the method setPrevent(item)
 2. rename the variable in the method respButAction(item)

example:

```<code>var hasChild = document.querySelectorAll(".menu-item-has-children a");
hasChild.forEach(setPrevent);

function setPrevent(item) {
    item.setAttribute('data-active', 'false');
    item.addEventListener("click", respButAction);
    // remove: item.preventDefault();
}

function respButAction(event) {
    isaActive = this.getAttribute('data-active');
    console.log(isaActive);

    if (isaActive == 'false') {
         this.setAttribute('data-active', 'true');
         event.stopPropagation();
    }
    if (isaActive == 'true') {
         this.setAttribute('data-active', 'false');
         event.preventDefault();
    }
}
</code>```

With this new variable name event you avoid confusion with item an event types, if you see in the docs from about the preventDefault you can understand the difference better

Body:
as I mentioned in the comment.

The issue is in the method setPrevent(item), here you can't call item.preventDefault(); because the item variable is the actual DOM element.

I would suggest 2 changes:
 1. remove the call in the method setPrevent(item)
 2. rename the variable in the method respButAction(item)

example:

var hasChild = document.querySelectorAll(".menu-item-has-children a");
hasChild.forEach(setPrevent);

function setPrevent(item) {
    item.setAttribute('data-active', 'false');
    item.addEventListener("click", respButAction);
    // remove: item.preventDefault();
}

function respButAction(event) {
    isaActive = this.getAttribute('data-active');
    console.log(isaActive);

    if (isaActive == 'false') {
         this.setAttribute('data-active', 'true');
         event.stopPropagation();
    }
    if (isaActive == 'true') {
         this.setAttribute('data-active', 'false');
         event.preventDefault();
    }
}

With this new variable name event you avoid confusion with item an event types, if you see in the docs from about the preventDefault you can understand the difference better


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
Use the Math.abs function:

```<code>$.map(eformDetailIds, function(e) {
        return e && e < 0 ? Math.abs(e) : 0;
});
</code>```

More info here

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

Body:
Use the Math.abs function:

$.map(eformDetailIds, function(e) {
        return e && e < 0 ? Math.abs(e) : 0;
});

More info here


问:
Doctrine ODM Select database at runtime
I want to use doctrine ODM for my project and I had the idea to have a seperate database for each of my clients. I want to be able to manage clients at runtime, through my API. My question now is:

When I setup doctrine ODM I have to set my database settings in my parameters.yml but I want to be able to select the database at runtime. I will have one main database with all my fixture collections and client index to know which database to select, but the client specific stuff will then be in those client databases. Each Document class will still be linked to a collection like in the normal situation, but then in a different database.

Is there a way to select the database for a Document class at runtime?

So lets say I go to www.myproject.com/client1/item/list
I will list every item in the dbclient1.Items collection, and if I go to www.myproject.com/client2/item/list I will list all items in the dbclient2.Items collection.

I hope I made clear what I want to reach here... I couldn't find anything about this, but I think it would be weird if I was the first person to have a question about this... There must have been people before me with the same idea right?

答:
I also needed to default the databaseName depending on the domainName (i.e. seballot.mysite.com will use seballot database)

I made this hack, which not very nice but works great. I added those line in the DocumentManager construct

$dbName = isset($_SERVER["HTTP_HOST"]) ? explode('.', $_SERVER["HTTP_HOST"])[0] : 'default_database_of_my_root_website';
$this->config->setDefaultDB($dbName);
```

Title: Doctrine ODM Select database at runtime


问:
REACT TypeError: Class extends value undefined is not a constructor or null
I'm new to React and I'm trying to build a static web page to practice.
When I try to open the web page I get this error referring to the App.js file in src folder.

Error1-Image

App.js code below:

```<code>import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component() {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;
</code>```

If I try to import React, {Component} from 'react'
and I use "extends Component" instead of "extends React.Component" I get this error:

Error2-Image

Thank you for your help!

答:
This is you need to do Component not Component()

import React, {Component} from 'react'; // import Component
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];
// Extends Component (not Component())
class App extends Component {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;```

Body:
I'm new to React and I'm trying to build a static web page to practice.
When I try to open the web page I get this error referring to the App.js file in src folder.

Error1-Image

App.js code below:

import React from 'react';
import Task from './task.js'
import Navbar from './js/Navbar';
import MainPage from './js/MainPage';
import './App.css';

const tasks = [];
tasks.push(new Task("finish lab07", 0, 1, "AWI", "2020-05-27", 0));
tasks.push(new Task("finish ", 1, 1, "AWI", "2020/05/30", 0));
tasks.push(new Task("start studyng", 0, 1, "FL", "2020/06/01", 0));

const projects = [{id: 0, projectName: "AWI"}, {id: 1, projectName: "FL"}];

class App extends React.Component() {
     constructor(props){
     super(props);
     this.state = {tasks: tasks};
     }

     render(){
          return (
               <>
                  <Navbar id="navbar" />
                  <MainPage projects={projects} tasks={tasks}/>
               </>
          );
     }
}

export default App;

If I try to import React, {Component} from 'react'
and I use "extends Component" instead of "extends React.Component" I get this error:

Error2-Image

Thank you for your help!


问:
jQuery: How do I check a number from string?
there is a class named:

```<code><div class="level_11 price_level" style="display: block;">
</code>```

I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.

I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.

I need to check the number and say if my number is lower then the number from the level_, then run the script.

```<code>let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1;  // Don't touch this //
let logLevel = Level +1; // Don't touch this //

console.log(`Success ✓ - ${IBuilding.length} buildings left`);

$.each(IBuilding, function(Index, Entity) {
    let BuildingMissing = IBuilding.length - (Index + 1);

    window.setTimeout(function() {
      $.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
      console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success ✓ - last building successfully expanded to level: ' + logLevel }`);

      }, Index * 250);
});
});
</code>```

Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"

Can anyone help me out? :/

答:
You can get the level number like this:

let classname =  $("div[class^='level']").attr("class").split(" ").filter(getClass);

function getClass(value) {
    return value.startsWith("level_");
}
let level = classname.toString().substr(6);
console.log(level);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="level_11 price_level" style="display: block;"></code>```

Body:
there is a class named:

I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.

I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.

I need to check the number and say if my number is lower then the number from the level_, then run the script.

let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1;  // Don't touch this //
let logLevel = Level +1; // Don't touch this //

console.log(`Success ✓ - ${IBuilding.length} buildings left`);

$.each(IBuilding, function(Index, Entity) {
    let BuildingMissing = IBuilding.length - (Index + 1);

    window.setTimeout(function() {
      $.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
      console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success ✓ - last building successfully expanded to level: ' + logLevel }`);

      }, Index * 250);
});
});

Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"

Can anyone help me out? :/

Body:
You can get the level number like this:

let classname =  $("div[class^='level']").attr("class").split(" ").filter(getClass);

function getClass(value) {
    return value.startsWith("level_");
}
let level = classname.toString().substr(6);
console.log(level);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="level_11 price_level" style="display: block;">


问:
Hyperledger fabric facing difficult setting up intermediate CA
I am trying to create intermediate CA for my project, I have one root CA and one intermediate CA with Intermediate CA config file as shown below. I am facing issue to create keypairs/MSP and tls cert for intermediate CA & unable to pass the config file to intermediate CA. Steps I followed

Running the Root CA container with bootstrapping admin.

Enrol the admin which generate the MSP for CA admin for org1

```<code>fabric-ca-client enroll -u https://admin:adminpw@localhost:7054 --caname ca-org1 --tls.certfiles ${PWD}/organizations/fabric-ca/org1/tls-cert.pem
</code>```

Register the Intermediate CA to root CA using below command

```<code>fabric-ca-client register --caname ca-org1 --id.name ica --id.attrs '"hf.Registrar.Roles=user,peer",hf.Revoker=true,hf.IntermediateCA=true' --id.secret icapw --tls.certfiles ${PWD}/organizations/fabric-ca/org1/tls-cert.pem
</code>```

Run the Intermediate CA container as shown below with using the below config file.

Enrol the Intermediate CA

```<code>fabric-ca-client enroll -u https://icaadmin:icaadminpw@localhost:6054 --caname ica-org1 --tls.certfiles ${PWD}/organizations/fabric-ca/icaOrg1/tls-cert.pem
</code>```

Root CA

```<code>version: "2"

networks:
  test:

services:
  ca_org1:
    image: hyperledger/fabric-ca:$IMAGE_TAG
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ca-org1
      - FABRIC_CA_SERVER_TLS_ENABLED=true
      - FABRIC_CA_SERVER_PORT=7054
    ports:
      - "7054:7054"
    command: sh -c 'fabric-ca-server start -b admin:adminpw -d'
    volumes:
      - ../organizations/fabric-ca/org1:/etc/hyperledger/fabric-ca-server
    container_name: ca_org1
    networks:
      - test

</code>```

Intermidate CA

```<code>version: "2"

networks:
  test:

services:
  ica-org1:
    image: hyperledger/fabric-ca
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ica-org1
      - FABRIC_CA_SERVER_TLS_ENABLED=true
      - FABRIC_LOGGING_SPEC=debug
      - FABRIC_CA_SERVER_PORT=6054
    ports:
      - "6054:6054"
    command: sh -c 'fabric-ca-server start  -b icaadmin:icaadminpw -u -d http://ica:icapw@ca-org1:7054'
    volumes:
      - ../organizations/fabric-ca/icaOrg1:/etc/hyperledger/fabric-ca-server
    container_name: ica-org1
    networks:
     - test
</code>```

ICA Fabric Config file

```<code>

# Version of config file
version: 1.2.0

# Server's listening port (default: 7054)
port: 7054

# Enables debug logging (default: false)
debug: false

# Size limit of an acceptable CRL in bytes (default: 512000)
crlsizelimit: 512000

tls:
  # Enable TLS (default: false)
  enabled: true
  # TLS for the server's listening port
  certfile:
  keyfile:
  clientauth:
    type: noclientcert
    certfiles:

ca:
  # Name of this CA
  name: ica.org1.example.com
  # Key file (is only used to import a private key into BCCSP)
  keyfile:
  # Certificate file (default: ca-cert.pem)
  certfile:
  # Chain file
  chainfile:

crl:
  # Specifies expiration for the generated CRL. The number of hours
  # specified by this property is added to the UTC time, the resulting time
  # is used to set the 'Next Update' date of the CRL.
  expiry: 24h

registry:
  # Maximum number of times a password/secret can be reused for enrollment
  # (default: -1, which means there is no limit)
  maxenrollments: -1

  # Contains identity information which is used when LDAP is disabled
  identities:
    - name: icaadmin
      pass: icaadminpw
      type: client
      affiliation: ""
      attrs:
        hf.Registrar.Roles: "client,peer,user,member"
        hf.Registrar.DelegateRoles: "client,peer,user,member"
        hf.Revoker: true
        hf.IntermediateCA: true
        hf.GenCRL: true
        hf.Registrar.Attributes: "*"
        hf.AffiliationMgr: true

db:
  type: sqlite3
  datasource: fabric-ca-server.db
  tls:
    enabled: false
    certfiles:
    client:
      certfile:
      keyfile:

ldap:
  # Enables or disables the LDAP client (default: false)
  # If this is set to true, the "registry" section is ignored.
  enabled: false
  # The URL of the LDAP server
  url: ldap://<adminDN>:<adminPassword>@<host>:<port>/<base>
  # TLS configuration for the client connection to the LDAP server
  tls:
    certfiles:
    client:
      certfile:
      keyfile:
  # Attribute related configuration for mapping from LDAP entries to Fabric CA attributes
  attribute:

    names: ["uid", "member"]
    converters:
      - name:
        value:
    maps:
      groups:
        - name:
          value:

affiliations:
  org1:
    - department1
    - department2

signing:
  default:
    usage:
      - digital signature
    expiry: 8760h
  profiles:
    ca:
      usage:
        - cert sign
        - crl sign
      expiry: 43800h
      caconstraint:
        isca: true
        maxpathlen: 0
    tls:
      usage:
        - signing
        - key encipherment
        - server auth
        - client auth
        - key agreement
      expiry: 8760h

csr:
  cn: ica.org1.example.com
  names:
    - C: US
      ST: "North Carolina"
      L: "Durham"
      O: org1.example.com
      OU:
  hosts:
    - localhost
    - org1.example.com
  ca:
    expiry: 131400h
    pathlength: 1

#############################################################################
# BCCSP (BlockChain Crypto Service Provider) section is used to select which
# crypto library implementation to use
#############################################################################
bccsp:
  default: SW
  sw:
    hash: SHA2
    security: 256
    filekeystore:
      # The directory used for the software file-based keystore
      keystore: msp/keystore

cacount:
cafiles:

intermediate:
  parentserver:
    url: https://ca-org1:7054
    caname: ca.org1.example.com

  enrollment:
    hosts: localhost
    profile:
    label:

  tls:
    certfiles:
    client:
      certfile:
      keyfile:

</code>```

答:
Since you configured your CAs as TLS enabled, root TLS certificate must be used by  intermediate CA. Check your intermediate CA file's corresponding section.

The certfiles attribute's value /tmp/root-ca-cert.pem is the same file of root CA's file: /tmp/hyperledger/fabric-ca/crypto/ca-cert.pem

```<code>intermediate:
  parentserver:
    url: https://admin:admin@root.ca.example.com:7054
    caname: root.ca.example.com

  enrollment:
    hosts:
      - ca1.example.com
    profile: ca
    label:

  tls:
    certfiles:
      - /tmp/root-ca-cert.pem
    client:
      certfile:
      keyfile:
</code>```

Body:
I am trying to create intermediate CA for my project, I have one root CA and one intermediate CA with Intermediate CA config file as shown below. I am facing issue to create keypairs/MSP and tls cert for intermediate CA & unable to pass the config file to intermediate CA. Steps I followed

Running the Root CA container with bootstrapping admin.

Enrol the admin which generate the MSP for CA admin for org1

fabric-ca-client enroll -u https://admin:adminpw@localhost:7054 --caname ca-org1 --tls.certfiles ${PWD}/organizations/fabric-ca/org1/tls-cert.pem

Register the Intermediate CA to root CA using below command

fabric-ca-client register --caname ca-org1 --id.name ica --id.attrs '"hf.Registrar.Roles=user,peer",hf.Revoker=true,hf.IntermediateCA=true' --id.secret icapw --tls.certfiles ${PWD}/organizations/fabric-ca/org1/tls-cert.pem

Run the Intermediate CA container as shown below with using the below config file.

Enrol the Intermediate CA

fabric-ca-client enroll -u https://icaadmin:icaadminpw@localhost:6054 --caname ica-org1 --tls.certfiles ${PWD}/organizations/fabric-ca/icaOrg1/tls-cert.pem

Root CA

version: "2"

networks:
  test:

services:
  ca_org1:
    image: hyperledger/fabric-ca:$IMAGE_TAG
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ca-org1
      - FABRIC_CA_SERVER_TLS_ENABLED=true
      - FABRIC_CA_SERVER_PORT=7054
    ports:
      - "7054:7054"
    command: sh -c 'fabric-ca-server start -b admin:adminpw -d'
    volumes:
      - ../organizations/fabric-ca/org1:/etc/hyperledger/fabric-ca-server
    container_name: ca_org1
    networks:
      - test

Intermidate CA

version: "2"

networks:
  test:

services:
  ica-org1:
    image: hyperledger/fabric-ca
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ica-org1
      - FABRIC_CA_SERVER_TLS_ENABLED=true
      - FABRIC_LOGGING_SPEC=debug
      - FABRIC_CA_SERVER_PORT=6054
    ports:
      - "6054:6054"
    command: sh -c 'fabric-ca-server start  -b icaadmin:icaadminpw -u -d http://ica:icapw@ca-org1:7054'
    volumes:
      - ../organizations/fabric-ca/icaOrg1:/etc/hyperledger/fabric-ca-server
    container_name: ica-org1
    networks:
     - test

ICA Fabric Config file

# Version of config file
version: 1.2.0

# Server's listening port (default: 7054)
port: 7054

# Enables debug logging (default: false)
debug: false

# Size limit of an acceptable CRL in bytes (default: 512000)
crlsizelimit: 512000

tls:
  # Enable TLS (default: false)
  enabled: true
  # TLS for the server's listening port
  certfile:
  keyfile:
  clientauth:
    type: noclientcert
    certfiles:

ca:
  # Name of this CA
  name: ica.org1.example.com
  # Key file (is only used to import a private key into BCCSP)
  keyfile:
  # Certificate file (default: ca-cert.pem)
  certfile:
  # Chain file
  chainfile:

crl:
  # Specifies expiration for the generated CRL. The number of hours
  # specified by this property is added to the UTC time, the resulting time
  # is used to set the 'Next Update' date of the CRL.
  expiry: 24h

registry:
  # Maximum number of times a password/secret can be reused for enrollment
  # (default: -1, which means there is no limit)
  maxenrollments: -1

  # Contains identity information which is used when LDAP is disabled
  identities:
    - name: icaadmin
      pass: icaadminpw
      type: client
      affiliation: ""
      attrs:
        hf.Registrar.Roles: "client,peer,user,member"
        hf.Registrar.DelegateRoles: "client,peer,user,member"
        hf.Revoker: true
        hf.IntermediateCA: true
        hf.GenCRL: true
        hf.Registrar.Attributes: "*"
        hf.AffiliationMgr: true

db:
  type: sqlite3
  datasource: fabric-ca-server.db
  tls:
    enabled: false
    certfiles:
    client:
      certfile:
      keyfile:

ldap:
  # Enables or disables the LDAP client (default: false)
  # If this is set to true, the "registry" section is ignored.
  enabled: false
  # The URL of the LDAP server
  url: ldap://<adminDN>:<adminPassword>@<host>:<port>/<base>
  # TLS configuration for the client connection to the LDAP server
  tls:
    certfiles:
    client:
      certfile:
      keyfile:
  # Attribute related configuration for mapping from LDAP entries to Fabric CA attributes
  attribute:

    names: ["uid", "member"]
    converters:
      - name:
        value:
    maps:
      groups:
        - name:
          value:

affiliations:
  org1:
    - department1
    - department2

signing:
  default:
    usage:
      - digital signature
    expiry: 8760h
  profiles:
    ca:
      usage:
        - cert sign
        - crl sign
      expiry: 43800h
      caconstraint:
        isca: true
        maxpathlen: 0
    tls:
      usage:
        - signing
        - key encipherment
        - server auth
        - client auth
        - key agreement
      expiry: 8760h

csr:
  cn: ica.org1.example.com
  names:
    - C: US
      ST: "North Carolina"
      L: "Durham"
      O: org1.example.com
      OU:
  hosts:
    - localhost
    - org1.example.com
  ca:
    expiry: 131400h
    pathlength: 1

#############################################################################
# BCCSP (BlockChain Crypto Service Provider) section is used to select which
# crypto library implementation to use
#############################################################################
bccsp:
  default: SW
  sw:
    hash: SHA2
    security: 256
    filekeystore:
      # The directory used for the software file-based keystore
      keystore: msp/keystore

cacount:
cafiles:

intermediate:
  parentserver:
    url: https://ca-org1:7054
    caname: ca.org1.example.com

  enrollment:
    hosts: localhost
    profile:
    label:

  tls:
    certfiles:
    client:
      certfile:
      keyfile:

Body:
Since you configured your CAs as TLS enabled, root TLS certificate must be used by  intermediate CA. Check your intermediate CA file's corresponding section.

The certfiles attribute's value /tmp/root-ca-cert.pem is the same file of root CA's file: /tmp/hyperledger/fabric-ca/crypto/ca-cert.pem

intermediate:
  parentserver:
    url: https://admin:admin@root.ca.example.com:7054
    caname: root.ca.example.com

  enrollment:
    hosts:
      - ca1.example.com
    profile: ca
    label:

  tls:
    certfiles:
      - /tmp/root-ca-cert.pem
    client:
      certfile:
      keyfile:


问:
difficulty connecting to SQL Server database inside a docker container using Sequelize
I have an SQL Server Docker image called microsoft/mssql-server-linux which was used to spin up an SQL Server database.  I have an API which I made outside of Docker and I've unsuccessfully tried to construct a connection string to connect to this database.

I have successfully connected to this database using Azure Data Studio just with the following connection settings

```<code>Connection Type: Microsoft SQL Server
Server: localhost
Username: (username I created)
Password: (password I created)
</code>```

I created an API project using Feathersjs and am using sequelize as an ORM.  Here is how I've been trying to create the connection.

```<code>  const sequelize = new Sequelize(database, username, password, {
    dialect: "mssql",
    host: localhost,
    encrypt: false,
    logging: false,
    operatorsAliases: false,
    define: {
      freezeTableName: true
    },
    dialectOptions: {
      port: 1433
      // instanceName: "NameOfTheMSSQLInstance"
    }
  });
</code>```

I'm using port 1433 because when I ran 'docker ps' in the terminal, it had this information listed under port.

```<code> 0.0.0.0:1433->1433/tcp
</code>```

I know the username/password are correct because I'm successfully connecting through Azure Data Studio and have changed them in a docker a few times just to make sure it wasn't a credentials issue.

I'm getting the following error message when trying to connect

error: Unhandled Rejection at: Promise  {"_bitField":18087936,"_fulfillmentHandler0":{"name":"SequelizeConnectionError","parent":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"},"original":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"}},"name":"SequelizeConnectionError","parent":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"},"original":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"}}
  error: GeneralError: Failed to connect to 172.17.0.2:1433 in 15000ms

答:
Late to the party but I used your question to fix my errors and it works now so I thought I'd share

I ran the MSSQL DB locally on Docker with:

```<code>docker run --name sql_server_demo -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=1Secure*Password1' -e 'MSSQL_PID=Developer' -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest
</code>```

To connect to it via sequelize, I created an 'environment' as follows:

```<code>"mssql": {
   "username": "sa",
   "password": "1Secure*Password1",
   "database": "master",
   "host": "127.0.0.1",
   "dialect": "mssql"
}
</code>```

This allowed me to run my migrations as my .sequelizerc file used that same environment:

```<code>// .sequelizerc

const path = require('path');

module.exports = {
    'env': 'mssql',
    'config': path.resolve('src/config/env', 'sequelize_db.json'),
    'models-path': path.resolve('src', 'models'),
    'seeders-path': path.resolve('src', 'seeders'),
    'migrations-path': path.resolve('src', 'migrations')
};
</code>```

then at run-time I configured the sequelize as follows (note that I used a config set up in my Nodejs server to just pull variables from the sequelize environment file, but I replaced them here):

```<code>this.sequelize = new Sequelize('master',  'sa', '1Secure*Password1', {
      host: '127.0.0.1',
      dialect: 'mssql',
      encrypt: false,
      define: {
            freezeTableName: true
      },
      dialectOptions: {
             port: 1433
      }
});
</code>```

Keep in mind I'm new to MSSQL, and this might not be the best way to do it, but I'm just happy I finally got it working

Cheers!

Body:
I have an SQL Server Docker image called microsoft/mssql-server-linux which was used to spin up an SQL Server database.  I have an API which I made outside of Docker and I've unsuccessfully tried to construct a connection string to connect to this database.

I have successfully connected to this database using Azure Data Studio just with the following connection settings

Connection Type: Microsoft SQL Server
Server: localhost
Username: (username I created)
Password: (password I created)

I created an API project using Feathersjs and am using sequelize as an ORM.  Here is how I've been trying to create the connection.

  const sequelize = new Sequelize(database, username, password, {
    dialect: "mssql",
    host: localhost,
    encrypt: false,
    logging: false,
    operatorsAliases: false,
    define: {
      freezeTableName: true
    },
    dialectOptions: {
      port: 1433
      // instanceName: "NameOfTheMSSQLInstance"
    }
  });

I'm using port 1433 because when I ran 'docker ps' in the terminal, it had this information listed under port.

 0.0.0.0:1433->1433/tcp

I know the username/password are correct because I'm successfully connecting through Azure Data Studio and have changed them in a docker a few times just to make sure it wasn't a credentials issue.

I'm getting the following error message when trying to connect

error: Unhandled Rejection at: Promise  {"_bitField":18087936,"_fulfillmentHandler0":{"name":"SequelizeConnectionError","parent":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"},"original":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"}},"name":"SequelizeConnectionError","parent":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"},"original":{"message":"Failed to connect to 172.17.0.2:1433 in 15000ms","code":"ETIMEOUT"}}
  error: GeneralError: Failed to connect to 172.17.0.2:1433 in 15000ms

Body:
Late to the party but I used your question to fix my errors and it works now so I thought I'd share

I ran the MSSQL DB locally on Docker with:

docker run --name sql_server_demo -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=1Secure*Password1' -e 'MSSQL_PID=Developer' -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest

To connect to it via sequelize, I created an 'environment' as follows:

"mssql": {
   "username": "sa",
   "password": "1Secure*Password1",
   "database": "master",
   "host": "127.0.0.1",
   "dialect": "mssql"
}

This allowed me to run my migrations as my .sequelizerc file used that same environment:

// .sequelizerc

const path = require('path');

module.exports = {
    'env': 'mssql',
    'config': path.resolve('src/config/env', 'sequelize_db.json'),
    'models-path': path.resolve('src', 'models'),
    'seeders-path': path.resolve('src', 'seeders'),
    'migrations-path': path.resolve('src', 'migrations')
};

then at run-time I configured the sequelize as follows (note that I used a config set up in my Nodejs server to just pull variables from the sequelize environment file, but I replaced them here):

this.sequelize = new Sequelize('master',  'sa', '1Secure*Password1', {
      host: '127.0.0.1',
      dialect: 'mssql',
      encrypt: false,
      define: {
            freezeTableName: true
      },
      dialectOptions: {
             port: 1433
      }
});

Keep in mind I'm new to MSSQL, and this might not be the best way to do it, but I'm just happy I finally got it working

Cheers!


问:
response.redirect() with parameters
I want to redirect to a page where the path is like /users/home/:id

```<code>   response.redirect('/users/home')
</code>```

The above code will redirect to /users/home but I want to redirect it to a page like '/users/home/1' dynamically with parameters. How shall I solve it?Do explain with some examples

答:
You could use template literals to form the new url, for example: </p>

```<code>app.get("/users/home/:id", (req, res) => {
    res.redirect(`/users/alternate_home/${req.params.id}`);
});

app.get("/users/alternate_home/:id", (req, res) => {
    res.json(users);
});
</code>```

Title: response.redirect() with parameters

Body:
I want to redirect to a page where the path is like /users/home/:id

   response.redirect('/users/home')

The above code will redirect to /users/home but I want to redirect it to a page like '/users/home/1' dynamically with parameters. How shall I solve it?Do explain with some examples

Body:
You could use template literals to form the new url, for example:

app.get("/users/home/:id", (req, res) => {
    res.redirect(`/users/alternate_home/${req.params.id}`);
});

app.get("/users/alternate_home/:id", (req, res) => {
    res.json(users);
});


问:
Pandas : select columns that ends with another column
I am working on a dirty dataset where two columnns that I need to match are not properly formatted :

"id" is a string often made of digits, that potentially starts with zero

"parent_id" represents the id of the parent of the row, but it has been formatted to an int, and so the starting zeros are gone.

I want to find for which rows "id" is the same as "parent_id".  However, I cannot manage to match it like this :

```<code>df["is_the_same"] = (df["id"]==df["parent_id"])
</code>```

cause some of them would not match  (for example, the id "01004" has "1004" as parent_id, and would not match in this case)

How can I select columns that have "id" equal to "parent_id" once potential zeroes have been removed ?

I also tried :

```<code>df["is_the_same"] = df["id"].str.endswith(df["parent_id"])
</code>```

But it seems .str.endswith  only work with constant strings (another column)

答:
Using Series.lstrip, you can strip off leading zeros from id column and then match it with parent_id column, like this:

```<code>df["id"].str.lstrip('0') == df["parent_id"]
</code>```

Assume this to be df:

```<code>In [68]: df
Out[68]:
      id parent_id
0  01004      1004
1   1004      1004
2    546       100

In [70]: df["is_the_same"] = df["id"].str.lstrip('0') == df["parent_id"]
In [71]: df
Out[71]:
      id parent_id  is_the_same
0  01004      1004         True
1   1004      1004         True
2    546       100        False
</code>```

Body:
I am working on a dirty dataset where two columnns that I need to match are not properly formatted :

"id" is a string often made of digits, that potentially starts with zero

"parent_id" represents the id of the parent of the row, but it has been formatted to an int, and so the starting zeros are gone.

I want to find for which rows "id" is the same as "parent_id".  However, I cannot manage to match it like this :

df["is_the_same"] = (df["id"]==df["parent_id"])

cause some of them would not match  (for example, the id "01004" has "1004" as parent_id, and would not match in this case)

How can I select columns that have "id" equal to "parent_id" once potential zeroes have been removed ?

I also tried :

df["is_the_same"] = df["id"].str.endswith(df["parent_id"])

But it seems .str.endswith  only work with constant strings (another column)

Body:
Using Series.lstrip, you can strip off leading zeros from id column and then match it with parent_id column, like this:

df["id"].str.lstrip('0') == df["parent_id"]

Assume this to be df:

In [68]: df
Out[68]:
      id parent_id
0  01004      1004
1   1004      1004
2    546       100

In [70]: df["is_the_same"] = df["id"].str.lstrip('0') == df["parent_id"]
In [71]: df
Out[71]:
      id parent_id  is_the_same
0  01004      1004         True
1   1004      1004         True
2    546       100        False


问:
Adding reversed previous number to achieve palindrome in python
Accept a number as an input and check whether the given number is palindrome or not
if it is a palindrome number print the number on the screen
if it is not a palindrome number reverse that number and add it to previous number repeat this until will get a palindrome number and print that palindrome number on the screen

input: 127

output: 848

I will be thank full if any one can solve this:

```<code>    n = int(input())
    if str(n) == str(n)[::-1]:
        print(str(n)[::-1],"is a palindrome")
    else:

</code>```

what should i write in else condition

答:
This works for me:</p>

```<code>n = int(input())
while True :
    if str(n) == str(n)[::-1]:
        print(str(n)[::-1],"is a palindrome")
        break
    else:
        n += int(str(n)[::-1])
</code>```

Body:
Accept a number as an input and check whether the given number is palindrome or not
if it is a palindrome number print the number on the screen
if it is not a palindrome number reverse that number and add it to previous number repeat this until will get a palindrome number and print that palindrome number on the screen

input: 127

output: 848

I will be thank full if any one can solve this:

    n = int(input())
    if str(n) == str(n)[::-1]:
        print(str(n)[::-1],"is a palindrome")
    else:

what should i write in else condition

Body:
This works for me:

n = int(input())
while True :
    if str(n) == str(n)[::-1]:
        print(str(n)[::-1],"is a palindrome")
        break
    else:
        n += int(str(n)[::-1])


问:
Looking for setting which makes virtual user and samples count same in Blazemeter
I just ran a simple load test on BlazeMeter with 4 virtual users but after complete, I can see in request states samples not equal to no. of virtual users :

If we look at the above screenshot, It shows no. of samples. Do I need any specific setting in BlazeMeter to make my Samples count the same as no. of users?

I want to set like if I run test with 4 users then I would see only 4 samples per request in states. Because in actual it is sending 1 request per user as far as I understand.

Looks like I could not find where is the setting for Loop Count in BlazeMeter. I think Loop count can help me to get what I want but still looking for a better solution.

答:
Seems Blazemeter is showing the correct results, but you configured the test to run for more than 1 iteration.

If you are looking to run the test for a specific amount of iterations, go to test configuration and click on iterations (next to duration). This option will let you decide the number of iteration for each thread till the test stops instead of running the test for x minutes.


问:
Reproduce same graph in NetworkX
I would like to improve my graph.
There are problems as follow:

how to create a consistent graph.the graph itself is not consistent everytime i execute / run the code, it will generate different images. The inconsistent graph is shown in the url.

how to customize the whole graph / picture size and to make it bigger

how to set a permanent position for an object 'a' so that it will consistently appears at the first / top position

how to customize length of arrow for each relationship.

Appreciate if anyone could give some notes or advices

This is my codes:

```<code>Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(Unique_liss)
g.add_edges_from(edgesList)
nx.to_pandas_adjacency(g)

G = nx.DiGraph()
for node in edgesList:
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A

nx.draw(G, with_labels=True, node_size = 2000,
        node_color = 'skyblue')
</code>```

答:
In order to have deterministic node layouts, you can use one of NetworkX's layouts, which allow you to specify a seed. Here's an example using nx.spring_layout for the above graph:

```<code>from matplotlib import pyplot as plt

seed = 31
pos = nx.spring_layout(G, seed=seed)
plt.figure(figsize=(10,6))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500, node_color = 'skyblue')
</code>```

You'll get the exact same layout if you re-run the above.

In order to customize the graph size you have several options. The simplest one baing setting the figure size as plt.figure(figsize=(x,y)) as above. And you can also control the size of the graph within the figure using the scale paramater in nx.spring_layout.

As per the last point, it looks like you cannot set specific arrow sizes for each edge. From the [docs](arrowsize : int, optional (default=10)) what you have is:

arrowsize : int, optional (default=10)

So you can only set this value to an int, which will result in an equal size for all edge arrows.

Title: Reproduce same graph in NetworkX

Body:
I would like to improve my graph.
There are problems as follow:

how to create a consistent graph.the graph itself is not consistent everytime i execute / run the code, it will generate different images. The inconsistent graph is shown in the url.

how to customize the whole graph / picture size and to make it bigger

how to set a permanent position for an object 'a' so that it will consistently appears at the first / top position

how to customize length of arrow for each relationship.

Appreciate if anyone could give some notes or advices

This is my codes:

Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(Unique_liss)
g.add_edges_from(edgesList)
nx.to_pandas_adjacency(g)

G = nx.DiGraph()
for node in edgesList:
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A

nx.draw(G, with_labels=True, node_size = 2000,
        node_color = 'skyblue')

Body:
In order to have deterministic node layouts, you can use one of NetworkX's layouts, which allow you to specify a seed. Here's an example using nx.spring_layout for the above graph:

from matplotlib import pyplot as plt

seed = 31
pos = nx.spring_layout(G, seed=seed)
plt.figure(figsize=(10,6))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500, node_color = 'skyblue')

You'll get the exact same layout if you re-run the above.

In order to customize the graph size you have several options. The simplest one baing setting the figure size as plt.figure(figsize=(x,y)) as above. And you can also control the size of the graph within the figure using the scale paramater in nx.spring_layout.

As per the last point, it looks like you cannot set specific arrow sizes for each edge. From the [docs](arrowsize : int, optional (default=10)) what you have is:

arrowsize : int, optional (default=10)

So you can only set this value to an int, which will result in an equal size for all edge arrows.