问:
Duplicating a React app folder does not work?
(This is on a Mac by the way. It seems cp -r on a Mac is "historical" and should be replaced by cp -R).

I tried the following:

```<code>mkdir TryContext
cd TryContext
npx create-react-app my-app
cd my-app
</code>```

and then I made an app that worked, and npm start was able to start the server and run it.

But then if I want to make a version 2 of this app, and started by cloning the folder first:

```<code>cd ..
cp -r my-app my-app-02
</code>```

to copy everything to my-app-02, and cd into that folder and do npm start, it will error, saying

```<code>> my-app@0.1.0 start /Users/username/code/TryContext/my-app-02
> react-scripts start

internal/modules/cjs/loader.js:800
    throw err;
    ^

Error: Cannot find module '../scripts/start'
</code>```

I tried different ways, and tried npm rebuild and then npm start, and it worked. But I thought if you copy a directory "as is", then using it, npm start should start the server without needing to do anything?  Why was that and what ways besides npm rebuild could fix it?

答:
TL;RD: when you copy using cp -r it doesn't really preserve symlinks, it just copies the file contents instead. So npm start can't find necessary symlink in this particular case. One of the possible solutions is to use cp -a when coping, which preserves symlinks and avoids this issue.

Mode detailed answer is here

:)

Body:
(This is on a Mac by the way. It seems cp -r on a Mac is "historical" and should be replaced by cp -R).

I tried the following:

mkdir TryContext
cd TryContext
npx create-react-app my-app
cd my-app

and then I made an app that worked, and npm start was able to start the server and run it.

But then if I want to make a version 2 of this app, and started by cloning the folder first:

cd ..
cp -r my-app my-app-02

to copy everything to my-app-02, and cd into that folder and do npm start, it will error, saying

> my-app@0.1.0 start /Users/username/code/TryContext/my-app-02
> react-scripts start

internal/modules/cjs/loader.js:800
    throw err;
    ^

Error: Cannot find module '../scripts/start'

I tried different ways, and tried npm rebuild and then npm start, and it worked. But I thought if you copy a directory "as is", then using it, npm start should start the server without needing to do anything?  Why was that and what ways besides npm rebuild could fix it?


来源: stackexchange

问:
Route:list works in local machine but gives error on server in laravel
I was updating my server code and everything worked well, even the migration and seeding.

but when I tried login URL it gave me 404 error so I checked and in that process ran then PHP artisan route: list command in the terminal.

and got the error as below:

```<code>PHP artisan route: list

   Illuminate\Contracts\Container\BindingResolutionException  : Target class [App\Http\Controllers\Api\V1\UserController] does not exist.

  at /var/www/html/x/vendor/laravel/framework/src/Illuminate/Container/Container.php:805
    801|
    802|         try {
    803|             $reflector = new ReflectionClass($concrete);
    804|         } catch (ReflectionException $e) {
  > 805|             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
    806|         }
    807|
    808|         // If the type is not instantiable, the developer is attempting to resolve
    809|         // an abstract type such as an Interface or Abstract Class and there is

  Exception trace:

  1   Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}()
      [internal]:0

  2   ReflectionException::("Class App\Http\Controllers\Api\V1\UserController does not exist")
      /var/www/html/x/vendor/laravel/framework/src/Illuminate/Container/Container.php:803

  Please use the argument -v to see more details.

</code>```

it says the given controller cannot be found. I have personally checked the folder and it exists. the permissions are correct and also if I run the same command in the local machine, I do get the route list on the same code.

have tried composer dump-autoload and composer update still no use of that as the error exists. so what's the real issue here. how to solve this issue?

答:
ok found the real issue. it was as below.

```<code>App\Http\Controllers\Api\V1\UserController

WAS CHANGED TO

App\Http\Controllers\API\V1\UserController
</code>```

I thought only windows are not case sensitive to the Caps and small character. As using Mac, I was never able to find it.

Just occurred to check the route list as it might be the case sensitivity, and it was. My bad :/

ContentLicense: CC BY-SA 4.0

Body:
I was updating my server code and everything worked well, even the migration and seeding.

but when I tried login URL it gave me 404 error so I checked and in that process ran then PHP artisan route: list command in the terminal.

and got the error as below:

PHP artisan route: list

   Illuminate\Contracts\Container\BindingResolutionException  : Target class [App\Http\Controllers\Api\V1\UserController] does not exist.

  at /var/www/html/x/vendor/laravel/framework/src/Illuminate/Container/Container.php:805
    801|
    802|         try {
    803|             $reflector = new ReflectionClass($concrete);
    804|         } catch (ReflectionException $e) {
  > 805|             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
    806|         }
    807|
    808|         // If the type is not instantiable, the developer is attempting to resolve
    809|         // an abstract type such as an Interface or Abstract Class and there is

  Exception trace:

  1   Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}()
      [internal]:0

  2   ReflectionException::("Class App\Http\Controllers\Api\V1\UserController does not exist")
      /var/www/html/x/vendor/laravel/framework/src/Illuminate/Container/Container.php:803

  Please use the argument -v to see more details.

it says the given controller cannot be found. I have personally checked the folder and it exists. the permissions are correct and also if I run the same command in the local machine, I do get the route list on the same code.

have tried composer dump-autoload and composer update still no use of that as the error exists. so what's the real issue here. how to solve this issue?

Body:
ok found the real issue. it was as below.

App\Http\Controllers\Api\V1\UserController

WAS CHANGED TO

App\Http\Controllers\API\V1\UserController

I thought only windows are not case sensitive to the Caps and small character. As using Mac, I was never able to find it.

Just occurred to check the route list as it might be the case sensitivity, and it was. My bad :/


问:
Python - Replace only exact word in string
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

```<code>x = "the"
y = "a"
z = "This is the thermometer"
</code>```

答:
```<code>import re

pattern=r'\bthe\b' # \b - start and end of the  word
repl='a'
string = 'This is the thermometer'

string=re.sub(pattern, repl, string)
</code>```

Body:
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

x = "the"
y = "a"
z = "This is the thermometer"


问:
pass an element name to another classes method
I have a feature file where I am passing the tab names like Actions,Workorders,notifications tabs to pageobjects class where the tab element and its actions are defined.
If that tab name is not visible we have to click on arrow button and click on the item . And I named the item as tabNameItem. Not clear on how to add the tab item name in this method. Following method threw an error "Then from the tabs User clicks on "accountWorkOrdersTab"                                  # AccountsPageSteps.from_the_tabs_User_clicks_on_tab(WebElement)
      cucumber.runtime.CucumberException: Don't know how to convert "accountWorkOrdersTab" into org.openqa.selenium.WebElement.    Try writing your own converter:  "
Calling method:

```<code>@Then("^from the tabs User clicks on \"([^\"]*)\"$")
public void from_the_tabs_User_clicks_on_tab(WebElement tabname) throws Throwable {
    serviceCloudAccountsPageObject.openAccountsTabs(tabname);
}
</code>```

Action class:

```<code>@FindBy(xpath = "//a[@text()='Work Order')]")
public WebElement accountWorkOrdersTab;

@FindBy(xpath = "//span[contains(.,'Work Order')]")
public WebElement accountWorkOrdersTabItem;
</code>```

public void openAccountsTabs(WebElement tabName) {

```<code>    if(verificationHelper.isDisplayed(tabName)){
        tabName.click();
        System.out.println(tabName.getText() +" tab displayed & is clicked");
    }
    else {

        moreTab.click();
        accountWorkOrdersTabItem.click();
        System.out.println("WorkOrder tab not displayed & is clicked from More tab");

    }
}
</code>```

}

答:
Dont pass the WebElement in feature file, Just pass the string .
from_the_tabs_User_clicks_on_tab(String tabname)

Based on this string value you can use a case statment and return the webElement.

```<code>public WebElement returnElement(String tabname) {
    WebElement returnElement = null;

    switch (elementName) {
    case "tabname1":
        returnElement = driver.findElement(By.xpath("//a[@text()='Work Order')]"));
        break;
    case "tabname2":
        returnElement = driver.findElement(By.xpath("//span[contains(.,'Wor Order')]"));;
        break;
default:
        break;
    }

    return returnElement;
}
</code>```

With the above code you should get the required web element and you can do your actions on the return Element.

Hope you got the idea.

Body:
I have a feature file where I am passing the tab names like Actions,Workorders,notifications tabs to pageobjects class where the tab element and its actions are defined.
If that tab name is not visible we have to click on arrow button and click on the item . And I named the item as tabNameItem. Not clear on how to add the tab item name in this method. Following method threw an error "Then from the tabs User clicks on "accountWorkOrdersTab"                                  # AccountsPageSteps.from_the_tabs_User_clicks_on_tab(WebElement)
      cucumber.runtime.CucumberException: Don't know how to convert "accountWorkOrdersTab" into org.openqa.selenium.WebElement.    Try writing your own converter:  "
Calling method:

@Then("^from the tabs User clicks on \"([^\"]*)\"$")
public void from_the_tabs_User_clicks_on_tab(WebElement tabname) throws Throwable {
    serviceCloudAccountsPageObject.openAccountsTabs(tabname);
}

Action class:

@FindBy(xpath = "//a[@text()='Work Order')]")
public WebElement accountWorkOrdersTab;

@FindBy(xpath = "//span[contains(.,'Work Order')]")
public WebElement accountWorkOrdersTabItem;

public void openAccountsTabs(WebElement tabName) {

    if(verificationHelper.isDisplayed(tabName)){
        tabName.click();
        System.out.println(tabName.getText() +" tab displayed & is clicked");
    }
    else {

        moreTab.click();
        accountWorkOrdersTabItem.click();
        System.out.println("WorkOrder tab not displayed & is clicked from More tab");

    }
}

}

Body:
Dont pass the WebElement in feature file, Just pass the string .
from_the_tabs_User_clicks_on_tab(String tabname)

