问:
how can I save editText visibility state (View.GONE)?
I have a problem with editText visibility. In the beginning of my code I've set visibility to GONE

```<code>editText.setVisibility(View.GONE);
</code>```

This part is fine, it sets my editText to GONE. However if i minimise my app and then summon it again, editText field becomes Visible. I've tried to save View setting with SharedPreferences, but i don't know how to do it right.
I am trying to save View with:

```<code>myPrefs = getSharedPreferences("save steps", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("visibility", editText.getVisibility());
editor.commit();
</code>```

And then load data back with:

```<code>editText.setVisibility(myPrefs.getInt("visibility", 0));
</code>```

But this approach crashes my app. Maybe there are any suggestions how to solve this?

答:
The reason is simple. When app come back from background, activity restarts (recreate your edittext).

You can use savedInstanceState or put

```<code>@Override
public void onResume(){
    super.onResume();
    edittext.setVisibility(View.GONE);
}
</code>```

EDIT:
Change:

```<code>editText.setVisibility(myPrefs.getInt("visibility", 0));
</code>```

to

```<code>editText.setVisibility(myPrefs.getInt("visibility", View.GONE));
</code>```

I can't see the entire code, maybe app crash is caused by null pointer exception..

Body:
I have a problem with editText visibility. In the beginning of my code I've set visibility to GONE

editText.setVisibility(View.GONE);

This part is fine, it sets my editText to GONE. However if i minimise my app and then summon it again, editText field becomes Visible. I've tried to save View setting with SharedPreferences, but i don't know how to do it right.
I am trying to save View with:

myPrefs = getSharedPreferences("save steps", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("visibility", editText.getVisibility());
editor.commit();

And then load data back with:

editText.setVisibility(myPrefs.getInt("visibility", 0));

But this approach crashes my app. Maybe there are any suggestions how to solve this?

Body:
The reason is simple. When app come back from background, activity restarts (recreate your edittext).

You can use savedInstanceState or put

@Override
public void onResume(){
    super.onResume();
    edittext.setVisibility(View.GONE);
}

EDIT:
Change:

editText.setVisibility(myPrefs.getInt("visibility", 0));

to

editText.setVisibility(myPrefs.getInt("visibility", View.GONE));

I can't see the entire code, maybe app crash is caused by null pointer exception..


来源: stackexchange

问:
How to write GQL `CONTAINS` comparator query in objectify
I use google cloud datastore to store and objectify to read the data. The entity that i use holds a list property and i would like to filter the records through multiple values and the results should be returned only if all the values are present in the list

GQL now supports CONTAINS query filter link here . I would like to know how this can be achieved in objectify

Assuming there are three entities that holds a list field

```<code>(Entity1) => list = ["id1","id2","id3","id4"]
(Entity2) => list = ["id1","id2","id3"]
(Entity3) => list = ["id1"]
queryList = ["id1","id2"]
</code>```

How do i write an objectify query that uses contains. For example,  ofy().load().type( Entity.class ).filter( "list contains" , queryList ).list(); so that only entities 1 and 2 are returned

I am familiar that IN filter ofy().load().type( Entity.class ).filter( "list in" , queryList ).list();
 will return all three entities.
But the requirement is to fetch only entities that has both id1 and id2

答: You'll want to use an AND query, which should be ...filter("list", "id1").filter("list", "id2")

ContentLicense: CC BY-SA 4.0

Body:
I use google cloud datastore to store and objectify to read the data. The entity that i use holds a list property and i would like to filter the records through multiple values and the results should be returned only if all the values are present in the list

GQL now supports CONTAINS query filter link here . I would like to know how this can be achieved in objectify

Assuming there are three entities that holds a list field

(Entity1) => list = ["id1","id2","id3","id4"]
(Entity2) => list = ["id1","id2","id3"]
(Entity3) => list = ["id1"]
queryList = ["id1","id2"]

How do i write an objectify query that uses contains. For example,  ofy().load().type( Entity.class ).filter( "list contains" , queryList ).list(); so that only entities 1 and 2 are returned

I am familiar that IN filter ofy().load().type( Entity.class ).filter( "list in" , queryList ).list();
 will return all three entities.
But the requirement is to fetch only entities that has both id1 and id2


问:
How do I get user entitlements to persist across conversations
I am trying to see if a user has purchased a product by checking conv.user.entitlements but except for immediately after purchase, this is empty.

This value seemed to be persisting between conversations previously, now it is always empty. I am able to see the entitlement using conv.user.entitlements immediately after purchase, but then it is gone.

```<code> if (arg.purchaseStatus === 'PURCHASE_STATUS_OK') {
 console.log('purchase2 ', conv.user.entitlements);
//this works as expected showing the entitlement
</code>```

In the logs I see:  purchase2  [ { entitlements: [ [Object] ],
    packageName: 'com.chad.myfirstapp' } ]

But when I try to log the same in the next conversation, I get:

purchase2 [ ]

答:
While the conv.user object is capable of storing data across conversations, there are both technical and legal limitations to keep in mind, documented here.

When the Assistant can match an identity to the user, the contents of user storage never expires, and only the user or the Action itself can clear it.

When the Assistant can't match an identity to the user, the content of user storage is cleared at the end of the conversation. Examples of cases where the Assistant can't match an identity to the user are:

Voice match is set up and there is no match.

The user disabled personal data.

In addition to the conv.user object, you can also store data in your preferred database. This Github sample demonstrates how to connect Dialogflow to a Firebase Firestore database.
You can find the write function here:

```<code>  function writeToDb (agent) {

    // Get parameter from Dialogflow with the string to add to the database
    const databaseEntry = agent.parameters.databaseEntry;

    // Get the database collection 'dialogflow' and document 'agent' and store
    // the document  {entry: "<value of database entry>"} in the 'agent' document
    const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
    return db.runTransaction(t => {
      t.set(dialogflowAgentRef, {entry: databaseEntry});
      return Promise.resolve('Write complete');
    }).then(doc => {
      agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
    }).catch(err => {
      console.log(`Error writing to Firestore: ${err}`);
      agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
    });
  }
</code>```

Body:
I am trying to see if a user has purchased a product by checking conv.user.entitlements but except for immediately after purchase, this is empty.

This value seemed to be persisting between conversations previously, now it is always empty. I am able to see the entitlement using conv.user.entitlements immediately after purchase, but then it is gone.

 if (arg.purchaseStatus === 'PURCHASE_STATUS_OK') {
 console.log('purchase2 ', conv.user.entitlements);
//this works as expected showing the entitlement

In the logs I see:  purchase2  [ { entitlements: [ [Object] ],
    packageName: 'com.chad.myfirstapp' } ]

But when I try to log the same in the next conversation, I get:

purchase2 [ ]

Body:
While the conv.user object is capable of storing data across conversations, there are both technical and legal limitations to keep in mind, documented here.

When the Assistant can match an identity to the user, the contents of user storage never expires, and only the user or the Action itself can clear it.

When the Assistant can't match an identity to the user, the content of user storage is cleared at the end of the conversation. Examples of cases where the Assistant can't match an identity to the user are:

Voice match is set up and there is no match.

The user disabled personal data.

In addition to the conv.user object, you can also store data in your preferred database. This Github sample demonstrates how to connect Dialogflow to a Firebase Firestore database.
You can find the write function here:

  function writeToDb (agent) {

    // Get parameter from Dialogflow with the string to add to the database
    const databaseEntry = agent.parameters.databaseEntry;

    // Get the database collection 'dialogflow' and document 'agent' and store
    // the document  {entry: "<value of database entry>"} in the 'agent' document
    const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
    return db.runTransaction(t => {
      t.set(dialogflowAgentRef, {entry: databaseEntry});
      return Promise.resolve('Write complete');
    }).then(doc => {
      agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
    }).catch(err => {
      console.log(`Error writing to Firestore: ${err}`);
      agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
    });
  }


问:
Order of evaluation of [in]equality operator in C++?
What is the order of evaluation of the equality operator in C++ ?

I see many code examples like this

```<code>template <class ForwardIt, class Compare>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last, Compare comp)
{
    if (first != last) {
        ForwardIt next = first;
        while (++next != last) {
            if (comp(*next, *first))
                return next;
            first = next;
        }
    }
    return last;
}
</code>```

and in the while (++next != last)
 - is the left side evaluated before the right side?

答: The order is unspecified, like most binary operators in C++. It's perfectly legal for the compiler to evaluate ++next or last first, so if next and last were references to the same underlying variable, you'd be entering undefined behavior territory (in this case, there is no problem).

Body:
What is the order of evaluation of the equality operator in C++ ?

I see many code examples like this

template <class ForwardIt, class Compare>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last, Compare comp)
{
    if (first != last) {
        ForwardIt next = first;
        while (++next != last) {
            if (comp(*next, *first))
                return next;
            first = next;
        }
    }
    return last;
}

and in the while (++next != last)
 - is the left side evaluated before the right side?


问:
Can ActorContext (getContext()) be passed outside the Actor to create child actors?
I want to have an ActorFactory class as below

public class SampleActorFactory {
  // Simple create method
  public createActor(AbstractActor.ActorContext actorContext, Props props) {
     return actorContext.actorOf(props);
  }
 // other complex create methods
 ...
}
```

<p>Is it ok to create a child actor using the above factory class, or is this considered a bad practice? If considered bad practice, then why?</p>

<p>eg:</p>

<pre class="lang-java prettyprint-override"><code>public class SampleActor extends AbstractActor {
 private final SampleActorFactory sampleActorFactory;
 @Override
 public Receive createReceive() {
        return receiveBuilder()
            .match(SampleData.class, sampleData -> {
              Props sampleProps = getSampleProps(...);
              ActorRef childActor = sampleActorFactory.createActor(getContext(), sampleProps);
            })
            .build();

    }
}
</code>```

答:
I don't see anything wrong with that approach, you should be able to access context outside of actor system. But.... generally to create an actor, you just need one line of code as below. With your code, you have to write two lines of code (one for Props and other one to call your createActor() method) where ever you create an actor. Other than implementing a factory method, if you achieve any additional benefit from it, you can go for it.</p>

```<code>ActorRef demoActor = getContext().system().actorOf(Props.create(MyDemoActor.class, prop1, prop2);
</code>```

Body:
I want to have an ActorFactory class as below

public class SampleActorFactory {
  // Simple create method
  public createActor(AbstractActor.ActorContext actorContext, Props props) {
     return actorContext.actorOf(props);
  }
 // other complex create methods
 ...
}

Is it ok to create a child actor using the above factory class, or is this considered a bad practice? If considered bad practice, then why?

eg:

public class SampleActor extends AbstractActor {
 private final SampleActorFactory sampleActorFactory;
 @Override
 public Receive createReceive() {
        return receiveBuilder()
            .match(SampleData.class, sampleData -> {
              Props sampleProps = getSampleProps(...);
              ActorRef childActor = sampleActorFactory.createActor(getContext(), sampleProps);
            })
            .build();

    }
}

Body:
I don't see anything wrong with that approach, you should be able to access context outside of actor system. But.... generally to create an actor, you just need one line of code as below. With your code, you have to write two lines of code (one for Props and other one to call your createActor() method) where ever you create an actor. Other than implementing a factory method, if you achieve any additional benefit from it, you can go for it.

ActorRef demoActor = getContext().system().actorOf(Props.create(MyDemoActor.class, prop1, prop2);


问:
Javascript Import Don't Work In Visual Studio Code
I can't import anything in my javascript files of my website, I've tried many things but it doesn't work.

So I want to import a .json file to a .js file using the import key word but it doesn't work. Another problem is that Visual Studio Code doesn't show me an error but the console does...

main.js import part

```<code>import dropDownList from "./navigationList.json"; //This is line number 1

console.log(dropDownList.shop.kits);
</code>```

navigationList.json file

```<code>{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}
</code>```

Error the console is showing:

mainJS.js:1 Uncaught SyntaxError: Unexpected identifier

The console says there is an Uncaught SyntaxError with my import and this causing me to make my code long and without import which sucks.
Please help me

答:
navigation_list.json

```<code>{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}
</code>```

main.js

```<code>var navigation_list = require('./navigation_list.json');
console.log(`>>>> Returned JSON data: ${navigation_list.shop.kits}`);
</code>```

End the output here:

Body:
I can't import anything in my javascript files of my website, I've tried many things but it doesn't work.

So I want to import a .json file to a .js file using the import key word but it doesn't work. Another problem is that Visual Studio Code doesn't show me an error but the console does...

main.js import part

import dropDownList from "./navigationList.json"; //This is line number 1

console.log(dropDownList.shop.kits);

navigationList.json file

{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}

Error the console is showing:

mainJS.js:1 Uncaught SyntaxError: Unexpected identifier

The console says there is an Uncaught SyntaxError with my import and this causing me to make my code long and without import which sucks.
Please help me

Body:
navigation_list.json

{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}

main.js

var navigation_list = require('./navigation_list.json');
console.log(`>>>> Returned JSON data: ${navigation_list.shop.kits}`);

End the output here:


问:
how to format my text dataset for training?
I'm new to python and machine learning,
I'm working on training a chatbot

I collected (or wrote) large number of possible inputs in an excel file (.xlsx), I will train my dataset using LSTM and IOBES lableing, I will do the same as here :
https://www.depends-on-the-definition.com/guide-sequence-tagging-neural-networks-python/

In the link you can see a snapshot of the dataset, I want to make my dataset like it.

my questions are :

1- Is there a way to split a sentence into words so I can do the tagging for words ? (there is a tool in Excel, I tried it but it is very exhausted).
2- I tried to convert my file to .cvs, but I've faced a lot of problems (it is with utf-8, because my dataset is not in english) , is there another extension ?

I really appreciate your help and advice.
Thank you

答:
I'm using openpyxl to load excel file directly into memory. For instance,

```<code>from openpyxl import load_workbook
trainingFile = './InputForTraining/1.labelled.Data.V2.xlsx'
trainingSheet = 'sheet1'
TrainingFile = load_workbook(trainingFile)
sheet = TrainingFile[trainingSheet]
</code>```

Then you don't have to convert excel to csv. Sometime if the data structure is every complicated, the converting is not that simple. You still have to write some code to form the structure.
For split sentence is quite easy if your sentence is quite clean. Python has function split() to split your string to a list of words based on space. For instance,

```<code>wordsList = yourString.split()
</code>```

But you will need to be careful about punctuation. It usually follows right after a word. You can use regEx to split punctuation to a word. For instance,

```<code>pat = re.compile(r"([.,;:()/&])")
return_text = pat.sub(" \\1 ", return_text)
wordList = return_text.split()
</code>```

So [.,;:()/&] will be split from a word.
Or maybe you can even just remove punctuation from sentences if you don't need them at all. And replace them as space. For instance,

```<code>return_text = re.sub("[^a-zA-Z\s1234567890]+", ' ', text).strip().rstrip()
</code>```

Then only letters and numbers will be remained.
.strip().rstrip() is removing extra spaces.

Body:
I'm using openpyxl to load excel file directly into memory. For instance,

from openpyxl import load_workbook
trainingFile = './InputForTraining/1.labelled.Data.V2.xlsx'
trainingSheet = 'sheet1'
TrainingFile = load_workbook(trainingFile)
sheet = TrainingFile[trainingSheet]

Then you don't have to convert excel to csv. Sometime if the data structure is every complicated, the converting is not that simple. You still have to write some code to form the structure.
For split sentence is quite easy if your sentence is quite clean. Python has function split() to split your string to a list of words based on space. For instance,

wordsList = yourString.split()

But you will need to be careful about punctuation. It usually follows right after a word. You can use regEx to split punctuation to a word. For instance,

pat = re.compile(r"([.,;:()/&])")
return_text = pat.sub(" \\1 ", return_text)
wordList = return_text.split()

So [.,;:()/&] will be split from a word.
Or maybe you can even just remove punctuation from sentences if you don't need them at all. And replace them as space. For instance,

return_text = re.sub("[^a-zA-Z\s1234567890]+", ' ', text).strip().rstrip()

Then only letters and numbers will be remained.
.strip().rstrip() is removing extra spaces.


问:
css does not work on selected row of a tableview in order to change the text color
I assigned a css-file to a table view.
I want to change te background color of the selected row (which works) and the txt color (ewhich does not work).
I know that this problem has been covered but none of the answers I found and applied did work.
The background of a selected row turns from dark grey into light blue.
The text color remains white (it should be black).
I am using the jre1.8.0_211.
It would be great if someone could help me. Thank you so much in advance.

I put the  '-fx-fill: black;' in the 'table-row-cell:selected{' part and tried '-fx-fill: black;
as some other variants from the net which I actually don't remember.
This is a part of the css-file:

```<code>.table-view .table-cell{
    -fx-text-fill: White;
    -fx-font-size: 14px;
}

.table-row-cell{
    -fx-background-color: -fx-table-cell-border-color, #616161;
    -fx-background-insets: 0, 0 0 1 0;
    -fx-padding: 0.0em; /* 0 */
}

table-row-cell:selected {
    -fx-background-color:  #CBDAFF;
    -fx-background-insets: 0;
    -fx-background-radius: 1;
    -fx-border-color: #b3c7dc;
}

.table-row-cell:selected .text {
    -fx-fill: black ;
}
</code>```

No effects can be recognized concerning the text color of a selected row.

答:
this worked for me:</p>

```<code>.table-view:focused .table-row-cell:selected .table-cell {
    -fx-text-fill: white;
}
</code>```

Body:
I assigned a css-file to a table view.
I want to change te background color of the selected row (which works) and the txt color (ewhich does not work).
I know that this problem has been covered but none of the answers I found and applied did work.
The background of a selected row turns from dark grey into light blue.
The text color remains white (it should be black).
I am using the jre1.8.0_211.
It would be great if someone could help me. Thank you so much in advance.

I put the  '-fx-fill: black;' in the 'table-row-cell:selected{' part and tried '-fx-fill: black;
as some other variants from the net which I actually don't remember.
This is a part of the css-file:

.table-view .table-cell{
    -fx-text-fill: White;
    -fx-font-size: 14px;
}

.table-row-cell{
    -fx-background-color: -fx-table-cell-border-color, #616161;
    -fx-background-insets: 0, 0 0 1 0;
    -fx-padding: 0.0em; /* 0 */
}

table-row-cell:selected {
    -fx-background-color:  #CBDAFF;
    -fx-background-insets: 0;
    -fx-background-radius: 1;
    -fx-border-color: #b3c7dc;
}

.table-row-cell:selected .text {
    -fx-fill: black ;
}

No effects can be recognized concerning the text color of a selected row.

Body:
this worked for me:

.table-view:focused .table-row-cell:selected .table-cell {
    -fx-text-fill: white;
}


问:
Generating tables with images in cells using Python
I am pulling an assortment of data from the web using Python, and I would like to organize that data in a table format, such as HTML. My data include an image for each record, and that's the part I need help with. Can I create a table, so that I can place individual images inside the table cells?

It should / can look like this (computer component pictures in the table:

I have been looking at certain Python libraries such as Plotly and Bokeh but it doesn't look like they have this feature yet.

答: Python module for handling images is called Pillow maybe it will help. Alse if you will have it in html you can use css to display it the way you want.</p>


问:
How to delete specific session record by clicking on href?
I unable to delete specific record from session array. I want to delete specific row in table when I click on delete link.</p>

```<code><?php
session_start();

    if(isset($_GET["product"]) && isset($_GET["category"])){

        $nomProduct = trim($_GET["product"]);
        $category = trim($_GET["category"]);
        $_SESSION['product'][] = array(
            "nomProduct" => $nomProduct ,
            "category" =>  $category

        );

      //session_destroy();

       }
?>

    html table
              <table class="table">
                <?php foreach($_SESSION["product"] as $items) { ?>
                <tr>
                    <th width="250px"><?php echo $items['nomProduct']; ?></th>
                    <td><?php echo $items['category']; ?></td>
                    <td style="text-align: right"><a href="">Delete</a><td>
                </tr>
                <?php }?>

            </table>
</code>```

答:
Modify your HTML

```<code><table class="table">
<?php foreach($_SESSION["product"] as $key => $items) { ?>
  <tr>
    <th width="250px"><?php echo $items['nomProduct']; ?></th>
    <td><?php echo $items['category']; ?></td>
    <td style="text-align: right"><a href=?key="<?php echo $key; ?>">Delete</a><td>
   </tr>
 <?php }?>
</table>
</code>```

Catch the array key and remove it from session array.

```<code>$key = filter_input(INPUT_GET, 'key');
unset($_SESSION['product'][$key]);
</code>```

Body:
I unable to delete specific record from session array. I want to delete specific row in table when I click on delete link.

<?php
session_start();

    if(isset($_GET["product"]) && isset($_GET["category"])){

        $nomProduct = trim($_GET["product"]);
        $category = trim($_GET["category"]);
        $_SESSION['product'][] = array(
            "nomProduct" => $nomProduct ,
            "category" =>  $category

        );

      //session_destroy();

       }
?>

    html table

                <?php foreach($_SESSION["product"] as $items) { ?>

                    <?php echo $items['nomProduct']; ?>
                    <?php echo $items['category']; ?>
                    Delete

                <?php }?>

Body:
Modify your HTML

<table class="table">
<?php foreach($_SESSION["product"] as $key => $items) { ?>
  <tr>
    <th width="250px"><?php echo $items['nomProduct']; ?></th>
    <td><?php echo $items['category']; ?></td>
    <td style="text-align: right"><a href=?key="<?php echo $key; ?>">Delete</a><td>
   </tr>
 <?php }?>
</table>

Catch the array key and remove it from session array.

$key = filter_input(INPUT_GET, 'key');
unset($_SESSION['product'][$key]);


问:
My code wont render even after installing dependencies
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

```<code>import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

<img className="teacher-img" src={teacher.img_src} alt="teacher" />
  <b className="projectTitle">{teacher.name}</b>
            <hr className="divider2 my-4"/>

          <a className="link" href={teacher.code} target="_blank"  rel="noopener noreferrer"><b> Code </b></a>
  <a  className="link code" href={teacher.live} target="_blank"  rel="noopener noreferrer"><b> Live </b></a>
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>
    <div className="container3">
    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>
      <a>
        <Icon name='user' />
        10 Friends
      </a>
    </Card.Content>
    </div>

  </Card>

</div>

    );
  });

  return (
    <div className="main-content">
      <h2>Projects </h2>
      <ul className="group">
        {teachers}
      </ul>
    </div>
  );
}

export default Teachers;
</code>```

Package.Json

```<code>{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答:
Try doing npm i -S semantic-ui-react

The -S is a save flag will save it to your dependencies in your package.json where i don't see it.

If that doesn't work try deleting your node_modules folder and reinstall with npm i

Body:
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

  {teacher.name}

           Code
   Live
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>

    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>

        <Icon name='user' />
        10 Friends

    </Card.Content>

  </Card>

    );
  });

  return (

Projects

        {teachers}

  );
}

export default Teachers;

Package.Json

{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}


问:
Splitting up Data into Rows based on Cell Value
First time here so apologies in advance if I'm asking this incorrectly.

I have a pretty good understanding of excel but I've only ever really used it for some easy to moderate formulas. I'm trying to figure out where to start with a problem I have but I'm not even sure what to search for to find the answer. From what I have been able to find - it should be achievable with either Power Query or a Excel-VBA macro?

I have maybe 400 rows of data on a sheet. I need to separate each row of data based on the values in 4 of the columns.

This is the screenshot I've made with a brief example of what I'm trying to achieve.

The top part of the screenshot is how the data is now. The bottom part is how I want the data to be modified. A new row is created for any fee thats been incurred (base fee for every row, then if they have incurred an order fee then a new row is added, if a priority fee has been incurred then a new row is added etc. If it's '0' then no new row).

If any one has any guidance on how to do this it'd be great. I'm not asking for the solution, but just some tips on what I can research or what I should be learning to accomplish something like this!

答:
I'm in a hurry, so this code is rushed. Can come back and explain things if needed. But it gives me the output you've shown.

```<code>Option Explicit

Private Sub UnpivotColumns()

    Dim sourceSheet As Worksheet
    Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")

    Dim lastSourceRow As Long
    lastSourceRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row

    Dim lastSourceColumn As Long
    lastSourceColumn = sourceSheet.Cells(1, sourceSheet.Columns.Count).End(xlToLeft).Column

    Dim sourceData As Range
    Set sourceData = sourceSheet.Range("A2", sourceSheet.Cells(lastSourceRow, lastSourceColumn))

    Dim destinationSheet As Worksheet
    Set destinationSheet = ThisWorkbook.Worksheets("Sheet2")

    destinationSheet.Cells.Clear
    destinationSheet.Range("A1:D1").Value = Array("Name", "Description", "Currency", "Fee")

    Dim destinationRowIndex As Long
    destinationRowIndex = 1 ' Skip header row

    Dim outputArray(1 To 4) As Variant ' Re-use same array throughout procedure

    Dim sourceRowIndex As Long
    For sourceRowIndex = 2 To lastSourceRow

        ' Base fee always needs writing (unconditionally)
        outputArray(1) = sourceSheet.Cells(sourceRowIndex, "A") ' Name
        outputArray(2) = "Base Fee"  ' Description
        outputArray(3) = "USD" ' Currency
        outputArray(4) = 150 ' Fee amount

        destinationRowIndex = destinationRowIndex + 1
        destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray

        Const FIRST_COLUMN_TO_UNPIVOT As Long = 4 ' Skip first three columns

        Dim sourceColumnIndex As Long
        For sourceColumnIndex = FIRST_COLUMN_TO_UNPIVOT To lastSourceColumn Step 2
            outputArray(2) = sourceSheet.Cells(1, sourceColumnIndex)  ' Unpivoted description
            outputArray(3) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex + 1) ' Unpivoted currency
            outputArray(4) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex) ' Unpivoted fee amount

            ' Skip amount if nil/zero
            If outputArray(4) > 0 Then
                destinationRowIndex = destinationRowIndex + 1
                destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray
            End If

        Next sourceColumnIndex

    Next sourceRowIndex

End Sub
</code>```

The code makes some assumptions (which are true for your screenshot, but might not be true if the layout of your data changes).

Bad things about this code:

It is rigid and not very flexible/dynamic

It will be slow as it read/writes cells one at a time.

There is no referential integrity (column indexes/offsets are assumed and never actually checked/asserted). This becomes a problem if the layout/position of your data changes.

Good things about this code:

It hopefully works (for the example you've shown in your screenshot).

This is my data before the code (on Sheet1):

This is my data after the code (on Sheet2):

Also, something like this is equally possible in Power Query too (and probably in fewer lines of code too).

Body:
I'm in a hurry, so this code is rushed. Can come back and explain things if needed. But it gives me the output you've shown.

Option Explicit

Private Sub UnpivotColumns()

    Dim sourceSheet As Worksheet
    Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")

    Dim lastSourceRow As Long
    lastSourceRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row

    Dim lastSourceColumn As Long
    lastSourceColumn = sourceSheet.Cells(1, sourceSheet.Columns.Count).End(xlToLeft).Column

    Dim sourceData As Range
    Set sourceData = sourceSheet.Range("A2", sourceSheet.Cells(lastSourceRow, lastSourceColumn))

    Dim destinationSheet As Worksheet
    Set destinationSheet = ThisWorkbook.Worksheets("Sheet2")

    destinationSheet.Cells.Clear
    destinationSheet.Range("A1:D1").Value = Array("Name", "Description", "Currency", "Fee")

    Dim destinationRowIndex As Long
    destinationRowIndex = 1 ' Skip header row

    Dim outputArray(1 To 4) As Variant ' Re-use same array throughout procedure

    Dim sourceRowIndex As Long
    For sourceRowIndex = 2 To lastSourceRow

        ' Base fee always needs writing (unconditionally)
        outputArray(1) = sourceSheet.Cells(sourceRowIndex, "A") ' Name
        outputArray(2) = "Base Fee"  ' Description
        outputArray(3) = "USD" ' Currency
        outputArray(4) = 150 ' Fee amount

        destinationRowIndex = destinationRowIndex + 1
        destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray

        Const FIRST_COLUMN_TO_UNPIVOT As Long = 4 ' Skip first three columns

        Dim sourceColumnIndex As Long
        For sourceColumnIndex = FIRST_COLUMN_TO_UNPIVOT To lastSourceColumn Step 2
            outputArray(2) = sourceSheet.Cells(1, sourceColumnIndex)  ' Unpivoted description
            outputArray(3) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex + 1) ' Unpivoted currency
            outputArray(4) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex) ' Unpivoted fee amount

            ' Skip amount if nil/zero
            If outputArray(4) > 0 Then
                destinationRowIndex = destinationRowIndex + 1
                destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray
            End If

        Next sourceColumnIndex

    Next sourceRowIndex

End Sub

The code makes some assumptions (which are true for your screenshot, but might not be true if the layout of your data changes).

Bad things about this code:

It is rigid and not very flexible/dynamic

It will be slow as it read/writes cells one at a time.

There is no referential integrity (column indexes/offsets are assumed and never actually checked/asserted). This becomes a problem if the layout/position of your data changes.

Good things about this code:

It hopefully works (for the example you've shown in your screenshot).

This is my data before the code (on Sheet1):

This is my data after the code (on Sheet2):

Also, something like this is equally possible in Power Query too (and probably in fewer lines of code too).


问:
Why is conditional test for ComboBox value being ignored? (Access VBA)
I have an If clause that was being completely ignored, until I discovered a workaround, but now I'd like to better understand what is happening under-the-hood.

We have a form with a ComboBox that gets populated, but a default value is not set on it.  When I go to save the form, we need to test if the user selected a value.  The code was:

```<code>If (Me.Combo78.Value = "") Then
    mb "Please select a value"
End If
</code>```

The code would never fire, until I changed the condition to read:

```<code>If ("" & Me.Combo78.Value = "") Then
    mb "Please select a value"
End If
</code>```

I'm guessing that the "" & forces the comparison to be a text comparison, and therefore can validly test against the empty string "", but what was the previous comparison actually doing, and is there a better, more intuitive way to manage this?  The solution I have just feels gross.

-- 30 years experience with coding in Pascal, HTML, Javascript, but <1 year coding in VBA, after being handed a legacy application that needs debugging.

答:
If the ComboBox has no value then Me.Combo78.Value will be null and consequently Me.Combo78.Value = "" will be null and will not validate the test expression for the if statement.

In your second code, concatenating an empty string with a null value will return an empty string, and so "" & Me.Combo78.Value returns an empty string, thus validating the test expression.

If you wish, you can verify this for yourself in the VBE Immediate Window (accessible using Ctrl+G):

?Null = ""
Null
?Null & "" = ""
True
```

<p>A more readable solution might be:</p>

<pre class="lang-vb prettyprint-override"><code>If IsNull(Me.Combo78) Or Me.Combo78 = "" Then
    mb "Please select a value"
End If
</code>```

Alternatively, you could use the Nz function:

If Nz(Me.Combo78, "") = "" Then
    mb "Please select a value"
End If
```

Since the Value property is the default member for this class, it may be safely omitted.

Body:
I have an If clause that was being completely ignored, until I discovered a workaround, but now I'd like to better understand what is happening under-the-hood.

We have a form with a ComboBox that gets populated, but a default value is not set on it.  When I go to save the form, we need to test if the user selected a value.  The code was:

If (Me.Combo78.Value = "") Then
    mb "Please select a value"
End If

The code would never fire, until I changed the condition to read:

If ("" & Me.Combo78.Value = "") Then
    mb "Please select a value"
End If

I'm guessing that the "" & forces the comparison to be a text comparison, and therefore can validly test against the empty string "", but what was the previous comparison actually doing, and is there a better, more intuitive way to manage this?  The solution I have just feels gross.

-- 30 years experience with coding in Pascal, HTML, Javascript, but <1 year coding in VBA, after being handed a legacy application that needs debugging.

Body:
If the ComboBox has no value then Me.Combo78.Value will be null and consequently Me.Combo78.Value = "" will be null and will not validate the test expression for the if statement.

In your second code, concatenating an empty string with a null value will return an empty string, and so "" & Me.Combo78.Value returns an empty string, thus validating the test expression.

If you wish, you can verify this for yourself in the VBE Immediate Window (accessible using Ctrl+G):

?Null = ""
Null
?Null & "" = ""
True

A more readable solution might be:

If IsNull(Me.Combo78) Or Me.Combo78 = "" Then
    mb "Please select a value"
End If

Alternatively, you could use the Nz function:

If Nz(Me.Combo78, "") = "" Then
    mb "Please select a value"
End If

Since the Value property is the default member for this class, it may be safely omitted.


问:
Jackson Serialize Instant to Nanosecond Issue
Jackson serialises java.time.Instant with WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS enabled by default.

It produces JSON like this

```<code>{ "timestamp":1421261297.356000000 }
</code>```

I wonder if there's a way to get rid of the zeros at the end. I want something like:

```<code>{ "timestamp":1421261297.356 }
</code>```

I tried:

```<code>mapper.configure( SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false );
mapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true );
</code>```

But this configuration changes it to millisecond representation 1421261297356. I want the seconds part and the fractional milliseconds part.

答:
When we are working with Java 8 Time package and Jackson good idea is to use jackson-modules-java8 project which serves many serialisers and deserialisers ready to use. To enable it we need to register JavaTimeModule module. To serialise Instant InstantSerializer is used. When we check how it is implemented we will find out that behind scene DecimalUtils.toDecimal method is used. It looks like there is always zeros added at the end of nanoseconds value.

We can write our InstantSerializer which serialises it in desired way. Because classes in this project are not ready to easily extend we need to implement many unwanted methods and constructors. Also we need create in our project com.fasterxml.jackson.datatype.jsr310.ser package and create our implementation there. See below example:

```<code>package com.fasterxml.jackson.datatype.jsr310.ser;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

public class ShortInstantSerializer extends InstantSerializerBase<Instant> {

    private ToLongFunction<Instant> getEpochSeconds = Instant::getEpochSecond;
    private ToIntFunction<Instant> getNanoseconds = i -> i.getNano() / 1_000_000;

    public ShortInstantSerializer() {
        super(Instant.class, Instant::toEpochMilli, Instant::getEpochSecond, Instant::getNano, null);
    }

    protected ShortInstantSerializer(ShortInstantSerializer base, Boolean useTimestamp, Boolean useNanoseconds, DateTimeFormatter formatter) {
        super(base, useTimestamp, useNanoseconds, formatter);
    }

    @Override
    protected JSR310FormattedSerializerBase<?> withFormat(Boolean useTimestamp, DateTimeFormatter formatter, JsonFormat.Shape shape) {
        return new ShortInstantSerializer(this, useTimestamp, null, formatter);
    }

    @Override
    public void serialize(Instant value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        if (useTimestamp(provider)) {
            if (useNanoseconds(provider)) {
                generator.writeNumber(new BigDecimal(toShortVersion(value)));
                return;
            }
        }

        super.serialize(value, generator, provider);
    }

    private String toShortVersion(final Instant value) {
        return getEpochSeconds.applyAsLong(value) + "." + padWithZeros(getNanoseconds.applyAsInt(value));
    }

    private String padWithZeros(final int value) {
        return String.format("%1$3s", String.valueOf(value)).replace(' ', '0');
    }
}
</code>```

And example how to use it:

```<code>import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.ShortInstantSerializer;

import java.time.Instant;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(Instant.class, new ShortInstantSerializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(javaTimeModule);
        mapper.disable(SerializationFeature.INDENT_OUTPUT);

        System.out.println(mapper.writeValueAsString(new Element()));
    }
}

class Element {

    private Instant timestamp = Instant.now();

    public Instant getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Instant timestamp) {
        this.timestamp = timestamp;
    }
}
</code>```

Above code prints:

```<code>{"timestamp":1559074287.223}
</code>```

If you want to rid of all zeros in all cases write your own getNanoseconds function declared in ShortInstantSerializer class.

Body:
Jackson serialises java.time.Instant with WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS enabled by default.

It produces JSON like this

{ "timestamp":1421261297.356000000 }

I wonder if there's a way to get rid of the zeros at the end. I want something like:

{ "timestamp":1421261297.356 }

I tried:

mapper.configure( SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false );
mapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true );