Based on this string value you can use a case statment and return the webElement.

public WebElement returnElement(String tabname) {
    WebElement returnElement = null;

    switch (elementName) {
    case "tabname1":
        returnElement = driver.findElement(By.xpath("//a[@text()='Work Order')]"));
        break;
    case "tabname2":
        returnElement = driver.findElement(By.xpath("//span[contains(.,'Wor Order')]"));;
        break;
default:
        break;
    }

    return returnElement;
}

With the above code you should get the required web element and you can do your actions on the return Element.

Hope you got the idea.


问:
Get new data when paging dates
I'd like to grab a new chunk of data via an Ajax call whenever the user switches date ranges-- IE, clicks Next Day button, switches modes, etc.

I think I should use viewDisplay(view), but that seems like it's too late-- the data has already been loaded?

Should I use viewDisplay(view) and do an ajax call and set-- something?  Or should I be looking at a different "event" in the calendar?

Thanks!

答:
Direct qutoe form the documentation

$('#calendar').fullCalendar({
      events: '/myfeed.php' }); Here is a URL that FullCalendar might visit:

/myfeed.php?start=1262332800&end=1265011200&_=1263178646

The _ parameter is automatically
  inserted to prevent the browser from
  caching the result

You should have a page that accepts this parameter- queries your DB, gets an array/table back in the format of event object

http://arshaw.com/fullcalendar/docs/event_data/Event_Object/

Then serialize that to a JSON using a library, remember to format time in ISO8601 !! AND fullcalendar request time using UNIX Timestamps...

Goodluck

ContentLicense: CC BY-SA 3.0

Title: Get new data when paging dates


问:
Form Recognizer invalid model status
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

```<code>{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check
</code>```

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor

答:
Could you explain your thought in details?

Here is what I did.

I generated the SAS token without applying any access policy. SAS is generated for whole container. I just chose Read, List permissions from the list and expiration date.

I am wondered that if I keep training data set under root folder then everything is OK. But when I put files under folder structure then the form recognizer service can't find those files.

Title: Form Recognizer invalid model status

Body:
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor


问:
How can I access a other html file when the device width equals the width of a mobile?
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.

.fullscreen-bg {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  z-index: -100;
}

.fullscreen-bg__video {
  position: absolute;
  top: 30%;
  left: center;
  width: 98%;
  height: 50%;
}

html {
  font-family: 'Montserrat', Arial, Helvetica, sans-serif;
  margin-top: 20px;
  margin: 1%;
  box-shadow: 0 1px 10px white, 0 0 40px black, 0 0 80px white;
  color: black;
  height: 96%;
  width: 98%;
}

body {
  background-color: white;
  float: center;
}

h1 {
  color: black;
  text-align: center;
  font-size: 25px;
  margin-bottom: 5px;
  text-shadow: 1px 1px 4px gray, 1px 1px 4px white;
}

p {
  color: black;
  text-align: center;
  margin-top: 0px;
  font-size: 15px;
}

header {
  padding: 1px;
  margin: auto;
  box-shadow: 0 0 10px white, 0 0 20px white;
}

nav {
  margin-left: auto;
  margin-top: 50px;
  margin-bottom: auto;
  float: left;
  background-color: white;
  height: auto;
  width: auto;
}

article {
  float: center;
  margin-top: 50px;
  margin-bottom: auto;
  width: auto;
  height: 100%;
}

/*NAV Menu*/

.overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: white;
  overflow-x: hidden;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 25%;
  width: 100%;
  text-align: center;
  margin-top: 30px;
  color: black;
}

.overlay a {
  padding: 8px;
  text-decoration: none;
  font-size: 36px;
  color: black;
  display: block;
  transition: 0.3s;
}

.overlay a:hover,
.overlay a:focus {
  color: rgb(0, 0, 0, 0.2);
}

.overlay .closebtn {
  position: absolute;
  top: 20px;
  right: 45px;
  font-size: 60px;
}

span {
  color: black;
  width: auto;
  height: auto;
  margin-top: 1%;
  float: right;
  margin-right: 1%;
}

/*Responsive*/

@media screen and (max-height: 450px) {
  .overlay a {
    font-size: 20px
  }
  .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
  }
}

footer {
  float: center;
  margin: auto;
  margin-top: 60%;
}

p1 {
  text-align: left;
}

.style {
  font-size: 30px;
  cursor: pointer;
  font-family: monospace, arial;
}

span {
  color: black;
  width: auto;
  height: auto;
  margin-top: 1%;
  float: right;
  margin-right: 1%;
}

/*LOGO*/

img.ri {
  position: absolute;
  max-width: 80%;
  top: 10%;
  left: 10%;
  border-radius: 3px;
  width: 100px;
  height: 100px;
}