But this configuration changes it to millisecond representation 1421261297356. I want the seconds part and the fractional milliseconds part.

Body:
When we are working with Java 8 Time package and Jackson good idea is to use jackson-modules-java8 project which serves many serialisers and deserialisers ready to use. To enable it we need to register JavaTimeModule module. To serialise Instant InstantSerializer is used. When we check how it is implemented we will find out that behind scene DecimalUtils.toDecimal method is used. It looks like there is always zeros added at the end of nanoseconds value.

We can write our InstantSerializer which serialises it in desired way. Because classes in this project are not ready to easily extend we need to implement many unwanted methods and constructors. Also we need create in our project com.fasterxml.jackson.datatype.jsr310.ser package and create our implementation there. See below example:

package com.fasterxml.jackson.datatype.jsr310.ser;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

public class ShortInstantSerializer extends InstantSerializerBase<Instant> {

    private ToLongFunction<Instant> getEpochSeconds = Instant::getEpochSecond;
    private ToIntFunction<Instant> getNanoseconds = i -> i.getNano() / 1_000_000;

    public ShortInstantSerializer() {
        super(Instant.class, Instant::toEpochMilli, Instant::getEpochSecond, Instant::getNano, null);
    }

    protected ShortInstantSerializer(ShortInstantSerializer base, Boolean useTimestamp, Boolean useNanoseconds, DateTimeFormatter formatter) {
        super(base, useTimestamp, useNanoseconds, formatter);
    }

    @Override
    protected JSR310FormattedSerializerBase<?> withFormat(Boolean useTimestamp, DateTimeFormatter formatter, JsonFormat.Shape shape) {
        return new ShortInstantSerializer(this, useTimestamp, null, formatter);
    }

    @Override
    public void serialize(Instant value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        if (useTimestamp(provider)) {
            if (useNanoseconds(provider)) {
                generator.writeNumber(new BigDecimal(toShortVersion(value)));
                return;
            }
        }

        super.serialize(value, generator, provider);
    }

    private String toShortVersion(final Instant value) {
        return getEpochSeconds.applyAsLong(value) + "." + padWithZeros(getNanoseconds.applyAsInt(value));
    }

    private String padWithZeros(final int value) {
        return String.format("%1$3s", String.valueOf(value)).replace(' ', '0');
    }
}

And example how to use it:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.ShortInstantSerializer;

import java.time.Instant;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(Instant.class, new ShortInstantSerializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(javaTimeModule);
        mapper.disable(SerializationFeature.INDENT_OUTPUT);

        System.out.println(mapper.writeValueAsString(new Element()));
    }
}

class Element {

    private Instant timestamp = Instant.now();

    public Instant getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Instant timestamp) {
        this.timestamp = timestamp;
    }
}

Above code prints:

{"timestamp":1559074287.223}

If you want to rid of all zeros in all cases write your own getNanoseconds function declared in ShortInstantSerializer class.


问:
How can I use mutliple url variables?
I will convert URL's like those

```<code>example.com/tasks.php?action=list
example.com/tasks.php?action=detail&id=48
example.com/tasks.php?action=add&name=Test
</code>```

into those

```<code>example.com/tasks/list
example.com/tasks/detail/48
example.com/tasks/add?name=Test
</code>```

So, I need two variables, but the second must be optional, the file extension must be hidden and I need to add get variables.

答:
So, I stole the base from someone's GitHub page (here):

```<code>Original URL:
http://www.example.com/index.php?category=fish
Desired destination URL:
http://www.example.com/category/fish/
.htaccess syntax:

RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]
</code>```

You can just add another parameter. With multiple parameters:

```<code>RewriteEngine On
RewriteRule ^/?tasks/([A-Za-z]{0,})/?$ tasks.php?action=$1 [L,QSA]
RewriteRule ^/?tasks/([A-Za-z]{0,})/([0-9]{0,})/?$ tasks.php?action=$1&id=$2 [L,QSA]
</code>```

With this, you can publish the pretty version of the links, and the server will direct traffic to the URLs with the GET parameters, behind the scenes.

EDIT: The first rule will catch your 3rd case by default because of the QSA.

Title: How can I use mutliple url variables?

Body:
I will convert URL's like those

example.com/tasks.php?action=list
example.com/tasks.php?action=detail&id=48
example.com/tasks.php?action=add&name=Test

into those

example.com/tasks/list
example.com/tasks/detail/48
example.com/tasks/add?name=Test

So, I need two variables, but the second must be optional, the file extension must be hidden and I need to add get variables.

Body:
So, I stole the base from someone's GitHub page (here):

Original URL:
http://www.example.com/index.php?category=fish
Desired destination URL:
http://www.example.com/category/fish/
.htaccess syntax:

RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]

You can just add another parameter. With multiple parameters:

RewriteEngine On
RewriteRule ^/?tasks/([A-Za-z]{0,})/?$ tasks.php?action=$1 [L,QSA]
RewriteRule ^/?tasks/([A-Za-z]{0,})/([0-9]{0,})/?$ tasks.php?action=$1&id=$2 [L,QSA]

With this, you can publish the pretty version of the links, and the server will direct traffic to the URLs with the GET parameters, behind the scenes.

EDIT: The first rule will catch your 3rd case by default because of the QSA.


问:
How to pass IHttpContextAccessor to DotLiquid's custom tag
My ASP.NET Core application is using dotliquid.  I am creating my own custom dotliquid tag and I want to inject IHttpContextAccessor in my custom tag. Based on my research i have to create ITagFactory to create tag and inject IHttpContextAccessor.

my custom factory

```<code>public class LiquidTagFactory : DotLiquid.ITagFactory
{
    private readonly Type _tagType;
    private readonly string _tagName;
    private readonly IHttpContextAccessor _contextAccessor;

    public string TagName { get { return _tagName; } }

    public LiquidTagFactory(Type tagType, string tagName, IHttpContextAccessor contextAccessor)
    {
        _tagType = tagType;
        _tagName = tagName;
        _contextAccessor = contextAccessor;
    }

    public Tag Create()
    {
        return (Tag)Activator.CreateInstance(_tagType, _contextAccessor);
    }
}
</code>```

my custom tag

```<code>public class TextBox : DotLiquid.Tag
{
    private string _html = null;
    private readonly IHttpContextAccessor _contextAccessor;

    public TextBox(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public override void Initialize(string tagName, string markup, List<string> tokens)
    {
        // here i want to store some values into HttpContext.Items
        _contextAccessor.HttpContext.Items.Add("key","somedata");

        base.Initialize(tagName, markup, tokens);
    }

    public override void Render(Context context, TextWriter result)
    {
       _html = CreateHtml();
        result.Write(_html);
        base.Render(context, result);
    }
}
</code>```

Then i would register this factory as

```<code> Template.RegisterTagFactory(new LiquidTagFactory(typeof(TexBox), "textbox", _httpContextAccessor));
</code>```

However, i am using ASP.NET Core. I am not sure how do i register custom tag factory using .NET Core's dependency injection?

looking at dotliquid's template code it stores the ITagFactory in private static field

```<code>  private static Dictionary<string, Tuple<ITagFactory, Type>> Tags { get; set;}
</code>```

In my case, every request will have its own IHttpContextAccessor, and i don't want to create factory for each request

答:
I think i found it. As per SO we can register IHttpContextAccessor singleton.
As of .NET Core 2.1 there is an extension method that has been added to correctly register an IHttpContextAccessor as a singleton. Simply add as follows in your ConfigureServices() method:

```<code>         services.AddHttpContextAccessor();
</code>```

This is equivalent to:

```<code>         services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
</code>```

and then register the factory in Configure() method in startup. Make sure to pass IHttpContextAccessor as parameter

```<code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<DomainOptions> domainOps, IHttpContextAccessor httpContextAccessor)
    {

        Template.RegisterTagFactory(new LiquidTagFactory(typeof(TextBox), "textbox", httpContextAccessor));
    }
</code>```

Body:
My ASP.NET Core application is using dotliquid.  I am creating my own custom dotliquid tag and I want to inject IHttpContextAccessor in my custom tag. Based on my research i have to create ITagFactory to create tag and inject IHttpContextAccessor.

my custom factory

public class LiquidTagFactory : DotLiquid.ITagFactory
{
    private readonly Type _tagType;
    private readonly string _tagName;
    private readonly IHttpContextAccessor _contextAccessor;

    public string TagName { get { return _tagName; } }

    public LiquidTagFactory(Type tagType, string tagName, IHttpContextAccessor contextAccessor)
    {
        _tagType = tagType;
        _tagName = tagName;
        _contextAccessor = contextAccessor;
    }

    public Tag Create()
    {
        return (Tag)Activator.CreateInstance(_tagType, _contextAccessor);
    }
}

my custom tag

public class TextBox : DotLiquid.Tag
{
    private string _html = null;
    private readonly IHttpContextAccessor _contextAccessor;

    public TextBox(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public override void Initialize(string tagName, string markup, List<string> tokens)
    {
        // here i want to store some values into HttpContext.Items
        _contextAccessor.HttpContext.Items.Add("key","somedata");

        base.Initialize(tagName, markup, tokens);
    }

    public override void Render(Context context, TextWriter result)
    {
       _html = CreateHtml();
        result.Write(_html);
        base.Render(context, result);
    }
}

Then i would register this factory as

 Template.RegisterTagFactory(new LiquidTagFactory(typeof(TexBox), "textbox", _httpContextAccessor));

However, i am using ASP.NET Core. I am not sure how do i register custom tag factory using .NET Core's dependency injection?

looking at dotliquid's template code it stores the ITagFactory in private static field

  private static Dictionary<string, Tuple<ITagFactory, Type>> Tags { get; set;}

In my case, every request will have its own IHttpContextAccessor, and i don't want to create factory for each request

Body:
I think i found it. As per SO we can register IHttpContextAccessor singleton.
As of .NET Core 2.1 there is an extension method that has been added to correctly register an IHttpContextAccessor as a singleton. Simply add as follows in your ConfigureServices() method:

         services.AddHttpContextAccessor();

This is equivalent to:

         services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and then register the factory in Configure() method in startup. Make sure to pass IHttpContextAccessor as parameter

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<DomainOptions> domainOps, IHttpContextAccessor httpContextAccessor)
    {

        Template.RegisterTagFactory(new LiquidTagFactory(typeof(TextBox), "textbox", httpContextAccessor));
    }


问:
Django runserver on Chromebook (Crostini)
I'm using a Chromebook HP 11 G5 EE and try to develop with Django.
I use Crostini (Linux terminal into Chrome OS with no developper mode).
I've created a virtualenv inside my home directory and installed with pip all my requirements.

When I try to do (with source bin/activate) :

```<code>./manage.py runserver
</code>```

It returns me :

Performing system checks...

```<code>System check identified no issues (0 silenced).
May 28, 2019 - 20:02:11
Django version 2.1.5, using settings 'myproject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Error: You don't have permission to access that port.
</code>```

I'd try to set parameters like 0.0.0.0:8000, penguin.linux.test:8000, to change ports, I've got the same error.

Is someone had the same issue and fixed it ?

Thanks !

答:
How about this:</p>

```<code>./manage.py runserver 0.0.0.0:8000
</code>```

Body:
I'm using a Chromebook HP 11 G5 EE and try to develop with Django.
I use Crostini (Linux terminal into Chrome OS with no developper mode).
I've created a virtualenv inside my home directory and installed with pip all my requirements.

When I try to do (with source bin/activate) :

./manage.py runserver

It returns me :

Performing system checks...

System check identified no issues (0 silenced).
May 28, 2019 - 20:02:11
Django version 2.1.5, using settings 'myproject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Error: You don't have permission to access that port.

I'd try to set parameters like 0.0.0.0:8000, penguin.linux.test:8000, to change ports, I've got the same error.

Is someone had the same issue and fixed it ?

Thanks !

Body:
How about this:

./manage.py runserver 0.0.0.0:8000


问:
Does the creation of a subclass object create objects of its superclasses as well?
Heres an example of what I mean:

```<code>public class Rectangle
{
    private int length;
    private int breadth;
    .
    .
}

public class Box extends Rectangle
{
    private int height;
    .
    .
}
</code>```

When you:

```<code>Box b = new Box();
</code>```

Does it create a Box as well as a Rectangle object, with the rectangle not directly accessible, but only accessible through the Box object. In other words, does it create two objects in memory?

答:
In other words, does it create two objects in memory?

No, it creates a single object. This single object represents a Box (and since this is a subtype of Rectangle this same object represents a Rectangle as well).