img.ri:empty {
  top: 55%;
  left: 49%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

@media only screen and (max-width: 500px) {
  html {
    background-image: url("C:/Users/Joalu/Desktop/WebApp/img/indexbackground.png");
    font-family: 'Lato';
    width: auto;
    height: 1908px;
    overflow-x: hidden;
    background-repeat: no-repeat;
  }
  body {
    margin: 0;
  }
  header {
    text-align: center;
  }
  h1 {
    font-size: 20px;
    color: white;
    margin-top: 3px;
    font-family: 'Lato';
  }
  h2 {
    display: block;
  }
  .btnheader {
    background-color: rgb(0, 0, 0, 0.5);
    border: 0;
    width: 485px;
    height: 87px;
    text-align: center;
    cursor: pointer;
    box-shadow: 0 0 30px white;
  }
  .overlay {
    background-color: rgb(0, 0, 0, 0.5);
    margin-top: 30px;
    text-align: center;
  }
  .btn-group button {
    background-color: rgb(0, 0, 0, 0.5);
    /* Green background */
    border: 0.5px solid rgb(0, 0, 0, 0.5);
    color: white;
    /* White text */
    padding: 20px 33px;
    /* Some padding */
    cursor: pointer;
    /* Pointer/hand icon */
    float: left;
    /* Float the buttons side by side */
    font-family: 'Lato', arial;
    width: 120.7px;
    text-align: center;
  }
  /* Clear floats (clearfix hack) */
  .btn-group:after {
    content: "";
    clear: both;
    display: table;
  }
  .btn-group button:not(:last-child) {
    border-right: none;
    /* Prevent double borders */
  }
  /* Add a background color on hover */
  .btn-group button:hover {
    background-color: rgb(0, 0, 0, 0.3);
    border: 0px;
    box-shadow: 0 0 40px black, 0 0 15px white;
  }
  .dot {
    height: 258px;
    width: 258px;
    background-color: rgb(0, 0, 0, 0);
    border-radius: 100%;
    display: inline-block;
    margin-top: 670px;
    cursor: pointer;
  }
  .dot:hover {
    box-shadow: 0 0 50px white;
  }
  img.ri {
    position: absolute;
    max-width: 80%;
    top: 20%;
    left: 10%;
    border-radius: 3px;
    width: 500px;
    height: 500px;
    margin-top: 140px;
  }
  img.ri:empty {
    top: 35%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  img.ri:hover {
    box-shadow: 0 0 10px gray, 0 0 40px black;
  }
  .footer {
    padding: 5%;
    height: 464px;
    width: 500px;
    background-color: rgb(0, 0, 0, 0.8);
    margin-top: 320px;
    color: white;
  }
  h3 {
    text-align: center;
    color: white;
    margin-top: 380px;
  }
  .bordr {
    border: 5px;
    height: auto;
    width: auto
  }
  p {
    text-align: center;
    color: white;
    font-family: 'Lato', arial;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="css/MainCSS.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/png" href="image/favicon.png" sizes="32x32">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <title>
    scxry
  </title>
</head>

<body>
  <div class="fullscreen-bg">
    <video loop muted autoplay poster="img/videoframe.jpg" class="fullscreen-bg__video">
        <source src="video/12345.mp4" type="video/mp4">
    </video>
  </div>
  <header>
    <span class="style" onclick="openNav()">☰</span>

  </header>

  <script type="text/javascript">
    if (screen.width <= 500) {
      document.location = "webapp.html";
    }
  </script>

  <nav>
    <div id="myNav" class="overlay">
      ×
      <div class="overlay-content">
        Home
        Store
        Social Media
        Contact
        FAQ
        <p>scxry cmpny est. 2020
          <p>
      </div>
    </div>
  </nav>

  <img src="image/scxrylogo800back.png" class="ri" />

  <script>
    function openNav() {
      document.getElementById("myNav").style.width = "100%";
    }

    function closeNav() {
      document.getElementById("myNav").style.width = "0%";
    }
  </script>

</body>

</html></code>```

@media only screen and (max-width: 500px) {

    html{
        background-image: url("C:/Users/Joalu/Desktop/scxryshop.de/image/webappbackground.png");
        font-family:  'Lato';
        width: auto;
        height: 1908px;
        overflow-x: hidden;
        background-repeat: no-repeat;
    }

    body{
        margin: 0;
    }

    header{
        text-align: center;
    }

    h1 {
        font-size: 20px;
        color: white;
        margin-top: 3px;
        font-family:   'Lato';
    }

    h2 {
        display: block;

    }

    .btnheader {
        background-color: rgb(0, 0, 0,0.5);
        border: 0;
        width: 485px;
        height: 87px;
        text-align: center;
        cursor: pointer;
        box-shadow: 0 0 30px white;
    }

    .overlay {
        background-color: rgb(0, 0, 0,0.5);
        margin-top: 30px ;
        text-align: center;
    }

    .btn-group button {
        background-color: rgb(0, 0, 0,0.5); /* Green background */
        border: 0.5px solid rgb(0, 0, 0,0.5);
        color: white; /* White text */
        padding: 20px 33px; /* Some padding */
        cursor: pointer; /* Pointer/hand icon */
        float: left;/* Float the buttons side by side */
        font-family:  'Lato', arial;
        width: 120.7px;
        text-align: center;

      }

      /* Clear floats (clearfix hack) */
      .btn-group:after {
        content: "";
        clear: both;
        display: table;
      }

      .btn-group button:not(:last-child) {
        border-right: none; /* Prevent double borders */
      }

      /* Add a background color on hover */
      .btn-group button:hover {
        background-color: rgb(0, 0, 0,0.3);
        border: 0px;
        box-shadow: 0 0 40px black, 0 0 15px white;
      }

      .dot {
        height: 258px;
        width: 258px;
        background-color: rgb(0, 0, 0,0);
        border-radius: 100%;
        display: inline-block;
        margin-top: 670px;
        cursor: pointer;
      }

      .dot:hover {
          box-shadow: 0 0 50px white;
      }

      img.ri{
        position: absolute;
        max-width: 80%;
        top: 20%;
        left: 10%;
        border-radius: 3px;
        width: 500px;
        height: 500px;
        margin-top: 140px;
    }

    img.ri:empty{
        top: 35%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

    img.ri:hover{
        box-shadow: 0 0 10px gray, 0 0 40px black;
    }

    .footer {
            padding: 5%;
            height: 464px;
            width: 500px;
            background-color: rgb(0, 0, 0,0.8);
            margin-top: 320px;
            color: white;
    }

    h3 {
        text-align: center;
        color: white;
        margin-top: 380px;
    }

    .bordr {
        border: 5px;
        height: auto;
        width: auto
    }

    p {
        text-align: center;
        color: white;
        font-family: 'Lato', arial;
    }

}

@media only screen and (max-width: 1920px) {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="css/webappcss.css" type="text/CSS" rel="stylesheet">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">

</head>
<body>
    <header>

        <button class="btnheader">
                <h1>scxry</h1>
        </button>

    </header>
    <body>

      <div class="btn-group">

            <button class="btn1">Media</button>

            <button class="btn2">FAQ</button>

            <button class="btn3">Contact</button>

            <button class="btn4">About</button>
    </div>

               <img src="image/custom.png" class="ri" style="height: auto">

        <div style="text-align:center">

            <span class="dot"></span>

          </div>
          <h3>Blog</h3>
          <div class="bordr">
              <p>This new mobile update will provide you <br> with the
            best experience.<br> Be sure to explore the whole website,<br>
            some personal information about me:</p>
            <p>I'm 15 years old and I'm a student at JKR Wendlingen <br>
            I will finish my school soon and will then go <br>
        to the MES in Kirchheim.</p>
        <p>I was thinking of selling some 3D printed <br>
        products because you can almost make everything <br>
    therefor prototyping is no problem.</p>
    <p>Also I'm looking forward to study abroad <br> and go to the
        US. Thank you so much for visting <br>
        this website if you need any help <br>
        feel free to contact me.
    </p>
    <p><b>THANK YOU!</b></p>
          </div>
          <script type="text/javascript">
            if (screen.width >=  500) {
            document.location = "index.html";
            }
            </script>
</body>
</html></code>```

答:
There are various elements and techniques to responsive design (changing content and/or layout across different device widths). Try not to think about it as a different HTML page but elements on the same page that show and hide according to the device width.

For example: -

```<code><div class="desktop-content">
  <p>This is the content someone will see on a desktop</p>
</div>
<div class="mobile-content">
  <p>This is the mobile content</p>
</div>
</code>```

And then with CSS you can then do something like this: -

```<code>.mobile-content{
  display:none;
}
@media only screen and (max-width: 500px) {
  .desktop-content{
    display:none
  }
  .mobile-content{
    display:block;
  }
}
</code>```

The disadvantage here is that you are asking the browser to load both sets of content but only displaying one so if there are large images or a lot of content involved another approach may be better.

If you MUST have 2 separate HTML files then you can do a JavaScript redirect based on the width of the window to the correct one ... but I would not recommend this approach.

Body:
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.
So i have implemented you code with javascript but i still cant figure out how to do it. Ok Im noob in JS but yeah.
here my code:
First one is my index with CSS
second one is my "webapp" with CSS
And I just doesnt want to work for some reason.
If I try to resize my browser it stays on the indes file.

.fullscreen-bg {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  z-index: -100;
}

.fullscreen-bg__video {
  position: absolute;
  top: 30%;
  left: center;
  width: 98%;
  height: 50%;
}

html {
  font-family: 'Montserrat', Arial, Helvetica, sans-serif;
  margin-top: 20px;
  margin: 1%;
  box-shadow: 0 1px 10px white, 0 0 40px black, 0 0 80px white;
  color: black;
  height: 96%;
  width: 98%;
}

body {
  background-color: white;
  float: center;
}

h1 {
  color: black;
  text-align: center;
  font-size: 25px;
  margin-bottom: 5px;
  text-shadow: 1px 1px 4px gray, 1px 1px 4px white;
}

p {
  color: black;
  text-align: center;
  margin-top: 0px;
  font-size: 15px;
}

header {
  padding: 1px;
  margin: auto;
  box-shadow: 0 0 10px white, 0 0 20px white;
}

nav {
  margin-left: auto;
  margin-top: 50px;
  margin-bottom: auto;
  float: left;
  background-color: white;
  height: auto;
  width: auto;
}

article {
  float: center;
  margin-top: 50px;
  margin-bottom: auto;
  width: auto;
  height: 100%;
}

/*NAV Menu*/

.overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: white;
  overflow-x: hidden;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 25%;
  width: 100%;
  text-align: center;
  margin-top: 30px;
  color: black;
}

.overlay a {
  padding: 8px;
  text-decoration: none;
  font-size: 36px;
  color: black;
  display: block;
  transition: 0.3s;
}

.overlay a:hover,
.overlay a:focus {
  color: rgb(0, 0, 0, 0.2);
}

.overlay .closebtn {
  position: absolute;
  top: 20px;
  right: 45px;
  font-size: 60px;
}

span {
  color: black;
  width: auto;
  height: auto;
  margin-top: 1%;
  float: right;
  margin-right: 1%;
}

/*Responsive*/

@media screen and (max-height: 450px) {
  .overlay a {
    font-size: 20px
  }
  .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
  }
}

footer {
  float: center;
  margin: auto;
  margin-top: 60%;
}

p1 {
  text-align: left;
}

.style {
  font-size: 30px;
  cursor: pointer;
  font-family: monospace, arial;
}

span {
  color: black;
  width: auto;
  height: auto;
  margin-top: 1%;
  float: right;
  margin-right: 1%;
}

/*LOGO*/

img.ri {
  position: absolute;
  max-width: 80%;
  top: 10%;
  left: 10%;
  border-radius: 3px;
  width: 100px;
  height: 100px;
}

img.ri:empty {
  top: 55%;
  left: 49%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

@media only screen and (max-width: 500px) {
  html {
    background-image: url("C:/Users/Joalu/Desktop/WebApp/img/indexbackground.png");
    font-family: 'Lato';
    width: auto;
    height: 1908px;
    overflow-x: hidden;
    background-repeat: no-repeat;
  }
  body {
    margin: 0;
  }
  header {
    text-align: center;
  }
  h1 {
    font-size: 20px;
    color: white;
    margin-top: 3px;
    font-family: 'Lato';
  }
  h2 {
    display: block;
  }
  .btnheader {
    background-color: rgb(0, 0, 0, 0.5);
    border: 0;
    width: 485px;
    height: 87px;
    text-align: center;
    cursor: pointer;
    box-shadow: 0 0 30px white;
  }
  .overlay {
    background-color: rgb(0, 0, 0, 0.5);
    margin-top: 30px;
    text-align: center;
  }
  .btn-group button {
    background-color: rgb(0, 0, 0, 0.5);
    /* Green background */
    border: 0.5px solid rgb(0, 0, 0, 0.5);
    color: white;
    /* White text */
    padding: 20px 33px;
    /* Some padding */
    cursor: pointer;
    /* Pointer/hand icon */
    float: left;
    /* Float the buttons side by side */
    font-family: 'Lato', arial;
    width: 120.7px;
    text-align: center;
  }
  /* Clear floats (clearfix hack) */
  .btn-group:after {
    content: "";
    clear: both;
    display: table;
  }
  .btn-group button:not(:last-child) {
    border-right: none;
    /* Prevent double borders */
  }
  /* Add a background color on hover */
  .btn-group button:hover {
    background-color: rgb(0, 0, 0, 0.3);
    border: 0px;
    box-shadow: 0 0 40px black, 0 0 15px white;
  }
  .dot {
    height: 258px;
    width: 258px;
    background-color: rgb(0, 0, 0, 0);
    border-radius: 100%;
    display: inline-block;
    margin-top: 670px;
    cursor: pointer;
  }
  .dot:hover {
    box-shadow: 0 0 50px white;
  }
  img.ri {
    position: absolute;
    max-width: 80%;
    top: 20%;
    left: 10%;
    border-radius: 3px;
    width: 500px;
    height: 500px;
    margin-top: 140px;
  }
  img.ri:empty {
    top: 35%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  img.ri:hover {
    box-shadow: 0 0 10px gray, 0 0 40px black;
  }
  .footer {
    padding: 5%;
    height: 464px;
    width: 500px;
    background-color: rgb(0, 0, 0, 0.8);
    margin-top: 320px;
    color: white;
  }
  h3 {
    text-align: center;
    color: white;
    margin-top: 380px;
  }
  .bordr {
    border: 5px;
    height: auto;
    width: auto
  }
  p {
    text-align: center;
    color: white;
    font-family: 'Lato', arial;
  }
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="css/MainCSS.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/png" href="image/favicon.png" sizes="32x32">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <title>
    scxry
  </title>

    <video loop muted autoplay poster="img/videoframe.jpg" class="fullscreen-bg__video">
        <source src="video/12345.mp4" type="video/mp4">
    </video>

    ☰

      ×

        Home
        Store
        Social Media
        Contact
        FAQ

scxry cmpny est. 2020

@media only screen and (max-width: 500px) {

    html{
        background-image: url("C:/Users/Joalu/Desktop/scxryshop.de/image/webappbackground.png");
        font-family:  'Lato';
        width: auto;
        height: 1908px;
        overflow-x: hidden;
        background-repeat: no-repeat;
    }

    body{
        margin: 0;
    }

    header{
        text-align: center;
    }

    h1 {
        font-size: 20px;
        color: white;
        margin-top: 3px;
        font-family:   'Lato';
    }

    h2 {
        display: block;

    }

    .btnheader {
        background-color: rgb(0, 0, 0,0.5);
        border: 0;
        width: 485px;
        height: 87px;
        text-align: center;
        cursor: pointer;
        box-shadow: 0 0 30px white;
    }

    .overlay {
        background-color: rgb(0, 0, 0,0.5);
        margin-top: 30px ;
        text-align: center;
    }

    .btn-group button {
        background-color: rgb(0, 0, 0,0.5); /* Green background */
        border: 0.5px solid rgb(0, 0, 0,0.5);
        color: white; /* White text */
        padding: 20px 33px; /* Some padding */
        cursor: pointer; /* Pointer/hand icon */
        float: left;/* Float the buttons side by side */
        font-family:  'Lato', arial;
        width: 120.7px;
        text-align: center;

      }

      /* Clear floats (clearfix hack) */
      .btn-group:after {
        content: "";
        clear: both;
        display: table;
      }

      .btn-group button:not(:last-child) {
        border-right: none; /* Prevent double borders */
      }

      /* Add a background color on hover */
      .btn-group button:hover {
        background-color: rgb(0, 0, 0,0.3);
        border: 0px;
        box-shadow: 0 0 40px black, 0 0 15px white;
      }

      .dot {
        height: 258px;
        width: 258px;
        background-color: rgb(0, 0, 0,0);
        border-radius: 100%;
        display: inline-block;
        margin-top: 670px;
        cursor: pointer;
      }

      .dot:hover {
          box-shadow: 0 0 50px white;
      }

      img.ri{
        position: absolute;
        max-width: 80%;
        top: 20%;
        left: 10%;
        border-radius: 3px;
        width: 500px;
        height: 500px;
        margin-top: 140px;
    }

    img.ri:empty{
        top: 35%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

    img.ri:hover{
        box-shadow: 0 0 10px gray, 0 0 40px black;
    }

    .footer {
            padding: 5%;
            height: 464px;
            width: 500px;
            background-color: rgb(0, 0, 0,0.8);
            margin-top: 320px;
            color: white;
    }

    h3 {
        text-align: center;
        color: white;
        margin-top: 380px;
    }

    .bordr {
        border: 5px;
        height: auto;
        width: auto
    }

    p {
        text-align: center;
        color: white;
        font-family: 'Lato', arial;
    }

}

@media only screen and (max-width: 1920px) {

}

<!DOCTYPE html>

    <link href="css/webappcss.css" type="text/CSS" rel="stylesheet">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">

        <button class="btnheader">

scxry

        </button>

            <button class="btn1">Media</button>

            <button class="btn2">FAQ</button>

            <button class="btn3">Contact</button>

            <button class="btn4">About</button>

Blog

This new mobile update will provide you
 with the
            best experience.
 Be sure to explore the whole website,

            some personal information about me:

I'm 15 years old and I'm a student at JKR Wendlingen

            I will finish my school soon and will then go

        to the MES in Kirchheim.

I was thinking of selling some 3D printed

        products because you can almost make everything

    therefor prototyping is no problem.

Also I'm looking forward to study abroad
 and go to the
        US. Thank you so much for visting

        this website if you need any help

        feel free to contact me.

THANK YOU!

Body:
There are various elements and techniques to responsive design (changing content and/or layout across different device widths). Try not to think about it as a different HTML page but elements on the same page that show and hide according to the device width.

For example: -

<div class="desktop-content">
  <p>This is the content someone will see on a desktop</p>
</div>
<div class="mobile-content">
  <p>This is the mobile content</p>
</div>

And then with CSS you can then do something like this: -

.mobile-content{
  display:none;
}
@media only screen and (max-width: 500px) {
  .desktop-content{
    display:none
  }
  .mobile-content{
    display:block;
  }
}

The disadvantage here is that you are asking the browser to load both sets of content but only displaying one so if there are large images or a lot of content involved another approach may be better.

If you MUST have 2 separate HTML files then you can do a JavaScript redirect based on the width of the window to the correct one ... but I would not recommend this approach.


问:
Why can Razor not see ViewBag, Url.Content, etc. when the layout page is outside ~/Views/Shared?
I'm working on a CSS framework that I can drop in to other projects as a NuGet package.

To keep things clean, the entire framework - views, styles, images, and master pages / layout pages - is actually stored under ~/CssThing/

Works perfectly with the WebForms view engine, but when I move the _layout.cshtml file into ~/CssThing/ and then modify my Razor page to say:

```<code>@{
Layout = "~/CssThing/_layout.cshtml";
}
</code>```

it starts complaining that ViewBag is not defined, or that The name 'Url' does not exist in the current context, or various other bits of weirdness that suggest the view is no longer inheriting from the proper base class.

How can I get this to work?

NOTE: The reason everything's split out like this is there's no way to force NuGet to overwrite existing code, and there's no way to spin up an empty MVC3 web application without picking up all the jQuery, etc. references, so rather than risk my framework getting half-deployed because half the files were already present, I'm keeping everything completely seperate.

答: You need to manually specify @inherits WebViewPage, or add the default Web.config section (which sets the base type) to the folder with the views.

Body:
I'm working on a CSS framework that I can drop in to other projects as a NuGet package.

To keep things clean, the entire framework - views, styles, images, and master pages / layout pages - is actually stored under ~/CssThing/

Works perfectly with the WebForms view engine, but when I move the _layout.cshtml file into ~/CssThing/ and then modify my Razor page to say:

@{
Layout = "~/CssThing/_layout.cshtml";
}

it starts complaining that ViewBag is not defined, or that The name 'Url' does not exist in the current context, or various other bits of weirdness that suggest the view is no longer inheriting from the proper base class.

How can I get this to work?

NOTE: The reason everything's split out like this is there's no way to force NuGet to overwrite existing code, and there's no way to spin up an empty MVC3 web application without picking up all the jQuery, etc. references, so rather than risk my framework getting half-deployed because half the files were already present, I'm keeping everything completely seperate.


答:
In your case you can use re.sub(x, y, z).
You can read the documentation here for more information.

Title: Python - Replace only exact word in string


问:
How to output the result of a chain of commands for a given input with bash
In reference to this question I still struggle the following single-liner to work

```<code>kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done
</code>```

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

```<code>bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

</code>```

Same results with a slightly different approach:

```<code>kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done
</code>```

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

```<code>do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;
</code>```

or

```<code>$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh
</code>```

答:
A parameter expansion might be what you want/need, instead of embedding grep and cut inside a while read loop.

```<code>#!/usr/bin/env bash

kubectl get ns | while IFS= read -r line; do
  [[ $line == Term ]] && ns=${line% *}
  echo "$ns"
done
</code>```

Depending on the pattern match, you might need *Term*

Body:
In reference to this question I still struggle the following single-liner to work

kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

Same results with a slightly different approach:

kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;

or

$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh

Body:
A parameter expansion might be what you want/need, instead of embedding grep and cut inside a while read loop.

#!/usr/bin/env bash

kubectl get ns | while IFS= read -r line; do
  [[ $line == Term ]] && ns=${line% *}
  echo "$ns"
done

Depending on the pattern match, you might need *Term*


问:
how to add a flat text file to BaseX?
What does it mean "content is not allowed in prolog"?  Perhaps the input method needs to be set first?  I'm trying to add data to an empty database in Basex with dummy data as below:

```<code>thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> open people
Database 'people' was opened in 199.0 ms.
>
> add to people /home/thufir/flwor/people/people.txt
"/home/thufir/flwor/people/people.txt" (Line 2): Content is not allowed in prolog.
>
> exit
Have a nice day.
thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ cat people.txt

a
1
2
3
b
4
5
6
c
7
8
9

thufir@dur:~/flwor/people$
</code>```

I could make it CSV or other, but would like to use just plain text.

Certainly it can be added through the GUI as:

Selecting the file:

答:
Okay, that was perhaps a silly question:</p>

```<code>>
> list
Name                 Resources  Size    Input Path
-------------------------------------------------------------------------------
com.w3schools.books  1          6290    https://www.w3schools.com/xml/books.xml
dummy                1          21119
foo                  1          167152  /home/thufir/basex/foo/foo.fodt
people               1          4610
text                 1          55302   /home/thufir/Desktop/text.txt
twitter              45         366800
w3school_data        1          5209    https://www.w3schools.com/xml/note.xml

7 database(s).
> drop database people
Database 'people' was dropped.
>
> create database people
Database 'people' created in 79.03 ms.
>
> open people
Database 'people' was opened in 0.05 ms.
>
> set parser text
PARSER: text
>
> add to people /home/thufir/flwor/people/people.txt
Resource(s) added in 9.18 ms.
>
> list
Name                 Resources  Size    Input Path
-------------------------------------------------------------------------------
com.w3schools.books  1          6290    https://www.w3schools.com/xml/books.xml
dummy                1          21119
foo                  1          167152  /home/thufir/basex/foo/foo.fodt
people               1          4610
text                 1          55302   /home/thufir/Desktop/text.txt
twitter              45         366800
w3school_data        1          5209    https://www.w3schools.com/xml/note.xml

7 database(s).
>
> exit
Have fun.
thufir@dur:~/flwor/people$
</code>```

Title: how to add a flat text file to BaseX?

Body:
What does it mean "content is not allowed in prolog"?  Perhaps the input method needs to be set first?  I'm trying to add data to an empty database in Basex with dummy data as below:

thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> open people
Database 'people' was opened in 199.0 ms.
>
> add to people /home/thufir/flwor/people/people.txt
"/home/thufir/flwor/people/people.txt" (Line 2): Content is not allowed in prolog.
>
> exit
Have a nice day.
thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ cat people.txt

a
1
2
3
b
4
5
6
c
7
8
9

thufir@dur:~/flwor/people$

I could make it CSV or other, but would like to use just plain text.

Certainly it can be added through the GUI as:

Selecting the file:

Body:
Okay, that was perhaps a silly question:

>
> list
Name                 Resources  Size    Input Path
-------------------------------------------------------------------------------
com.w3schools.books  1          6290    https://www.w3schools.com/xml/books.xml
dummy                1          21119
foo                  1          167152  /home/thufir/basex/foo/foo.fodt
people               1          4610
text                 1          55302   /home/thufir/Desktop/text.txt
twitter              45         366800
w3school_data        1          5209    https://www.w3schools.com/xml/note.xml

7 database(s).
> drop database people
Database 'people' was dropped.
>
> create database people
Database 'people' created in 79.03 ms.
>
> open people
Database 'people' was opened in 0.05 ms.
>
> set parser text
PARSER: text
>
> add to people /home/thufir/flwor/people/people.txt
Resource(s) added in 9.18 ms.
>
> list
Name                 Resources  Size    Input Path
-------------------------------------------------------------------------------
com.w3schools.books  1          6290    https://www.w3schools.com/xml/books.xml
dummy                1          21119
foo                  1          167152  /home/thufir/basex/foo/foo.fodt
people               1          4610
text                 1          55302   /home/thufir/Desktop/text.txt
twitter              45         366800
w3school_data        1          5209    https://www.w3schools.com/xml/note.xml

7 database(s).
>
> exit
Have fun.
thufir@dur:~/flwor/people$


问:
Running text2column for column A:A
I am quite new to VBA scripting, but I have to perform the following actions:

convert a csv file to xls one

in the saved xls file to perform the following actions:
         1. To run Text To Columns  for the data
         2. To define the type of each column ( amount , date, text).
         3. To make the first 0 in Amount&Date columns be visible ( e.g. "04521.6823" & for date "05/02/2020"). Here  I plan to use .NumberFormat option.

I succesfully converted the file, but cannot perform Text2Column part.
My data is only in column A, separator ";", only on sheet1.
Here is the latest code I ran:

```<code> Sub text2columns()
    Dim rg As Range

    Set rg = Range("A:A").CurrentRegion

    rg.TextToColumns Destination:=Range("A:A"), ConsecutiveDelimiter:=True, DataType:=xlDelimited, Space:=True

    End Sub
</code>```

Can anyone help me? I know questions are basic, but need some help to continue.
Thank you!

答:
Fomramt Style ~>  1: tab, 2: comma, 3:space, 4:semiclone, 5:None, 6:User's Letter</p>

```<code>Sub TransToXLSFromCSV()
Dim vFile As Variant
Dim vDB
Dim fn As String
Dim strPath As String
Dim i As Long
Dim Wb As Workbook
    strPath = ThisWorkbook.Path
    vFile = Application.GetOpenFilename("Select Text Files *.txt,*.txt;*.csv", _
      Title:="Select Text Files!", MultiSelect:=True)
    If TypeName(vFile) = "Boolean" Then Exit Sub
    Application.ScreenUpdating = False

    For i = 1 To UBound(vFile)
        fn = Dir(vFile(i))
        fn = Left(fn, Len(fn) - 4)

         Set Wb = Workbooks.Open(Filename:=vFile(i), Format:=2) '<~~ Foramt style comma
         vDB = Wb.ActiveSheet.UsedRange
         Wb.Close
         Set Wb = Workbooks.Add
         With Wb
            .ActiveSheet.Range("a1").Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
            .SaveAs Filename:=strPath & "\" & fn & ".xlsx"
            .Close (0)
         End With
    Next i
    Application.ScreenUpdating = True
End Sub
</code>```

Title: Running text2column for column A:A

Body:
I am quite new to VBA scripting, but I have to perform the following actions:

convert a csv file to xls one

in the saved xls file to perform the following actions:
         1. To run Text To Columns  for the data
         2. To define the type of each column ( amount , date, text).
         3. To make the first 0 in Amount&Date columns be visible ( e.g. "04521.6823" & for date "05/02/2020"). Here  I plan to use .NumberFormat option.

I succesfully converted the file, but cannot perform Text2Column part.
My data is only in column A, separator ";", only on sheet1.
Here is the latest code I ran:

 Sub text2columns()
    Dim rg As Range

    Set rg = Range("A:A").CurrentRegion

    rg.TextToColumns Destination:=Range("A:A"), ConsecutiveDelimiter:=True, DataType:=xlDelimited, Space:=True

    End Sub

Can anyone help me? I know questions are basic, but need some help to continue.
Thank you!

Body:
Fomramt Style ~>  1: tab, 2: comma, 3:space, 4:semiclone, 5:None, 6:User's Letter

Sub TransToXLSFromCSV()
Dim vFile As Variant
Dim vDB
Dim fn As String
Dim strPath As String
Dim i As Long
Dim Wb As Workbook
    strPath = ThisWorkbook.Path
    vFile = Application.GetOpenFilename("Select Text Files *.txt,*.txt;*.csv", _
      Title:="Select Text Files!", MultiSelect:=True)
    If TypeName(vFile) = "Boolean" Then Exit Sub
    Application.ScreenUpdating = False

    For i = 1 To UBound(vFile)
        fn = Dir(vFile(i))
        fn = Left(fn, Len(fn) - 4)

         Set Wb = Workbooks.Open(Filename:=vFile(i), Format:=2) '<~~ Foramt style comma
         vDB = Wb.ActiveSheet.UsedRange
         Wb.Close
         Set Wb = Workbooks.Add
         With Wb
            .ActiveSheet.Range("a1").Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
            .SaveAs Filename:=strPath & "\" & fn & ".xlsx"
            .Close (0)
         End With
    Next i
    Application.ScreenUpdating = True
End Sub


问:
Blazor pages in TOR Browser not rendering
I have an ASP.NET Core 3.1 Blazor Server-Side Application.

Recently a user has complained, that it does not work with the TOR Browser.

So I tried it out and had to find out, it works in only ~50% of all cases.
Every time I tried, I requested a new circuit for the request.
When it worked, everything was fine and even the speed was not that bad.
But if not, first, the tab is loading the source, showing the favicon and then nothing happens for a while.
Sometimes, if you are patient enough it looks like the first render happens, but the second and so on for all the async operations never happens.

Is there a difference between the TOR nodes, that prevents Blazor pages from working properly?

答:
Tor by default blocks javascript, which blazor signalR is based on, so it can't effectively communicate with the server, disable noscript.
Also k</p>


问:
How to know if url is already bookmarked
I am adding bookmark from code. Now in Firefox if user already added the url as bookmark he should not be able to bookmark it again. How can I do it? For now every time a new bookmark is getting created.</p>

答:
If you want to prevent people from clicking a bookmark link on your website for a second time, you could try to write using cookies to hide the link if there's a cookie on the client.

As far as I know trying to check the bookmarks library (Places) in FireFox by using javascript on your website, that is impossible.

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Zaagmans


问:
Magento Model with Foreign Key Constraint
I am trying to create a model in my module that saves data and links against the customer_entity table. I have got the module saving the model without the foreign key constraint but as soon as I alter the table to include the constraint I get an integrity constraint violation exception even though I am including a customer id that exists in the customer_entity table.

Is there something extra I need to do with my model class or model resource class to get the model saving correctly?

答: There's too many things that could be a mitigating factor here.  At some point Magento is running some set of SQL queries that temporarily (or possibly permanently) cause a foreign key constraint.   The only way to solve this is to drop down below the Model layer and look at the actual SQL being run against your database.   </p>


问:
Mongodb returning wrong count
I streamed data from a data file that is a few GB and imported into a Mongo collection. The file was zipped so I did  zcat file.gz | mongoimport  I know that I should be having 454229 documents in the collection. It was empty and the file has 454229 records. After the process, I tried a count and got 459680. I emptied the collection and repeated the process. Same result. Then I tried a distinct on the "_id" column, tried length, and got 454229. To makre sure no other process was changing the data, I tried count and distinct twice, distinct followed by count and then count followed by distinct.

```<code>rs1:PRIMARY> db.amazon_xml_data.distinct("_id").length;
454229
rs1:PRIMARY> db.amazon_xml_data.count({});
459680
rs1:PRIMARY> db.amazon_xml_data.count({});
459680
rs1:PRIMARY> db.amazon_xml_data.distinct("_id").length;
454229
</code>```

Mongo version is 3.2.22. I have this text at the end of the log file too...

```<code>amazon_xml_data 1.11GB
2020-02-15T14:37:07.302+0530    imported 454229 documents
</code>```

So I am almost sure that the number returned by count is wrong.

答:
In 2 cases count may be inaccurate:

After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count may be inaccurate.
  Run validate on each collection on the mongod to restore the correct statistics after an unclean shutdown.

https://docs.mongodb.com/v3.2/reference/command/count/#accuracy-after-unexpected-shutdown

On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

https://docs.mongodb.com/v3.2/reference/method/db.collection.count/#sharded-clusters

Use better:

```<code>db.amazon_xml_data.aggregate(
   [
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)
</code>```

Title: Mongodb returning wrong count

Body:
I streamed data from a data file that is a few GB and imported into a Mongo collection. The file was zipped so I did  zcat file.gz | mongoimport  I know that I should be having 454229 documents in the collection. It was empty and the file has 454229 records. After the process, I tried a count and got 459680. I emptied the collection and repeated the process. Same result. Then I tried a distinct on the "_id" column, tried length, and got 454229. To makre sure no other process was changing the data, I tried count and distinct twice, distinct followed by count and then count followed by distinct.

rs1:PRIMARY> db.amazon_xml_data.distinct("_id").length;
454229
rs1:PRIMARY> db.amazon_xml_data.count({});
459680
rs1:PRIMARY> db.amazon_xml_data.count({});
459680
rs1:PRIMARY> db.amazon_xml_data.distinct("_id").length;
454229

Mongo version is 3.2.22. I have this text at the end of the log file too...

amazon_xml_data 1.11GB
2020-02-15T14:37:07.302+0530    imported 454229 documents

So I am almost sure that the number returned by count is wrong.

Body:
In 2 cases count may be inaccurate:

After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count may be inaccurate.
  Run validate on each collection on the mongod to restore the correct statistics after an unclean shutdown.

https://docs.mongodb.com/v3.2/reference/command/count/#accuracy-after-unexpected-shutdown

On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

https://docs.mongodb.com/v3.2/reference/method/db.collection.count/#sharded-clusters

Use better:

db.amazon_xml_data.aggregate(
   [
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)


问:
How to extract time from CURRENT_TIMESTAMP in Postgresql
Just as we are able to extract the date from timestamps in Postgresql using date(CURRENT_TIMESTAMP), I was wondering if there's a equivalent function to extract time. (formatted as hh:mm:ss)

I want to be able to compare a time value, stored in a column with the time datatype (see https://www.postgresql.org/docs/current/datatype-datetime.html), to the current time just using an SQL query.

Any suggestions are most welcome!

答:
You can either use current_time or casting a timestamp to time: current_timestamp::time

e.g.

```<code>where the_time_column >= current_time - interval '6' hour
</code>```

For details, see Current Date/Time in the Postgres manual

Body:
You can either use current_time or casting a timestamp to time: current_timestamp::time

e.g.

where the_time_column >= current_time - interval '6' hour

For details, see Current Date/Time in the Postgres manual


问:
How do I highlight text linked to from a separate webpage?
I have a web-page with anchor tags that are linked to specific words in another page that contain only the words.

Every single word in the words page is wrapped with an  anchor tag having a unique ID like this:

```<code><a id="a">Капитанская</a>
<a id="b">дочкаБереги</a>
<a id="c">Капитанская</a>
<a id="d">дочкаБереги</a>
</code>```

And in the web-page there are links to those words that look like this:

```<code><a href="website.com/text-page.html#a">Капитанская</a>
<a href="website.com/text-page.html#b">дочкаБереги</a>
</code>```

I need to find a way to highlight the word I'm linking to with a colored background or something like that.

I'm using JavaScript, HTML, CSS and PHP for both the webpages, and don't have the ability to use anything else.

答:
You could use css</p>

```<code>#wordid:target {
    background-color: #ddd;
    -webkit-transition: all 1s linear;
}
</code>```

Body:
I have a web-page with anchor tags that are linked to specific words in another page that contain only the words.

Every single word in the words page is wrapped with an  anchor tag having a unique ID like this:

Капитанская
дочкаБереги
Капитанская
дочкаБереги

And in the web-page there are links to those words that look like this:

Капитанская
дочкаБереги

I need to find a way to highlight the word I'm linking to with a colored background or something like that.

I'm using JavaScript, HTML, CSS and PHP for both the webpages, and don't have the ability to use anything else.

Body:
You could use css

#wordid:target {
    background-color: #ddd;
    -webkit-transition: all 1s linear;
}


问:
PowerShell analysing variables and objects
I found that I do .GetType() and | Get-Member a lot, and sometimes I forget that it's .GetType and I try .Get-Type duh! error!), so I've been writing a function to try and gather that info quickly. This has proven to be quite useful when working on the console (I make sure to put the core command before each output so that I never forget the connection to real commands, so more of a techy summary to keep me connected to the language).

I'm curious if there are additional compound commands to extract useful generic information that we could use to report on the structure of a given object (things that we can quickly obtain in a nicely compact summary format even though more complex commands are required for some useful insight about given objects)?

• $a = @(1,2,"x") ; obj $a. This returns 71 Methods (System.String and System.Int32) Types, so I've removed duplicates down to 50 (good to quickly see what is usable but maybe good to somehow also mention the different Types that are contained in that array?).

• Some input will break the function of course, but even a ScriptBlock example like this also works fine obj {$a; $x}. You can even do things like obj "".GetType() to see the Methods and properties in there.

• The use of .Module in the GetType() might be redundant as usually outputs CommonLanguageRuntimeLibrary, but maybe other useful information from these members (everything is useful at different times of course, but I'm curious for generic summary output)?

• In general any improvements or other compound commands that you use or could be useful to crack open object information in a quick summary view would be great to know? :-)

Updated with -Force that @Clint suggested:

```<code>function obj ($cmd) {
    if ($cmd -eq $null) { Write-Host "Object is `$null" ; return }
    Write-Host "Contents:" -F Cyan
    $cmd
    ""
    Write-Host "(`$object).GetType()" -F Cyan -NoNewline ; Write-Host " :: [BaseType|Name|IsPublic|IsSerial|Module]"
    ($cmd).GetType() | % { "$($_.BaseType), $($_.Name), $($_.IsPublic), $($_.IsSerializable), $($_.Module)" }
    ""
    Write-Host "`$object | Get-Member -Force" -F Cyan
    $m = "" ; $p = "" ; $pp = "" ; $np = "" ; $sp = ""
    $msum = 0 ; $psum = 0 ; $ppsum = 0 ; $npsum = 0 ; $spsum = 0
    $($cmd | Get-Member -Force) | % {
        if ($_.MemberType -eq "Method") { if(!($m -like "*$($_.Name),*")) { $m += "$($_.Name), " ; $msum++ } }
        if ($_.MemberType -eq "Property") { if(!($p -like "*$($_.Name),*")) { $p += "$($_.Name), " ; $psum++ } }
        if ($_.MemberType -eq "ParameterizedProperty") { if(!($pp -like "*$($_.Name),*")) { $pp += "$($_.Name), " ; $ppsum++} }
        if ($_.MemberType -eq "NoteProperty") { if(!($np -like "*$($_.Name),*")) { $np += "$($_.Name), " ; $npsum++ } }
        if ($_.MemberType -eq "ScriptProperty") { if(!($sp -like "*$($_.Name),*")) { $sp += "$($_.Name), " ; $npsum++ } }
    }
    if($msum -ne 0) { Write-Host ":: Method [$msum] => $($m.TrimEnd(", "))" }
    if($psum -ne 0) { Write-Host ":: Property [$psum] => $($p.TrimEnd(", "))" }
    if($ppsum -ne 0) { Write-Host ":: ParameterizedProperty [$ppsum] => $($pp.TrimEnd(", "))" }
    if($npsum -ne 0) { Write-Host ":: NoteProperty [$npsum] => $($np.TrimEnd(", "))" }
    if($spsum -ne 0) { Write-Host ":: ScriptProperty [$spsum] => $($sp.TrimEnd(", "))" }
    ""
}
</code>```

An example of output:

```<code>C:\> $a = @(123,"x")
C:\> def $a
Contents:
123
x

($object).GetType() :: [BaseType|Name|IsPublic|IsSerial|Module]
array, Object[], True, True, CommonLanguageRuntimeLibrary

$object | Get-Member -Force
:: Method [50] => CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToBoolean, ToByte, ToChar, ToDateTime, ToDecimal, ToDouble, ToInt16,
ToInt32, ToInt64, ToSByte, ToSingle, ToString, ToType, ToUInt16, ToUInt32, ToUInt64, Clone, Contains, CopyTo, EndsWith, GetEnumerator,
get_Chars, get_Length, IndexOf, IndexOfAny, Insert, IsNormalized, LastIndexOf, LastIndexOfAny, Normalize, PadLeft, PadRight, Remove, Replace,
Split, StartsWith, Substring, ToCharArray, ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant, Trim, TrimEnd, TrimStart
:: Property [1] => Length
:: ParameterizedProperty [1] => Chars
</code>```

答:
You have summarized it quite well as it is, you might as well add

```<code>object | gm -Force # To add members that are usually hidden by default
</code>```

The Get-Member command uses the Force parameter to add the intrinsic
  members and compiler-generated members of the objects to the display.
  Get-Member gets these members, but it hides them by default.

Intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames)

Compiler-generated get_ and set_ methods

MSDN Doc

```<code>object.PSObject #Wraps the information pertaining to different members
object.PSObject | Select-Object -ExpandProperty Properties #You can do the same for other members
</code>```

```<code>$object |gm -force -static #even with force the static members are not listed by default, so we need to explicitly mention static
</code>```

maybe good to somehow also mention the different Types that are contained in that array?).

```<code>$object | ForEach-Object {$_.GetType().FullName}
</code>```

OffTopic, additionally, if you want to capture the time taken for the function to execute

```<code>$sw = [Diagnostics.Stopwatch]::StartNew()
$sw.Stop()
Write-Host "Execution time" $sw.Elapsed.Milliseconds "ms"
</code>```

Body:
I found that I do .GetType() and | Get-Member a lot, and sometimes I forget that it's .GetType and I try .Get-Type duh! error!), so I've been writing a function to try and gather that info quickly. This has proven to be quite useful when working on the console (I make sure to put the core command before each output so that I never forget the connection to real commands, so more of a techy summary to keep me connected to the language).

I'm curious if there are additional compound commands to extract useful generic information that we could use to report on the structure of a given object (things that we can quickly obtain in a nicely compact summary format even though more complex commands are required for some useful insight about given objects)?

• $a = @(1,2,"x") ; obj $a. This returns 71 Methods (System.String and System.Int32) Types, so I've removed duplicates down to 50 (good to quickly see what is usable but maybe good to somehow also mention the different Types that are contained in that array?).

• Some input will break the function of course, but even a ScriptBlock example like this also works fine obj {$a; $x}. You can even do things like obj "".GetType() to see the Methods and properties in there.

• The use of .Module in the GetType() might be redundant as usually outputs CommonLanguageRuntimeLibrary, but maybe other useful information from these members (everything is useful at different times of course, but I'm curious for generic summary output)?

• In general any improvements or other compound commands that you use or could be useful to crack open object information in a quick summary view would be great to know? :-)

Updated with -Force that @Clint suggested:

function obj ($cmd) {
    if ($cmd -eq $null) { Write-Host "Object is `$null" ; return }
    Write-Host "Contents:" -F Cyan
    $cmd
    ""
    Write-Host "(`$object).GetType()" -F Cyan -NoNewline ; Write-Host " :: [BaseType|Name|IsPublic|IsSerial|Module]"
    ($cmd).GetType() | % { "$($_.BaseType), $($_.Name), $($_.IsPublic), $($_.IsSerializable), $($_.Module)" }
    ""
    Write-Host "`$object | Get-Member -Force" -F Cyan
    $m = "" ; $p = "" ; $pp = "" ; $np = "" ; $sp = ""
    $msum = 0 ; $psum = 0 ; $ppsum = 0 ; $npsum = 0 ; $spsum = 0
    $($cmd | Get-Member -Force) | % {
        if ($_.MemberType -eq "Method") { if(!($m -like "*$($_.Name),*")) { $m += "$($_.Name), " ; $msum++ } }
        if ($_.MemberType -eq "Property") { if(!($p -like "*$($_.Name),*")) { $p += "$($_.Name), " ; $psum++ } }
        if ($_.MemberType -eq "ParameterizedProperty") { if(!($pp -like "*$($_.Name),*")) { $pp += "$($_.Name), " ; $ppsum++} }
        if ($_.MemberType -eq "NoteProperty") { if(!($np -like "*$($_.Name),*")) { $np += "$($_.Name), " ; $npsum++ } }
        if ($_.MemberType -eq "ScriptProperty") { if(!($sp -like "*$($_.Name),*")) { $sp += "$($_.Name), " ; $npsum++ } }
    }
    if($msum -ne 0) { Write-Host ":: Method [$msum] => $($m.TrimEnd(", "))" }
    if($psum -ne 0) { Write-Host ":: Property [$psum] => $($p.TrimEnd(", "))" }
    if($ppsum -ne 0) { Write-Host ":: ParameterizedProperty [$ppsum] => $($pp.TrimEnd(", "))" }
    if($npsum -ne 0) { Write-Host ":: NoteProperty [$npsum] => $($np.TrimEnd(", "))" }
    if($spsum -ne 0) { Write-Host ":: ScriptProperty [$spsum] => $($sp.TrimEnd(", "))" }
    ""
}

An example of output:

C:\> $a = @(123,"x")
C:\> def $a
Contents:
123
x

($object).GetType() :: [BaseType|Name|IsPublic|IsSerial|Module]
array, Object[], True, True, CommonLanguageRuntimeLibrary

$object | Get-Member -Force
:: Method [50] => CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToBoolean, ToByte, ToChar, ToDateTime, ToDecimal, ToDouble, ToInt16,
ToInt32, ToInt64, ToSByte, ToSingle, ToString, ToType, ToUInt16, ToUInt32, ToUInt64, Clone, Contains, CopyTo, EndsWith, GetEnumerator,
get_Chars, get_Length, IndexOf, IndexOfAny, Insert, IsNormalized, LastIndexOf, LastIndexOfAny, Normalize, PadLeft, PadRight, Remove, Replace,
Split, StartsWith, Substring, ToCharArray, ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant, Trim, TrimEnd, TrimStart
:: Property [1] => Length
:: ParameterizedProperty [1] => Chars

Body:
You have summarized it quite well as it is, you might as well add

object | gm -Force # To add members that are usually hidden by default

The Get-Member command uses the Force parameter to add the intrinsic
  members and compiler-generated members of the objects to the display.
  Get-Member gets these members, but it hides them by default.

Intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames)

Compiler-generated get_ and set_ methods

MSDN Doc

object.PSObject #Wraps the information pertaining to different members
object.PSObject | Select-Object -ExpandProperty Properties #You can do the same for other members

$object |gm -force -static #even with force the static members are not listed by default, so we need to explicitly mention static

maybe good to somehow also mention the different Types that are contained in that array?).

$object | ForEach-Object {$_.GetType().FullName}

OffTopic, additionally, if you want to capture the time taken for the function to execute

$sw = [Diagnostics.Stopwatch]::StartNew()
$sw.Stop()
Write-Host "Execution time" $sw.Elapsed.Milliseconds "ms"


问:
How to sort the files according to the time stamp in unix?
How to sort the files according to the time stamp in unix?
I need to sort the files and also based on time they created.</p>

答:
Use -t on ls.  e.g:.

```<code>ls -tr
</code>```

or

```<code>ls -ltr
</code>```

Body:
Use -t on ls.  e.g:.

ls -tr

or

ls -ltr


问:
React - Substitute for `setState` Callback in Functional Components?
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

```<code>const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}
</code>```

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

答:
You can use useEffect hook to see when the state change happend.</p>

```<code>useEffect(() => {
  // do something
  console.log('openDoor change', openDoor)
}, [openDoor]);
</code>```

Body:
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

Body:
You can use useEffect hook to see when the state change happend.

useEffect(() => {
  // do something
  console.log('openDoor change', openDoor)
}, [openDoor]);


问:
Heap space out of memory error in javafx project maven
I wrote my research project using javafx and maven. When I'm trying run some function,  I get error out of memory. I solved this problem in usually console project, but I can't solve the problem in maven.

I checked using memory in task manager and I got information, that my program uses about 2.5-3.0 Gb memory. Maven's app don't give me more than 2gb memory. How to fix this?

I used  environment variables,
configuration in pom.xml:

```<code><configuration><argLine>-Xmx4098m</argLine></configuration>
</code>```

and this

```<code><build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
            <argLine>-Xmx4098m</argLine>
        </configuration>
      </plugin>
    </plugins>
  </build>
</code>```

Maybe I used this incorrect.

答:
You can execute below command before running application</p>

```<code>export JAVA_OPTS="-Xms4098m -Xmx4098m  -XX:NativeMemoryTracking=summary"
</code>```

Body:
I wrote my research project using javafx and maven. When I'm trying run some function,  I get error out of memory. I solved this problem in usually console project, but I can't solve the problem in maven.

I checked using memory in task manager and I got information, that my program uses about 2.5-3.0 Gb memory. Maven's app don't give me more than 2gb memory. How to fix this?

I used  environment variables,
configuration in pom.xml:

<configuration><argLine>-Xmx4098m</argLine></configuration>

and this

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
            <argLine>-Xmx4098m</argLine>
        </configuration>
      </plugin>
    </plugins>
  </build>

Maybe I used this incorrect.

Body:
You can execute below command before running application

export JAVA_OPTS="-Xms4098m -Xmx4098m  -XX:NativeMemoryTracking=summary"


问:
How to delete an index from array in java
I want to delete given index from array and update the array after deleting the index.Array size must be same as previous.

The task is this one

```<code>import java.util.*;
class Example{
    public static void main(String args[]){
        int[] xr={0,10,20,30,40,50,60,70,80,90};
        System.out.println(Arrays.toString(xr));//[0,10,20,30,40,50,60,70,80,90]
        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,30,40,50,60,70,80,90,0]

        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,50,60,70,80,90,0,0]

        delete(3, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,60,70,80,90,0,0,0]
    }
}
</code>```

I tried from this way.but i am not sure this one is correct or not.

```<code>import java.util.*;
class Example{
    public static void main(String args[]){
        int[] xr={0,10,20,30,40,50,60,70,80,90};
        System.out.println(Arrays.toString(xr));//[0,10,20,30,40,50,60,70,80,90]
        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,30,40,50,60,70,80,90,0]

        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,50,60,70,80,90,0,0]

        delete(3, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,60,70,80,90,0,0,0]
    }

    public static void delete(int index,int[] array)
    {
        for (int i = 0; i <array.length ; i++)
        {
            if (i==index)
            {
                array[i]=array[i+1];
            }
            if (i>index && i<array.length-1)
            {
                array[i]=array[i+1];
            }

        }
        array[array.length-1]=0;
    }
}
</code>```

答:
public static void delete(int index,int[] array){
        if(index < 0 || index > array.length){
            return; // or throw error
        }

        for(int cpt = index; cpt < array.length - 1 ; cpt++){
            array[cpt] = array[cpt+1];
        }

        array[array.length - 1] = 0;
    }
```

It works, I hope this is what you wanted

Body:
I want to delete given index from array and update the array after deleting the index.Array size must be same as previous.

The task is this one

import java.util.*;
class Example{
    public static void main(String args[]){
        int[] xr={0,10,20,30,40,50,60,70,80,90};
        System.out.println(Arrays.toString(xr));//[0,10,20,30,40,50,60,70,80,90]
        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,30,40,50,60,70,80,90,0]

        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,50,60,70,80,90,0,0]

        delete(3, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,60,70,80,90,0,0,0]
    }
}

I tried from this way.but i am not sure this one is correct or not.

import java.util.*;
class Example{
    public static void main(String args[]){
        int[] xr={0,10,20,30,40,50,60,70,80,90};
        System.out.println(Arrays.toString(xr));//[0,10,20,30,40,50,60,70,80,90]
        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,30,40,50,60,70,80,90,0]

        delete(2, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,50,60,70,80,90,0,0]

        delete(3, xr); //delete(int index, int[] array)
        System.out.println(Arrays.toString(xr));//[0,10,40,60,70,80,90,0,0,0]
    }

    public static void delete(int index,int[] array)
    {
        for (int i = 0; i <array.length ; i++)
        {
            if (i==index)
            {
                array[i]=array[i+1];
            }
            if (i>index && i<array.length-1)
            {
                array[i]=array[i+1];
            }

        }
        array[array.length-1]=0;
    }
}

Body:
public static void delete(int index,int[] array){
        if(index < 0 || index > array.length){
            return; // or throw error
        }

        for(int cpt = index; cpt < array.length - 1 ; cpt++){
            array[cpt] = array[cpt+1];
        }

        array[array.length - 1] = 0;
    }

It works, I hope this is what you wanted


问:
Cannot setState inside Firestore add promise
At a loss here. I've tried many variations of this but basically I am trying to set the state of uploadRefId to the id returned once I create a new collection. I can see the id is generated via console.log but the setState function does not seem to work within the scope of this promise (the uploadRefId is null)?</p>

```<code>const [uploadRefId, setUploadRefId] = React.useState(null);

let uploadRefCol = await firestore.collection("uploads");
await uploadRefCol.add(uploadData)
  .then( (uploadDataRef) => {
    console.log('uploadDataRef.id: ', uploadDataRef.id);
    setUploadRefId(uploadDataRef.id);
    console.log('uploadRefId', uploadRefId);
  })
  .catch( (error) => {
    console.log('Error!', error)
});
</code>```

答:
Changing state can be funny throughout the life cycle of React.

If your uploadDataRef.id is of type string see if this helps:

```<code>const [uploadRefId, setUploadRefId] = React.useState('');
</code>```

If it is a numeric value see if setUploadRefId works with this:

```<code>const [uploadRefId, setUploadRefId] = React.useState(0);
</code>```

This may not be a solution per say but it could lead you to one.

Body:
At a loss here. I've tried many variations of this but basically I am trying to set the state of uploadRefId to the id returned once I create a new collection. I can see the id is generated via console.log but the setState function does not seem to work within the scope of this promise (the uploadRefId is null)?

const [uploadRefId, setUploadRefId] = React.useState(null);

let uploadRefCol = await firestore.collection("uploads");
await uploadRefCol.add(uploadData)
  .then( (uploadDataRef) => {
    console.log('uploadDataRef.id: ', uploadDataRef.id);
    setUploadRefId(uploadDataRef.id);
    console.log('uploadRefId', uploadRefId);
  })
  .catch( (error) => {
    console.log('Error!', error)
});

Body:
Changing state can be funny throughout the life cycle of React.

If your uploadDataRef.id is of type string see if this helps:

const [uploadRefId, setUploadRefId] = React.useState('');

If it is a numeric value see if setUploadRefId works with this:

const [uploadRefId, setUploadRefId] = React.useState(0);

This may not be a solution per say but it could lead you to one.


答:
I'll tell you that it works pretty much in the same way as this.setState, you just a pass a callback function which takes previous state as a parameter and returns new state(docs)

```<code>const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);

  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
    setTimeout(() => setOpenDoor(prevDoor => !prevDoor), 500)
  }
  return(...);
}
</code>```

In order for you know when it changes you can use useEffect callback, which's gonna be called each time something changes in the dependencies array(docs)

```<code>const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);

  useEffect(() => {
    console.log('openDoor changed!', openDoor)
  }, [openDoor])

  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
    setTimeout(() => setOpenDoor(prevDoor => !prevDoor), 500)
  }
  return(...);
}
</code>```

:)

Title: React - Substitute for `setState` Callback in Functional Components?

Body:
I'll tell you that it works pretty much in the same way as this.setState, you just a pass a callback function which takes previous state as a parameter and returns new state(docs)

const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);

  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
    setTimeout(() => setOpenDoor(prevDoor => !prevDoor), 500)
  }
  return(...);
}

In order for you know when it changes you can use useEffect callback, which's gonna be called each time something changes in the dependencies array(docs)

const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);

  useEffect(() => {
    console.log('openDoor changed!', openDoor)
  }, [openDoor])

  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
    setTimeout(() => setOpenDoor(prevDoor => !prevDoor), 500)
  }
  return(...);
}

:)


问:
How to format as Text using Text-To-Columns
This code works using text to columns to separate column A into as many columns as I need, but I cannot figure out a way to make it do this with all columns outputted into text format.

```<code>Sub TxT_to_Columns()
    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
    Destination:=Range("A1"), _
    DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, _
    Tab:=False, _
    Semicolon:=False, _
    Comma:=False, _
    Space:=False, _
    Other:=True, _
    OtherChar:="|"