The inheritance simply ensures that the interface of the Box object is an extension of the Rectangle interface.

ContentLicense: CC BY-SA 3.0

Body:
Heres an example of what I mean:

public class Rectangle
{
    private int length;
    private int breadth;
    .
    .
}

public class Box extends Rectangle
{
    private int height;
    .
    .
}

When you:

Box b = new Box();

Does it create a Box as well as a Rectangle object, with the rectangle not directly accessible, but only accessible through the Box object. In other words, does it create two objects in memory?


问:
Method 'Range' of object'_Worksheet' failed |Excel|VBA|
Error : Method 'Range' of object'_Worksheet' failed

```<code>Dim Ws As Worksheet
For Each Ws In Sheets(Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))

    Ws.Range("I9:AM68" & Rows.Count).Replace What:="AP", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="BL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="MA", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="PA", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="PL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="SL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="UP", Replacement:="", LookAt:=xlWhole

    Ws.Range("I9:AM68" & Rows.Count).Replace What:="H1", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="H2", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="TR", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="WH", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="NJ", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="AL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="SUP", Replacement:="", LookAt:=xlWhole

Next Ws
</code>```

If match is Found in each sheet the Data is Been Cleared => have Conditional Formatting in Range => I to AM

This is my another code which i have tried not working

```<code>Dim Ws As Worksheet, lr As Long, c As Range
For Each Ws In Sheets(Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))
    lr = Ws.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
    For Each c In Ws.Range("I9:AM68" & lr)
        Select Case UCase(c.Value)
            Case "SUP", "AP", "AL"
                c.Value = ""
                c.Interior.ColorIndex = xlNone
        End Select
    Next
Next Ws
</code>```

This is the Image of my Excel

[my image][1]: https://i.stack.imgur.com/yDLj4.png

This Below Works fine for me But not setting the cell color to normal cell color like no fill color

```<code>'what:=UCase("SUP"), Replacement:="", ReplaceFormat:=True

Dim Ws As Worksheet
For Each Ws In Sheets(Array("Sheet1", "Sheet2", "Sheet3"))

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=False

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AP"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AP"), Replacement:="", ReplaceFormat:=False

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=False

Next Ws
</code>```

this is below output of above code
[output][1]: https://i.stack.imgur.com/H09ab.png

答:
Assuming you are trying to get the last row in that range, and not the actual rows.count, see below one way to achieve those replacements.

Option Explicit
Sub doSomeReplacements()

    Application.ScreenUpdating = False

    Dim wb As Workbook: Set wb = ThisWorkbook   'set your workbook variable
    Dim Ws As Worksheet
    Dim shNames() As String: shNames = Split("Sheet1,Sheet2,Sheet3", ",") 'allocate sheet names to an array
    Dim strReplaces() As String: strReplaces = Split("AP,BL,MA,PA,PL,SL,UP,H1,H2,TR,WH,NJ,AL,SUP", ",") 'allocate replacement strings to an array
    Dim lastRow As Long, X As Long, Z As Long, R As Long, C As Long

    For X = LBound(shNames) To UBound(shNames)  'Loop through the array of sheet names
        On Error Resume Next
        Set Ws = wb.Sheets(shNames(X))
        On Error GoTo 0

        If Not Ws Is Nothing Then   'If there is a worksheet to work with....
            With Ws
                'lastRow = .Cells(.Rows.Count, "I").End(xlUp).Row   'get last row at column "I"
                lastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row 'alternative last row

                For R = 1 To lastRow
                    For C = 1 To 11 '"A:K"
                        For Z = LBound(strReplaces) To UBound(strReplaces) 'Loop through the array of replacements and apply the replacement
                            With .Cells(R, C)
                                If .Value = strReplaces(Z) Then
                                    .Value = ""
                                    .Interior.ColorIndex = xlNone
                                End If
                            End With
                        Next Z
                    Next C
                Next R
            End With
        End If
        Set Ws = Nothing
    Next X

    Application.ScreenUpdating = True