End Sub
</code>```

How can I do the same thing but output all columns to text format?

Thank you,

答:
Firstly, all the credit must go to Scott Craner!

I will only show a shorter way of arrays building, as response at what @Sabatino Ognibene asked lately. I am sure that Scott knew that, but he wanted to present the array building in a way able to easily be understood.

```<code>Dim arr() As Variant, i As Long, nrCol As Long
    nrCol = 12 'the number of columns you need to result
    ReDim arr(1 To nrCol) As Variant
    For i = 1 To nrCol
      arr(i) = Array(i, 2) '2 will be used for `Text` formatting.
    Next
</code>```

Body:
This code works using text to columns to separate column A into as many columns as I need, but I cannot figure out a way to make it do this with all columns outputted into text format.

Sub TxT_to_Columns()
    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
    Destination:=Range("A1"), _
    DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, _
    Tab:=False, _
    Semicolon:=False, _
    Comma:=False, _
    Space:=False, _
    Other:=True, _
    OtherChar:="|"
End Sub

How can I do the same thing but output all columns to text format?

Thank you,

Body:
Firstly, all the credit must go to Scott Craner!

I will only show a shorter way of arrays building, as response at what @Sabatino Ognibene asked lately. I am sure that Scott knew that, but he wanted to present the array building in a way able to easily be understood.

Dim arr() As Variant, i As Long, nrCol As Long
    nrCol = 12 'the number of columns you need to result
    ReDim arr(1 To nrCol) As Variant
    For i = 1 To nrCol
      arr(i) = Array(i, 2) '2 will be used for `Text` formatting.
    Next


问:
Java wildcard strange behaviour when class is generic
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

```<code>package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}
</code>```

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

```<code>public class Test<T> {
...
}
</code>```

,

```<code>Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog
</code>```

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

答:
Interesting question.

I confirmed your result by compiling it for myself and indeed it does compile (with warnings) if you add the unused type parameter.  However, it fails to compile again if you actually specify a type for the type parameter:

```<code>    new Test<Object>().test(animalList);
    new Test<Object>().test(mammalList);
    new Test<Object>().test(dogList);
</code>```

My suspicion is that, because you are using an unchecked operation to construct the Test object, the compiler doesn't bother to check the other parameter types and treats the whole thing as unchecked/unsafe.  When you specify the type it reverts back to its previous behaviour.

Body:
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

public class Test<T> {
...
}

,

Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

Body:
Interesting question.

I confirmed your result by compiling it for myself and indeed it does compile (with warnings) if you add the unused type parameter.  However, it fails to compile again if you actually specify a type for the type parameter:

    new Test<Object>().test(animalList);
    new Test<Object>().test(mammalList);
    new Test<Object>().test(dogList);

My suspicion is that, because you are using an unchecked operation to construct the Test object, the compiler doesn't bother to check the other parameter types and treats the whole thing as unchecked/unsafe.  When you specify the type it reverts back to its previous behaviour.


问:
cannot execute scripts through cypher-shell
I'm trying to execute these queries within Cypher-shell environment:

```<code>LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS row
WITH row.Fname AS first, row.Lname AS last
MERGE (p:la {last: last})
MERGE (o:fi {first: first})
MERGE (c:central {name: "central node"})
MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p)
RETURN count(o)
</code>```

I have saved these queries inside a file named "cypher.ex1" and I'm using this command to execute it:

```<code>neo4j@neo4j> :source cypher.ex1
</code>```

but nothing happens. I added ";" to the end of all queries like this:

```<code>LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS row;