End Sub
```

Body:
Error : Method 'Range' of object'_Worksheet' failed

Dim Ws As Worksheet
For Each Ws In Sheets(Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))

    Ws.Range("I9:AM68" & Rows.Count).Replace What:="AP", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="BL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="MA", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="PA", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="PL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="SL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="UP", Replacement:="", LookAt:=xlWhole

    Ws.Range("I9:AM68" & Rows.Count).Replace What:="H1", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="H2", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="TR", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="WH", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="NJ", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="AL", Replacement:="", LookAt:=xlWhole
    Ws.Range("I9:AM68" & Rows.Count).Replace What:="SUP", Replacement:="", LookAt:=xlWhole

Next Ws

If match is Found in each sheet the Data is Been Cleared => have Conditional Formatting in Range => I to AM

This is my another code which i have tried not working

Dim Ws As Worksheet, lr As Long, c As Range
For Each Ws In Sheets(Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))
    lr = Ws.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
    For Each c In Ws.Range("I9:AM68" & lr)
        Select Case UCase(c.Value)
            Case "SUP", "AP", "AL"
                c.Value = ""
                c.Interior.ColorIndex = xlNone
        End Select
    Next
Next Ws

This is the Image of my Excel

[my image][1]: https://i.stack.imgur.com/yDLj4.png

This Below Works fine for me But not setting the cell color to normal cell color like no fill color

'what:=UCase("SUP"), Replacement:="", ReplaceFormat:=True

Dim Ws As Worksheet
For Each Ws In Sheets(Array("Sheet1", "Sheet2", "Sheet3"))

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("SUP"), Replacement:="", ReplaceFormat:=False

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AP"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AP"), Replacement:="", ReplaceFormat:=False

Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=True
Ws.Range("A4:K" & Rows.Count).Replace what:=UCase("AL"), Replacement:="", ReplaceFormat:=False

Next Ws

this is below output of above code
[output][1]: https://i.stack.imgur.com/H09ab.png


问:
RegEx for validating emails with single letter domains
I have a regular expression which is good with all my rules except that it fails to validate email addresses with less than 3 characters in its domain:

```<code>^(?=(.{1,64}@.{1,255}))([-+%_a-zA-Z0-9]{1,64}(\.[-+%_a-zA-Z0-9][^.]{0,}){0,})@[^-\.@#!$&^*~`={}|'"?]([a-zA-Z0-9_]{1,63}(\.[a-zA-Z0-9-]{0,}){0,}[^.](?!.web)(\.[a-zA-Z]{2,6}){1,4})$
</code>```

Eg It considers sample@q.com and sample@me.com as invalid emails

Regex can be found here
https://regex101.com/r/XcXIaL/1

Could anyone suggest a modification to this existing regular expression

It should accept

```<code>sample@q.com
sample@me.com
sample@mes.com
</code>```

Body:
I have a regular expression which is good with all my rules except that it fails to validate email addresses with less than 3 characters in its domain:

^(?=(.{1,64}@.{1,255}))([-+%_a-zA-Z0-9]{1,64}(\.[-+%_a-zA-Z0-9][^.]{0,}){0,})@[^-\.@#!$&^*~`={}|'"?]([a-zA-Z0-9_]{1,63}(\.[a-zA-Z0-9-]{0,}){0,}[^.](?!.web)(\.[a-zA-Z]{2,6}){1,4})$

Eg It considers sample@q.com and sample@me.com as invalid emails

Regex can be found here
https://regex101.com/r/XcXIaL/1

Could anyone suggest a modification to this existing regular expression

It should accept

sample@q.com
sample@me.com
sample@mes.com

Body:
Here, we simply reduce the {1,63} boundary to {0,63}, and remove this unnecessary letter:

[^-\.@#!$&^*~`={}|'"?]

The key part of our code associated with that is:

[^-\.@#!$&^*~`={}|'"?]([a-zA-Z0-9_]{1,63}(\.[a-zA-Z0-9-]{0,}){0,}[^.](?!.web)

changed to:

([a-zA-Z0-9_]{1,63}(\.[a-zA-Z0-9-]{0,}){0,}[^.](?!.web)

and final code is:

^(?=(.{1,64}@.{1,255}))([-+%_a-zA-Z0-9]{1,64}(\.[-+%_a-zA-Z0-9][^.]{0,}){0,})@([a-zA-Z0-9_]{0,63}(\.[a-zA-Z0-9-]{0,}){0,}[^.](?!.web)(\.[a-zA-Z]{2,6}){1,4})$

DEMO

Our modified expression is:


问:
Executing FolderBrowserDialog in powershell from client browser using javascript
I'm trying to trigger some sort of Folder Selection Dialog, I have a working model with nodejs and the powershell but it only works when the server and client are on the same machine. I need the prompt to occur on the client side triggered from the browser. From what i understand I can not trigger Powershell from Chrome? So is there an alternative or am i just screwed?

My current Powershell script

```<code>{
    param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
     Out-Null

   $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
        $objForm.Rootfolder = $RootFolder
        $objForm.Description = $Description
        $Show = $objForm.ShowDialog()
        If ($Show -eq "OK")
        {
            Return $objForm.SelectedPath
        }
        Else
        {
            Write-Error "Operation cancelled by user."
        }
    }

$folder = Select-FolderDialog # the variable contains user folder selection
write-host $folder
</code>```

My javascript function

```<code>
async function asyncfindDir() {
          //executes powershell script
       let promise = new Promise((resolve, reject) => {
        const Shell = require('node-powershell');
        const ps = new Shell({
          executionPolicy: 'Bypass',
          noProfile: true
        });

        ps.addCommand('./selectfolder.ps1');
        ps.invoke()
        .then(output => {
          //console.log(output);

          var shelloutput = output;
          console.log (shelloutput + '^^from external script');

          res.send(shelloutput);
        })
        .catch(err => {
          console.log('please select a directory path')
          //console.log('err');
        });
});
};
</code>```

Is there anyway to get that working locally?
Is there a trigger i'm not aware of to access that kind of dialog from the browser? I know i'm not the only person with this issue but i have yet to see a real solution.

答:
Short answer: No.

Longer answer, is best illustrated by rephrasing your question with a different script name:

Using my browser, can I click on a link to visit a website, and have it run a random
  PowerShell script called Delete_All_Files.ps1?

Answers why you will never be able to run a PowerShell script from a browser, on a remote machine, and why browsers will deliberately block you from doing it, because people usually don't want to have all their files deleted when they click on a random link in their email.

If you want to run PowerShell scripts on remote machines, then you should look into PSRemoting and Enter-PSSession.

@kuzimoto is right. If you just want to display a folder dialog box, there are easier ways to do that and Fine Uploader is an easier way.

Replying to your comment: If you want to specify a directory name, the reason you can't do it is because you are essentially asking:

Using my browser, can I click on a link to visit a website, and have
  it run a script that will enumerate through all the files and folders
  in my C:\ so that it can choose the folder C:\users\Justin
  Miller\Desktop\SECRET FILES\?

The reason both operations do not work is because both operations require local computer access. i.e. local script execution access, and local directory knowledge access. Security-wize, we, in general, don't want to visit a random website and have it execute random code, or know what files/folders I have on my machine, which is why you won't be able to do what you want to try to do.

Body:
I'm trying to trigger some sort of Folder Selection Dialog, I have a working model with nodejs and the powershell but it only works when the server and client are on the same machine. I need the prompt to occur on the client side triggered from the browser. From what i understand I can not trigger Powershell from Chrome? So is there an alternative or am i just screwed?

My current Powershell script

{
    param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
     Out-Null

   $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
        $objForm.Rootfolder = $RootFolder
        $objForm.Description = $Description
        $Show = $objForm.ShowDialog()
        If ($Show -eq "OK")
        {
            Return $objForm.SelectedPath
        }
        Else
        {
            Write-Error "Operation cancelled by user."
        }
    }

$folder = Select-FolderDialog # the variable contains user folder selection
write-host $folder

My javascript function

async function asyncfindDir() {
          //executes powershell script
       let promise = new Promise((resolve, reject) => {
        const Shell = require('node-powershell');
        const ps = new Shell({
          executionPolicy: 'Bypass',
          noProfile: true
        });

        ps.addCommand('./selectfolder.ps1');
        ps.invoke()
        .then(output => {
          //console.log(output);

          var shelloutput = output;
          console.log (shelloutput + '^^from external script');

          res.send(shelloutput);
        })
        .catch(err => {
          console.log('please select a directory path')
          //console.log('err');
        });
});
};

Is there anyway to get that working locally?
Is there a trigger i'm not aware of to access that kind of dialog from the browser? I know i'm not the only person with this issue but i have yet to see a real solution.


问:
How to <select> only none existing users from a case. SQL SELECT
Working on selecting all users into an html <select> that doesn't exist in it already.

I am working on a "case" website where I can put users on cases. Users can be put on multiple cases at once. I am making a html <select> with all the users I can add to the case and it is important that already existing users on that case aren't shown.

I have 3 SQL tables. Users, Cases, and Junc_jobs. Junc_Jobs works as a many to many relations to connect users and cases. All the users that I want to select are fk_role > 1.

```<code>USERS
+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  05   | Rasmus     | 57       |
|  06   | Ulrik      | 57       |
|  10   | Nick       | 59       |
|  12   | Lisa       | 59       |
|  22   | Marco      | 65       |
|  23   | Frederik   | 63       |
+-------+------------+----------+

CASES
+-------+------------+
|  id   | caseName   |
+-------+------------+
|  57   | case 1     |
|  59   | case 2     |
|  63   | case 3     |
|  64   | case 4     |
|  65   | case 5     |
+-------+------------+

JUNC_JOBS
+-------+------------+--------------+
|  id   | fk_case    | fk_employee  |
+-------+------------+--------------+
|  1    | 57         | 5            |
|  2    | 59         | 5            |
|  3    | 64         | 23           |
|  4    | 65         | 23           |
|  5    | 65         | 22           |
|  6    | 66         | 10           |
|  7    | 61         | 22           |
|  8    | 60         | 5            |
|  9    | 63         | 5            |
|  10   | 66         | 22           |
|  11   | 62         | 12           |
+-------+------------+--------------+
</code>```

So far I've tried doing something like this:

SELECT users.id, users.firstName, users.lastName, junc_jobs.fk_case FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE (fk_case IS NULL AND users.fk_role > 1) OR (fk_case != 66 AND  users.fk_role > 1)
ORDER BY firstName
```

<p>BUT if <code>junc_jobs</code> contain users with multiple cases it stops working. We get something like this:</p>

```+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  06   | Ulrik      | 57       |
|  05   | Rasmus     | 57       |
|  12   | Lisa       | 59       |
|  10   | Nick       | 59       |
|  05   | Rasmus     | 59       |
|  23   | Frederik   | 63       |
|  06   | Macro      | 63       |
|  23   | Frederik   | 64       |
|  23   | Frederik   | 65       |
|  22   | Marco      | 65       |
|  10   | Nick       | 65       |
+-------+------------+----------+
```

As you can see, users that are on fk_case = 66 is removed, but if that user is already on other cases they still get shown. User with id = 22 is on fk_case 66 and this user removed from the list completely.

I tried using GROUP BY ID to only show one of each users, but the users that are already on the case and have other cases, is shown too.

答:
Put the fk_case test in the ON clause, and then only show the users with no match.

```<code>SELECT DISTINCT u.id, u.firstName, u.lastName
FROM users as U
LEFT JOIN junc_jobs AS j ON u.id = j.fk_employee AND j.fk_case = 66
WHERE j.fk_case IS NULL AND u.fk_role > 1
</code>```

Body:
Working on selecting all users into an html <select> that doesn't exist in it already.

I am working on a "case" website where I can put users on cases. Users can be put on multiple cases at once. I am making a html <select> with all the users I can add to the case and it is important that already existing users on that case aren't shown.

I have 3 SQL tables. Users, Cases, and Junc_jobs. Junc_Jobs works as a many to many relations to connect users and cases. All the users that I want to select are fk_role > 1.

USERS
+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  05   | Rasmus     | 57       |
|  06   | Ulrik      | 57       |
|  10   | Nick       | 59       |
|  12   | Lisa       | 59       |
|  22   | Marco      | 65       |
|  23   | Frederik   | 63       |
+-------+------------+----------+

CASES
+-------+------------+
|  id   | caseName   |
+-------+------------+
|  57   | case 1     |
|  59   | case 2     |
|  63   | case 3     |
|  64   | case 4     |
|  65   | case 5     |
+-------+------------+

JUNC_JOBS
+-------+------------+--------------+
|  id   | fk_case    | fk_employee  |
+-------+------------+--------------+
|  1    | 57         | 5            |
|  2    | 59         | 5            |
|  3    | 64         | 23           |
|  4    | 65         | 23           |
|  5    | 65         | 22           |
|  6    | 66         | 10           |
|  7    | 61         | 22           |
|  8    | 60         | 5            |
|  9    | 63         | 5            |
|  10   | 66         | 22           |
|  11   | 62         | 12           |
+-------+------------+--------------+

So far I've tried doing something like this:

SELECT users.id, users.firstName, users.lastName, junc_jobs.fk_case FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE (fk_case IS NULL AND users.fk_role > 1) OR (fk_case != 66 AND  users.fk_role > 1)
ORDER BY firstName

BUT if junc_jobs contain users with multiple cases it stops working. We get something like this:

+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  06   | Ulrik      | 57       |
|  05   | Rasmus     | 57       |
|  12   | Lisa       | 59       |
|  10   | Nick       | 59       |
|  05   | Rasmus     | 59       |
|  23   | Frederik   | 63       |
|  06   | Macro      | 63       |
|  23   | Frederik   | 64       |
|  23   | Frederik   | 65       |
|  22   | Marco      | 65       |
|  10   | Nick       | 65       |
+-------+------------+----------+

As you can see, users that are on fk_case = 66 is removed, but if that user is already on other cases they still get shown. User with id = 22 is on fk_case 66 and this user removed from the list completely.

I tried using GROUP BY ID to only show one of each users, but the users that are already on the case and have other cases, is shown too.

Body:
Put the fk_case test in the ON clause, and then only show the users with no match.

SELECT DISTINCT u.id, u.firstName, u.lastName
FROM users as U
LEFT JOIN junc_jobs AS j ON u.id = j.fk_employee AND j.fk_case = 66
WHERE j.fk_case IS NULL AND u.fk_role > 1


问:
How to implement batching in a google app-script to avoid execution timeouts
I found a solution on how to reduce the execution time here but I'm unable to implement it through batching as discussed here. [question]:Google app script timeout ~ 5 minutes?

Sorry, I am completely new to scripts. The script below loops through all sheets and changes the sheetname to the value in A1.

```<code>function onEdit() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();

// Array holding the names of the sheets to exclude from the execution
var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var i=10;i<allsheets.length;i++) {
var sheet = allsheets[i];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is met.
if(exclude.indexOf(sheet.getName())==-1) continue;
}

} // end of loop

} // end of function
</code>```

How can I implement batching on the above script using the example below as a reference to reduce the number of service calls?

for (var i = 1; i <= 100; i++) {
  SpreadsheetApp.getActiveSheet().deleteRow(i);
}

Do this:

SpreadsheetApp.getActiveSheet().deleteRows(i, 100);

答:
Try this:

```<code>function onEdit(e) {
  var sh=e.range.getSheet();
  var name=sh.getName();
  var a1=sh.getRange('A1').getValue();
  if(name!=a1) {
    sh.setName(a1);
  }
}
</code>```

Note: you cannot run this function without the event object.  So you cannot run it from the script editor unless you supply the event object.

Body:
I found a solution on how to reduce the execution time here but I'm unable to implement it through batching as discussed here. [question]:Google app script timeout ~ 5 minutes?

Sorry, I am completely new to scripts. The script below loops through all sheets and changes the sheetname to the value in A1.

function onEdit() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();

// Array holding the names of the sheets to exclude from the execution
var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var i=10;i<allsheets.length;i++) {
var sheet = allsheets[i];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is met.
if(exclude.indexOf(sheet.getName())==-1) continue;
}

} // end of loop

} // end of function

How can I implement batching on the above script using the example below as a reference to reduce the number of service calls?

for (var i = 1; i <= 100; i++) {
  SpreadsheetApp.getActiveSheet().deleteRow(i);
}

Do this:

SpreadsheetApp.getActiveSheet().deleteRows(i, 100);

Body:
Try this:

function onEdit(e) {
  var sh=e.range.getSheet();
  var name=sh.getName();
  var a1=sh.getRange('A1').getValue();
  if(name!=a1) {
    sh.setName(a1);
  }
}

Note: you cannot run this function without the event object.  So you cannot run it from the script editor unless you supply the event object.


答:
`

```<code>$key=array_search($_GET['product'],$_SESSION['product']);
if($key!==false)
unset($_SESSION['product'][$key]);
$_SESSION["product"] = array_values($_SESSION["product"]);
</code>```

`

Maybe this might help!
You need to find the key as this is an array.

EDIT:

Made an example for you, here when you click the link, it deletes the first name from the session array.

```<code><?php
    session_start();
    $_SESSION["user"] = ["fname"=>"William","lname"=>"Henry" ];
    if(isset($_GET["delete"]))
    {
        if($_GET["key"])
        {
            $key=$_GET["key"];
            unset($_SESSION['user'][$key]);
        }
    }
?>
</code>```

HTML on the same page

```<code><h1>
        <?php
            if(isset($_SESSION["user"]["fname"]))echo $_SESSION["user"]["fname"]." ";
            if(isset($_SESSION["user"]["lname"]))echo $_SESSION["user"]["lname"];
        ?>
</h1>
    <a href="<?php echo $_SERVER['PHP_SELF']."?delete=user&key=fname" ?>">Delete First Name</a>
</code>```

If you want to delete the lastname (lname), change the key=lname in the href of the link, hope this example helps in your case

Title: How to delete specific session record by clicking on href?

Body:
I unable to delete specific record from session array. I want to delete specific row in table when I click on delete link.

<?php
session_start();

    if(isset($_GET["product"]) && isset($_GET["category"])){

        $nomProduct = trim($_GET["product"]);
        $category = trim($_GET["category"]);
        $_SESSION['product'][] = array(
            "nomProduct" => $nomProduct ,
            "category" =>  $category

        );

      //session_destroy();

       }
?>

    html table

                <?php foreach($_SESSION["product"] as $items) { ?>

                    <?php echo $items['nomProduct']; ?>
                    <?php echo $items['category']; ?>
                    Delete

                <?php }?>

Body:
`

$key=array_search($_GET['product'],$_SESSION['product']);
if($key!==false)
unset($_SESSION['product'][$key]);
$_SESSION["product"] = array_values($_SESSION["product"]);

`

Maybe this might help!
You need to find the key as this is an array.

EDIT:

Made an example for you, here when you click the link, it deletes the first name from the session array.

<?php
    session_start();
    $_SESSION["user"] = ["fname"=>"William","lname"=>"Henry" ];
    if(isset($_GET["delete"]))
    {
        if($_GET["key"])
        {
            $key=$_GET["key"];
            unset($_SESSION['user'][$key]);
        }
    }
?>

HTML on the same page

<h1>
        <?php
            if(isset($_SESSION["user"]["fname"]))echo $_SESSION["user"]["fname"]." ";
            if(isset($_SESSION["user"]["lname"]))echo $_SESSION["user"]["lname"];
        ?>
</h1>
    <a href="<?php echo $_SERVER['PHP_SELF']."?delete=user&key=fname" ?>">Delete First Name</a>

If you want to delete the lastname (lname), change the key=lname in the href of the link, hope this example helps in your case


问:
How do I fix error: RuntimeException Unmatched delimiter: )
The problem is that if I pass this function (in my REPL) with 08 or 09, it will give me an error.

I've tried removing parenthesizes around to see if the error would go away.

```<code>(defn format-pump-number [number]
  (if (.contains (str number) "0")
    (str number)
    (str "0" number))
    (if (> number 9)
      (if (< number 100)
        (str number)
        (throw (Exception. "Dispenser number can only be 2 characters!"))))
      (str "0" number))
</code>```

I expect [number] to be returned 08 or 09 when passed that exact number.

答:
Computers usually interpret a number like 08 or 09 to be octal, which is an error since octal digits only go from 0..7.  Historically, it was thought that using a leading zero character 0 was a clever type of code, since the character 0 looks like the character O from the word Octal.
So, when the compiler sees an integer starting with a 0, it is interpreted to mean "The digits coming next should be interpreted in base-8, not base-10".  Example:

```<code> 12  =>  twelve (parsed using base-ten)
012  =>  ten    (parsed using base-eight)
</code>```

This attempt to be overly clever causes problems through today, as you have discovered.

So, it is not your function at all, just a bad error message.  Observe:

```<code>(println "val=" 8) => `val= 8`
</code>```

but

```<code>(println "val=" 08)
  => Error refreshing environment: Syntax error reading source at (tst/demo/core.clj:19:20).
</code>```

I do not get an error message regarding "Unmatched delimiter", so I'm not sure how that arose.

Body:
The problem is that if I pass this function (in my REPL) with 08 or 09, it will give me an error.

I've tried removing parenthesizes around to see if the error would go away.

(defn format-pump-number [number]
  (if (.contains (str number) "0")
    (str number)
    (str "0" number))
    (if (> number 9)
      (if (< number 100)
        (str number)
        (throw (Exception. "Dispenser number can only be 2 characters!"))))
      (str "0" number))

I expect [number] to be returned 08 or 09 when passed that exact number.

Body:
Computers usually interpret a number like 08 or 09 to be octal, which is an error since octal digits only go from 0..7.  Historically, it was thought that using a leading zero character 0 was a clever type of code, since the character 0 looks like the character O from the word Octal.
So, when the compiler sees an integer starting with a 0, it is interpreted to mean "The digits coming next should be interpreted in base-8, not base-10".  Example:

 12  =>  twelve (parsed using base-ten)
012  =>  ten    (parsed using base-eight)

This attempt to be overly clever causes problems through today, as you have discovered.

So, it is not your function at all, just a bad error message.  Observe:

(println "val=" 8) => `val= 8`

but

(println "val=" 08)
  => Error refreshing environment: Syntax error reading source at (tst/demo/core.clj:19:20).

I do not get an error message regarding "Unmatched delimiter", so I'm not sure how that arose.


问:
What Is the most popular combination of technologies used to building Reactjs web apps
I'm mid PHP/Laravel developer with some exp in jQuery and Vue.js
I want to start self-learning in reactive JS frameworks (for example ReactJS), because I see is the near future in web development.

I checked the [React + redux] is the most popular technology working on browser side, but what about back-end ?
Secured API to PHP/MySQL? or maybe run apps directly on NodeJS server ? if nodejs env. then where will be storing the data ? SQL? NoSQL?

Tell me please what back-end stack is the most popular? or what stack is the near future ?

What about PWA with ReactJS ?

Thank You!

答:
In my experience node.js is more popular for startups and makes it easy to work with since its all javascript.

Java and C# tend to be popular in large enterprise companies

SQL systems, such as MYSQL and PSQL are by and far the most popular options for both small and large companies.

SQL systems such as, Oracle and Microsoft SQL server, are the most popular in extremely large companies.

MongoDB is the most popular NoSQL db but its not used as often in production.

PHP as a server side language is used in about 80% of websites, but that is mostly because of wordpress, I have personally never seen a React frontend being implemented with a PHP backend.

Django and flask are popular python server frameworks but I find them to be popular with AngularJS( the original angular not angular 2+) not React.

The most common stack Ive seen is React, Redux, Express, PSQL, AWS.

https://w3techs.com/technologies/overview/programming_language/all

https://db-engines.com/en/ranking


问:
Top-bar animates on scroll
I'm looking to recreate the scrolling effect found on here: As you scroll, an orange bar begins to stretch across the top of the screen, and if you scroll back up to the top, it moves back in the other direction.

Would anyone be able to help get me started?

答:
I believe you are looking for a scroll indicator. You can follow this tutorial.

https://www.w3schools.com/howto/howto_js_scroll_indicator.asp

You need the following html, css and js. This will add a progress bar the top which will show how much the page has been scrolled.

Code:

window.onscroll = function() {
  myFunction()
};

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.header {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
  background-color: #f1f1f1;
}

/* The progress container (grey background) */

.progress-container {
  width: 100%;
  height: 8px;
  background: #ccc;
}

/* The progress bar (scroll indicator) */

.progress-bar {
  height: 8px;
  background: #4caf50;
  width: 0%;
}</code>```

Scroll Indicator

 More content ..
```

Title: Top-bar animates on scroll

Body:
I believe you are looking for a scroll indicator. You can follow this tutorial.

https://www.w3schools.com/howto/howto_js_scroll_indicator.asp

You need the following html, css and js. This will add a progress bar the top which will show how much the page has been scrolled.

Code:

window.onscroll = function() {
  myFunction()
};

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}

.header {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
  background-color: #f1f1f1;
}

/* The progress container (grey background) */

.progress-container {
  width: 100%;
  height: 8px;
  background: #ccc;
}

/* The progress bar (scroll indicator) */

.progress-bar {
  height: 8px;
  background: #4caf50;
  width: 0%;
}

<div class="header">
  <h2>Scroll Indicator</h2>
  <div class="progress-container">
    <div class="progress-bar" id="myBar"></div>
  </div>
</div>
<div> More content .. </div>