WITH row.Fname AS first, row.Lname AS last;

MERGE (p:la {last: last});

MERGE (o:fi {first: first});

MERGE (c:central {name: "central node"});

MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p);

RETURN count(o);
</code>```

I receive this error:

```<code>Query cannot conclude with LOAD CSV (must be RETURN or an update clause) (line 2, column 60 (offset: 60))
"LOAD CSV WITH HEADERS FROM 'file:///subdomainIP.csv' AS row;"
</code>```

What's wrong?

答:
You must only use a semicolon at the end of a Cypher statement, not at the end of every clause.

A Cypher statement usually has a RETURN clause at the end, but it can also end with a clause that writes to the DB (e.g., a CREATE clause) if there is nothing that needs to be returned.

In your particular file, you really only have a single Cypher statement, so delete all the semicolons except the last one.

Body:
I'm trying to execute these queries within Cypher-shell environment:

LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS row
WITH row.Fname AS first, row.Lname AS last
MERGE (p:la {last: last})
MERGE (o:fi {first: first})
MERGE (c:central {name: "central node"})
MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p)
RETURN count(o)

I have saved these queries inside a file named "cypher.ex1" and I'm using this command to execute it:

neo4j@neo4j> :source cypher.ex1

but nothing happens. I added ";" to the end of all queries like this:

LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS row;

WITH row.Fname AS first, row.Lname AS last;

MERGE (p:la {last: last});

MERGE (o:fi {first: first});

MERGE (c:central {name: "central node"});

MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p);

RETURN count(o);

I receive this error:

Query cannot conclude with LOAD CSV (must be RETURN or an update clause) (line 2, column 60 (offset: 60))
"LOAD CSV WITH HEADERS FROM 'file:///subdomainIP.csv' AS row;"

What's wrong?