问:
How can I remove this error when I deploy my React App?
Currently I have a functioning React app that I am able to run on localhost:3000. My current deployment process is as follows: I ran npm run build, and uploaded that file to my shared hosting provider.

I then added a .htaccess file with

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>
</code>```

Then I added "homepage": ".", in the package.json. (I even tried to add the "homepage": "http://websiteexample.com", instead of the . ).

From another post I seen, I even removed the forward slashes in my index.html.

None of this seems to work and gives me a blank page with the following error in the console:
 DevTools failed to load source map: Could not parse content for https://website.com/static/js/main.f532f71f.js.map: Unexpected token < in JSON at position 0

Question: How can I deploy it? Is there something I am missing?

UPDATE: I just deployed another react app, it seems as though this process works fine, but the issue is coming from one of my files... just need to figure out which one

UPDATE 2: I found the file... the error that I am getting now is:
Uncaught TypeError: (0 , kn.forwardRef) is not a function What is this? Will update again soon.

UPDATE 3: I have a modal that takes props, which is making all these issues. BUT why does it fail to render once deployed, but works on localhost? Be back soon with more answers.

Final Update:
The error was coming from the following line"

```<code>{ props.accordion1_1 ?  <Accordion></Accordion> : <Typogrpahy></Typography>}
</code>```

The accordion comes from React Material Ui. So I decided to add a useEffect to watch for the props.

答:
The error was coming from the following line:

```<code>{ props.accordion1_1 ?  <Accordion></Accordion> : <Typogrpahy></Typography>}
</code>```

The accordion comes from React Material Ui. So I decided to add a useEffect to watch for the props.

Body:
Currently I have a functioning React app that I am able to run on localhost:3000. My current deployment process is as follows: I ran npm run build, and uploaded that file to my shared hosting provider.

I then added a .htaccess file with

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

Then I added "homepage": ".", in the package.json. (I even tried to add the "homepage": "http://websiteexample.com", instead of the . ).

From another post I seen, I even removed the forward slashes in my index.html.

None of this seems to work and gives me a blank page with the following error in the console:
 DevTools failed to load source map: Could not parse content for https://website.com/static/js/main.f532f71f.js.map: Unexpected token < in JSON at position 0

Question: How can I deploy it? Is there something I am missing?

UPDATE: I just deployed another react app, it seems as though this process works fine, but the issue is coming from one of my files... just need to figure out which one

UPDATE 2: I found the file... the error that I am getting now is:
Uncaught TypeError: (0 , kn.forwardRef) is not a function What is this? Will update again soon.

UPDATE 3: I have a modal that takes props, which is making all these issues. BUT why does it fail to render once deployed, but works on localhost? Be back soon with more answers.

Final Update:
The error was coming from the following line"

{ props.accordion1_1 ?  <Accordion></Accordion> : <Typogrpahy></Typography>}

The accordion comes from React Material Ui. So I decided to add a useEffect to watch for the props.

Body:
The error was coming from the following line:

{ props.accordion1_1 ?  <Accordion></Accordion> : <Typogrpahy></Typography>}

The accordion comes from React Material Ui. So I decided to add a useEffect to watch for the props.


来源: stackexchange

问:
Sort storage files by modified date in Laravel
I'm building a personal blog using Laravel 8, where the articles are displayed from .md files (no database). Everything works perfectly, but I'm struggling to sort those .md files by the modified date or creation date. Files are placed into the storage folder

Current code:

```<code>        // Getting files from storage:
        $files = Storage::disk('articles')->allFiles();
        $articles = [];

        foreach ($files as $file) {
            $storage = Storage::disk('articles')->get($file);
            array_push($articles, $storage);
            $collection = collect($articles);
        }

        $array = collect($articles);
        $articles = $this->paginate($array);

        return view('pages.home', compact('articles'));
</code>```

I've tried to get file details using the filemtime() function, but I get the following error:

```<code>$filePath = Storage::path($file);
$fileDate = filemtime($filePath);
dd($fileDate);
</code>```
```<code>ErrorException
filemtime(): stat failed for C:\my-project\storage\app\article-file.md
</code>```

stat function returns the same error.

Storage is linked, file exists, it returns the right path...

I'm out of ideas...

答:
Laravel already has method to read last modify file metadata

```<code>Storage::lastModified($name);
</code>```

Link to documantation:
https://laravel.com/docs/8.x/filesystem#file-metadata

ContentLicense: CC BY-SA 4.0

Body:
I'm building a personal blog using Laravel 8, where the articles are displayed from .md files (no database). Everything works perfectly, but I'm struggling to sort those .md files by the modified date or creation date. Files are placed into the storage folder

Current code:

        // Getting files from storage:
        $files = Storage::disk('articles')->allFiles();
        $articles = [];

        foreach ($files as $file) {
            $storage = Storage::disk('articles')->get($file);
            array_push($articles, $storage);
            $collection = collect($articles);
        }

        $array = collect($articles);
        $articles = $this->paginate($array);

        return view('pages.home', compact('articles'));

I've tried to get file details using the filemtime() function, but I get the following error:

$filePath = Storage::path($file);
$fileDate = filemtime($filePath);
dd($fileDate);

ErrorException
filemtime(): stat failed for C:\my-project\storage\app\article-file.md

stat function returns the same error.

Storage is linked, file exists, it returns the right path...

I'm out of ideas...

Body:
Laravel already has method to read last modify file metadata

Storage::lastModified($name);

Link to documantation:
https://laravel.com/docs/8.x/filesystem#file-metadata


问:
Is it possible to make a variable that contains a reference of a function?
for example:

```<code>fun aFunc() {
    print("hello")
}

fun main() {
    val test = aFunc //<-- this does not compile

    test()
}
</code>```

Why is it not possible to make test equal to a reference of aFunc in this case, and is there a correct way to do it?

答:
Yes it is, you can either reference the function directly or create new function which calls the other one, both ways here:

val test = ::aFunc
val test2 = { aFunc() }

test()
test2()
```

Body:
for example:

fun aFunc() {
    print("hello")
}

fun main() {
    val test = aFunc //<-- this does not compile

    test()
}

Why is it not possible to make test equal to a reference of aFunc in this case, and is there a correct way to do it?


问:
Can't use formGroup in my angular project
I try to use formGroup in my angular project, but it returns an error :

Can't bind to 'formGroup' since it isn't a known property of 'form'.

I have imported FormsModule and ReactiveFormsModule into my auth.module and app.module but I can't seem to solve my error. I hope someone will be kind enough to help me, please.

HTML

```<code><form [formGroup]="form" (submit)="submit()">
    <div class="input-field">
        <input id="username" formControlName="username" type="text" required>
        <label for="username">Username</label>
    </div>
    <div class="input-field">
        <input id="email" formControlName="email" type="text" required>
        <label for="email">Email</label>
    </div>
    <div class="input-field">
        <input id="password" formControlName="password" type="password" required>
        <label for="password">Mot de passe</label>
    </div>
    <div class="button-form">
        <button class="custom-btn btn-sign-in" type="submit">S'inscire</button>
    </div>
</form>
</code>```

auth.module

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    CommonModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
})
export class AuthModule { }
</code>```

app.module

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MainComponent } from './pages/main/main.component';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
    MainComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

register.component

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  form: FormGroup;

  constructor(
    private router: Router,
    private formBuilder: FormBuilder
  ) { }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      username: '',
      email: '',
      password: ''
    });
  }

  submit(): void{
    console.log(this.form.getRawValue());
  }

  btnClick() {
    this.router.navigate(['/login']);
  }
}
</code>```

答:
This might be an import issue:
If you're using the RegisterComponent in another module, be sure to add the RegisterComponent to the exports of the AuthModule as well

Also noteworthy is that importing the FormsModule and ReactiveFormsModule into the AppModule makes it available throughout your app

Body:
I try to use formGroup in my angular project, but it returns an error :

Can't bind to 'formGroup' since it isn't a known property of 'form'.

I have imported FormsModule and ReactiveFormsModule into my auth.module and app.module but I can't seem to solve my error. I hope someone will be kind enough to help me, please.

HTML

<form [formGroup]="form" (submit)="submit()">

        <input id="username" formControlName="username" type="text" required>
        Username

        <input id="email" formControlName="email" type="text" required>
        Email

        <input id="password" formControlName="password" type="password" required>
        Mot de passe

        <button class="custom-btn btn-sign-in" type="submit">S'inscire</button>

</form>

auth.module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    CommonModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
})
export class AuthModule { }

app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MainComponent } from './pages/main/main.component';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents,
    MainComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

register.component

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  form: FormGroup;

  constructor(
    private router: Router,
    private formBuilder: FormBuilder
  ) { }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      username: '',
      email: '',
      password: ''
    });
  }

  submit(): void{
    console.log(this.form.getRawValue());
  }

  btnClick() {
    this.router.navigate(['/login']);
  }
}


问:
Powershell - output a foreach loop to one line
I am trying to take the output of my foreach loop and apply the array to a string that reads on one line. Here is my code so far:

```<code>$upper = 65..90
$lower = 97..122
foreach ($i in $upper)
{
[char]$i
}
foreach ($i in $lower)
{
[char]$i
}
</code>```

I'm guessing I need to convert the output of the scriptblock to a variable and use the -join option, but everywhere I look I'm struggling to find how to structure that. Any guidance would be appreciated.

答:
For this particular case, ForEach(type convertToType) is very useful, here is a cool way to get your lower and upper case dictionary string:

```<code>$lowerDict = [string]::new(([int][char]'a'..[int][char]'z').ForEach([char]))
$upperDict = $lowerDict.ToUpper()
</code>```

If you have access to PowerShell Core, it can be reduced to:

```<code>$lowerDict = [string]::new('a'..'z')
$upperDict = $lowerDict.ToUpper()
</code>```

As for what you are struggling on, how to do it with what you currently have (a foreach loop). You can capture all the output from the loop first:

```<code>$upper = foreach ($i in 65..90) { [char]$i }
</code>```

Now, $upper is an array of chars, then to convert it to string, you can either use -join (guessed right) or [string]::new(...) as I did on my previous example:

```<code>$upperDict = -join $upper
# OR
$upperDict = [string]::new($upper)
</code>```

Body:
I am trying to take the output of my foreach loop and apply the array to a string that reads on one line. Here is my code so far:

$upper = 65..90
$lower = 97..122
foreach ($i in $upper)
{
[char]$i
}
foreach ($i in $lower)
{
[char]$i
}

I'm guessing I need to convert the output of the scriptblock to a variable and use the -join option, but everywhere I look I'm struggling to find how to structure that. Any guidance would be appreciated.

Body:
For this particular case, ForEach(type convertToType) is very useful, here is a cool way to get your lower and upper case dictionary string:

$lowerDict = [string]::new(([int][char]'a'..[int][char]'z').ForEach([char]))
$upperDict = $lowerDict.ToUpper()

If you have access to PowerShell Core, it can be reduced to:

$lowerDict = [string]::new('a'..'z')
$upperDict = $lowerDict.ToUpper()

As for what you are struggling on, how to do it with what you currently have (a foreach loop). You can capture all the output from the loop first:

$upper = foreach ($i in 65..90) { [char]$i }

Now, $upper is an array of chars, then to convert it to string, you can either use -join (guessed right) or [string]::new(...) as I did on my previous example:

$upperDict = -join $upper
# OR
$upperDict = [string]::new($upper)


问:
navbar is not appearing on mobile phones view
my problem is when i press on the hamburger menu the whole menu does not appear (in mobile view) - even though i'm sure about the code and it working properly, the only problem in mobile view i can't diplay all the main menu ( work - blog - contact ) so when i hover on the icon i don't get anything.

nav-bar {
  font-size: 18px;
  padding-bottom: 10px;
}

.main-menu {
  list-style-type: none;
}

.main-menu li {
  text-align: center;
  margin: 15px auto;
}

.main-menu a {
  text-decoration: none;
  color: black;
}

.main-menu a:hover {
  text-decoration: overline;
}

.main-menu li i {
  padding-right: 10px;
}

.logo {
  margin-top: 10px;
  margin-left: 20px;
  width: 200px;
}

.logo img {
  width: 40px;
  border-radius: 20px;
  margin-top: 20px;
  margin-left: 30px;
  margin-bottom: 30px;
}

.menu-toggle {
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
  color: black;
  font-size: 24px;
}

.active {
  display: block;
}

.main-menu {
  display: none;
}

@media screen and (min-width: 60rem) {
  /*Desktop view*/
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0;
    min-height: 70px;
  }
  .main-menu {
    display: flex;
    flex-wrap: wrap;
    margin-right: 30px;
  }
  .main-menu li {
    margin: 0px 0px 5px 0px;
  }
  .main-menu a {
    margin-left: 40px;
  }
  /* Hide the menu toogle icon when the full menu is visible */
  .menu-toggle {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav-bar">
  <!-- The Toggle Button is used to hide and show the menu for a Mobile Layout -->
  <span class="menu-toggle">
         <i class="fas fa-bars"></i>
    </span>

    <img src="img/logo.png" alt="Logo">

  <ul class="main-menu">
    <li>
      <i class="fas fa-home"></i>Works
    </li>
    <li>
      <i class="fas fa-university"></i>Blogs
    </li>
    <li>
      <i class="fas fa-headset"></i>Contact
    </li>
  </ul>
</nav></code>```

答:
The main issue was that the menu wasn't being hidden / shown. I corrected that and added a css transition. You can use js instead of the input to keep track of the menu state on mobile.

.nav-bar {
    font-size: 18px;
    padding-bottom: 10px;
    overflow: hidden;
}

.main-menu {
    list-style-type: none;
}

.main-menu li {
    text-align: center;
    margin: 15px auto;
}

.main-menu a {
    text-decoration: none;
    color: black;
}

.main-menu a:hover {
    text-decoration: overline;
}

.main-menu li i {
    padding-right: 10px;
}

.logo {
    margin-top: 10px;
    margin-left: 20px;
    width: 200px;
}

.logo img {
    width: 40px;
    border-radius: 20px;
    margin-top: 20px;
    margin-left: 30px;
    margin-bottom: 30px;
}

.menu-toggle {
    position: absolute;
    top: 10px;
    right: 20px;
    cursor: pointer;
    color: black;
    font-size: 24px;
    width: 32px;
    height: 32px;
}

#menu-toggle-checkbox {
  display: none;
}

.active {
    display: block;
}

.main-menu {
    transform: translate(100%);
    transition: transform 1s;
}

@media screen and  (min-width: 60rem) {
    /*Desktop view*/
    .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 0;
        min-height: 70px;
    }

    .main-menu {
        display: flex;
        flex-wrap: wrap;
        margin-right: 30px;
        transform: translate(0%);
    }

    .main-menu li {
        margin: 0px 0px 5px 0px;
    }

    .main-menu a {
        margin-left: 40px;
    }

    /* Hide the menu toogle icon when the full menu is visible */
    .menu-toggle {
        display: none;
    }
}

@media screen and  (max-width: 60rem) {
  .menu-toggle {
    display: block;
  }

  #menu-toggle-checkbox:checked + .logo + .main-menu {
    transform: translateX(0)
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<nav class="nav-bar">
        <!-- The Toggle Button is used to hide and show the menu for a Mobile Layout -->
        <label class="menu-toggle" for="menu-toggle-checkbox">
          <i class="fa fa-bars"></i>
        </label>
        <input type="checkbox" id="menu-toggle-checkbox"/>

            <img src="img/logo.png" alt="Logo">

        <ul class="main-menu">
            <li>
                <i class="fas fa-home"></i>Works
            </li>
            <li>
                <i class="fas fa-university"></i>Blogs
            </li>
            <li>
                <i class="fas fa-headset"></i>Contact
            </li>
        </ul>
    </nav> </code>```

Body:
my problem is when i press on the hamburger menu the whole menu does not appear (in mobile view) - even though i'm sure about the code and it working properly, the only problem in mobile view i can't diplay all the main menu ( work - blog - contact ) so when i hover on the icon i don't get anything.

nav-bar {
  font-size: 18px;
  padding-bottom: 10px;
}

.main-menu {
  list-style-type: none;
}

.main-menu li {
  text-align: center;
  margin: 15px auto;
}

.main-menu a {
  text-decoration: none;
  color: black;
}

.main-menu a:hover {
  text-decoration: overline;
}

.main-menu li i {
  padding-right: 10px;
}

.logo {
  margin-top: 10px;
  margin-left: 20px;
  width: 200px;
}

.logo img {
  width: 40px;
  border-radius: 20px;
  margin-top: 20px;
  margin-left: 30px;
  margin-bottom: 30px;
}

.menu-toggle {
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
  color: black;
  font-size: 24px;
}

.active {
  display: block;
}

.main-menu {
  display: none;
}

@media screen and (min-width: 60rem) {
  /*Desktop view*/
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0;
    min-height: 70px;
  }
  .main-menu {
    display: flex;
    flex-wrap: wrap;
    margin-right: 30px;
  }
  .main-menu li {
    margin: 0px 0px 5px 0px;
  }
  .main-menu a {
    margin-left: 40px;
  }
  /* Hide the menu toogle icon when the full menu is visible */
  .menu-toggle {
    display: none;
  }
}

      Works

      Blogs

      Contact

Body:
The main issue was that the menu wasn't being hidden / shown. I corrected that and added a css transition. You can use js instead of the input to keep track of the menu state on mobile.

.nav-bar {
    font-size: 18px;
    padding-bottom: 10px;
    overflow: hidden;
}

.main-menu {
    list-style-type: none;
}

.main-menu li {
    text-align: center;
    margin: 15px auto;
}

.main-menu a {
    text-decoration: none;
    color: black;
}

.main-menu a:hover {
    text-decoration: overline;
}

.main-menu li i {
    padding-right: 10px;
}

.logo {
    margin-top: 10px;
    margin-left: 20px;
    width: 200px;
}

.logo img {
    width: 40px;
    border-radius: 20px;
    margin-top: 20px;
    margin-left: 30px;
    margin-bottom: 30px;
}

.menu-toggle {
    position: absolute;
    top: 10px;
    right: 20px;
    cursor: pointer;
    color: black;
    font-size: 24px;
    width: 32px;
    height: 32px;
}

#menu-toggle-checkbox {
  display: none;
}

.active {
    display: block;
}

.main-menu {
    transform: translate(100%);
    transition: transform 1s;
}

@media screen and  (min-width: 60rem) {
    /*Desktop view*/
    .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 0;
        min-height: 70px;
    }

    .main-menu {
        display: flex;
        flex-wrap: wrap;
        margin-right: 30px;
        transform: translate(0%);
    }

    .main-menu li {
        margin: 0px 0px 5px 0px;
    }

    .main-menu a {
        margin-left: 40px;
    }

    /* Hide the menu toogle icon when the full menu is visible */
    .menu-toggle {
        display: none;
    }
}

@media screen and  (max-width: 60rem) {
  .menu-toggle {
    display: block;
  }

  #menu-toggle-checkbox:checked + .logo + .main-menu {
    transform: translateX(0)
  }

}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<nav class="nav-bar">
        <!-- The Toggle Button is used to hide and show the menu for a Mobile Layout -->
        <label class="menu-toggle" for="menu-toggle-checkbox">
          <i class="fa fa-bars"></i>
        </label>
        <input type="checkbox" id="menu-toggle-checkbox"/>
        <a href="#" class="logo">
            <img src="img/logo.png" alt="Logo">
        </a>
        <ul class="main-menu">
            <li>
                <a href="#"><i class="fas fa-home"></i>Works</a>
            </li>
            <li>
                <a href="#"><i class="fas fa-university"></i>Blogs</a>
            </li>
            <li>
                <a href="#"><i class="fas fa-headset"></i>Contact</a>
            </li>
        </ul>
    </nav>


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
casperOne is correct.  Once you reach a certain threshold, the Append() method becomes slower than AppendFormat(). Here are the different lengths and elapsed ticks of 100,000 iterations of each method:

Length: 1

```<code>Append()       - 50900
AppendFormat() - 126826
</code>```

Length: 1000

```<code>Append()       - 1241938
AppendFormat() - 1337396
</code>```

Length: 10,000

```<code>Append()       - 12482051
AppendFormat() - 12740862
</code>```

Length: 20,000

```<code>Append()       - 61029875
AppendFormat() - 60483914
</code>```

When strings with a length near 20,000 are introduced, the AppendFormat() function will slightly outperform Append().

Why does this happen? See casperOne's answer.

Edit:

I reran each test individually under Release configuration and updated the results.

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

Body:
casperOne is correct.  Once you reach a certain threshold, the Append() method becomes slower than AppendFormat(). Here are the different lengths and elapsed ticks of 100,000 iterations of each method:

Length: 1

Append()       - 50900
AppendFormat() - 126826

Length: 1000

Append()       - 1241938
AppendFormat() - 1337396

Length: 10,000

Append()       - 12482051
AppendFormat() - 12740862

Length: 20,000

Append()       - 61029875
AppendFormat() - 60483914

When strings with a length near 20,000 are introduced, the AppendFormat() function will slightly outperform Append().

Why does this happen? See casperOne's answer.

Edit:

I reran each test individually under Release configuration and updated the results.

OwnerDisplayName: John Rasch

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: John Rasch


问:
How to compare string, object with string?
I am new to c#. I have a few (string, object) that I need to compare to a string.

string, object looks like: [password, helloworld]  and my string looks like 'helloworld'

When I try to do if(A == B) I get the following error:

```<code>Operator '==' cannot be applied to operands of type '(string, object)' and 'string'
</code>```

[password, helloworld] is a System.Collections.Generic.Dictionary`2[System.String,System.Object]

答:
Just going off of the error you're getting it looks like you are using a C# Tuple type. Like the comments on your post are saying, you need to reference the item inside of the tuple, rather than compare the tuple itself.

```<code>public static bool TestDefaultName()
{
    (string, object) tuple = ("password", "helloworld");
    return tuple.Item2.ToString() == "helloworld";
}
</code>```

You can also name the items inside the tuple:

```<code>public static bool TestCustomName()
{
    (string myString, object myObject) tuple = ("password", "helloworld");
    return tuple.myObject.ToString() == "helloworld";
}
</code>```

Body:
I am new to c#. I have a few (string, object) that I need to compare to a string.

string, object looks like: [password, helloworld]  and my string looks like 'helloworld'

When I try to do if(A == B) I get the following error:

Operator '==' cannot be applied to operands of type '(string, object)' and 'string'

[password, helloworld] is a System.Collections.Generic.Dictionary`2[System.String,System.Object]

Body:
Just going off of the error you're getting it looks like you are using a C# Tuple type. Like the comments on your post are saying, you need to reference the item inside of the tuple, rather than compare the tuple itself.

public static bool TestDefaultName()
{
    (string, object) tuple = ("password", "helloworld");
    return tuple.Item2.ToString() == "helloworld";
}

You can also name the items inside the tuple:

public static bool TestCustomName()
{
    (string myString, object myObject) tuple = ("password", "helloworld");
    return tuple.myObject.ToString() == "helloworld";
}


问:
Sort array output python
```<code>array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

</code>```

I'm trying to write a code to sort the array

答:
Not clear what "sort the array in the format of another array" meams?  If you mean sort a subset of the aray so that the order in the subset is the same as the order in the array, you can  use something like

sorted(array2,key = lambda k:array1.index(k))

which will sort array2  so that any two elements of array2 are in the same order as in array 1.  Note "subset" is needed.  This will fail if there is an element of array2 that is not in array1

Title: Sort array output python

Body:
array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

I'm trying to write a code to sort the array


问:
How can I get a random item from multiple arrays based on a checkbox?
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox"> txt<br>
<input type="checkbox"> test<br>
<input type="checkbox"> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p></code>```

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

答:
You could use an if clause to determine whether or not the checkbox is checked. Then if it is checked, use the random number as a key to the array, which you can then append to the result.

 function myFunc() {

     let txt = ["txt1", "txt2", "txt3"];
     let test = ["test1", "test2", "test3"];
     let ran = ["ran1", "ran2", "ran3"];

     let target = document.getElementById('tst');

     let result = "";

     let txtKey = [Math.floor(Math.random() * txt.length)]
     let testKey = [Math.floor(Math.random() * test.length)]
     let ranKey = [Math.floor(Math.random() * ran.length)]

        if (document.getElementById('txt').checked) {
     result = result+txt[txtKey];
     }

        if (document.getElementById('test').checked) {
     result = result+test[testKey];
     }

        if (document.getElementById('ran').checked) {
     result = result+ran[ranKey];
     }

target.innerHTML = result;

 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="txt" type="checkbox"> <label for="txt">txt</label><br>
<input id="test" type="checkbox"> <label for="test">test</label><br>
<input id="ran" type="checkbox"> <label for="ran">ran</label>
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p></code>```

There are a few things that you could do to make this more elegant, but I think the idea works.

Body:
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}

<input type="checkbox"> txt

<input type="checkbox"> test

<input type="checkbox"> ran

<button onclick="myFunc()">One Character</button>

  sum text lol

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

Body:
You could use an if clause to determine whether or not the checkbox is checked. Then if it is checked, use the random number as a key to the array, which you can then append to the result.

 function myFunc() {

     let txt = ["txt1", "txt2", "txt3"];
     let test = ["test1", "test2", "test3"];
     let ran = ["ran1", "ran2", "ran3"];

     let target = document.getElementById('tst');

     let result = "";

     let txtKey = [Math.floor(Math.random() * txt.length)]
     let testKey = [Math.floor(Math.random() * test.length)]
     let ranKey = [Math.floor(Math.random() * ran.length)]

        if (document.getElementById('txt').checked) {
     result = result+txt[txtKey];
     }

        if (document.getElementById('test').checked) {
     result = result+test[testKey];
     }

        if (document.getElementById('ran').checked) {
     result = result+ran[ranKey];
     }

target.innerHTML = result;

 }

<input id="txt" type="checkbox"> <label for="txt">txt</label><br>
<input id="test" type="checkbox"> <label for="test">test</label><br>
<input id="ran" type="checkbox"> <label for="ran">ran</label>
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p>

There are a few things that you could do to make this more elegant, but I think the idea works.


问:
Why snsClient.unsubscribe(request) did give me a error on snsClient.unsubscribe(request)?
I'm trying to use:

```<code>  UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn("arn:aws:sns:us-east-1:9999999999:myTopic")
                .build();

  UnsubscribeResponse result = snsClient.unsubscribe(request);
</code>```

But I received an error:

software.amazon.awssdk.services.sns.model.InvalidParameterException: Invalid parameter: SubscriptionId (Service: Sns, Status Code: 400, Request ID: 08d4fa07-be89-5b3d-bd81-a07bcf09de7a, Extended Request ID: null)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:123) ~[sdk-core-2.17.46.jar:na]

Can you help me to solve this problem?

答:
To solve my problem I just get the subcription Id like this:

```<code>public String retornaSubscriptionArnSNS(String arnSns)  {

    String resultado = "";

    try {
        ListSubscriptionsRequest request = ListSubscriptionsRequest.builder()
                .build();

        ListSubscriptionsResponse result = snsClient.listSubscriptions(request);

        int intSize = result.subscriptions().size();

        if (intSize > 0) {

            for (int i = 0; i < intSize-1; i++) {

                if (result.subscriptions().get(0).topicArn().equals(arnSns)) {

                    resultado = result.subscriptions().get(i).subscriptionArn();
                    System.out.println("I found my topic: "+resultado);
                    break;
                }

            }

        } else {
            System.out.println("No one subscription found");
        }

        if (resultado == "") {
            System.out.println("Topic not found");
        }

    } catch (SnsException e) {

        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return resultado;

}
</code>```

Then you can call this method like this:

```<code>    retornaSubscriptionArnSNS("arn:aws:sns:us-east-1:9999999999:myTopic");
</code>```

If the topic exists with subscription , then will print:

I found my topic: : arn:aws:sns:us-east-1:9999999999:myTopic:3e32b1c0-d3b7-40a6-8000-99220be49445

Else:

No one subscription found

I hope that code can be useful for you!

Body:
I'm trying to use:

  UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn("arn:aws:sns:us-east-1:9999999999:myTopic")
                .build();

  UnsubscribeResponse result = snsClient.unsubscribe(request);

But I received an error:

software.amazon.awssdk.services.sns.model.InvalidParameterException: Invalid parameter: SubscriptionId (Service: Sns, Status Code: 400, Request ID: 08d4fa07-be89-5b3d-bd81-a07bcf09de7a, Extended Request ID: null)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:123) ~[sdk-core-2.17.46.jar:na]

Can you help me to solve this problem?

Body:
To solve my problem I just get the subcription Id like this:

public String retornaSubscriptionArnSNS(String arnSns)  {

    String resultado = "";

    try {
        ListSubscriptionsRequest request = ListSubscriptionsRequest.builder()
                .build();

        ListSubscriptionsResponse result = snsClient.listSubscriptions(request);

        int intSize = result.subscriptions().size();

        if (intSize > 0) {

            for (int i = 0; i < intSize-1; i++) {

                if (result.subscriptions().get(0).topicArn().equals(arnSns)) {

                    resultado = result.subscriptions().get(i).subscriptionArn();
                    System.out.println("I found my topic: "+resultado);
                    break;
                }

            }

        } else {
            System.out.println("No one subscription found");
        }

        if (resultado == "") {
            System.out.println("Topic not found");
        }

    } catch (SnsException e) {

        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    return resultado;

}

Then you can call this method like this:

    retornaSubscriptionArnSNS("arn:aws:sns:us-east-1:9999999999:myTopic");

If the topic exists with subscription , then will print:

I found my topic: : arn:aws:sns:us-east-1:9999999999:myTopic:3e32b1c0-d3b7-40a6-8000-99220be49445

Else:

No one subscription found

I hope that code can be useful for you!


问:
AWS Cognito PHP respondToAuthChallenge NEW_PASSWORD_REQUIRED User Attributes Missing
I'm trying to use respondToAuthChallenge with NEW_PASSWORD_REQUIRED to change the user's password. I keep getting "Invalid attributes given, given_name is missing" errors. I've tried adding the user's attributes to the call, but I can't seem to find any documentation on how that data should be formatted within the call.

Here is the original code...

```<code>$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
    ],
    'Session'             => $COG_USER_SESSION,
]);
</code>```

Then I tried adding the user attributes like so...

```<code>$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
        'UserAttributes'  => '{"given_name":"Bob"}',
    ],
    'Session'             => $COG_USER_SESSION,
]);
</code>```

But I'm still getting the same error. If I format the UserAttributes value as an array, I get an error saying that a string is expected.

Does anyone know how I should be passing the user attributes? I'm super lost on this one.

答:
Ah, I think I figured it out after hours of trying many different variations... this is what finally ended up working.

```<code>$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
        'userAttributes.given_name' => 'Bob',
    ],
    'Session'             => $COG_USER_SESSION,
]);
</code>```

I can't believe this isn't documented somewhere.

Body:
I'm trying to use respondToAuthChallenge with NEW_PASSWORD_REQUIRED to change the user's password. I keep getting "Invalid attributes given, given_name is missing" errors. I've tried adding the user's attributes to the call, but I can't seem to find any documentation on how that data should be formatted within the call.

Here is the original code...

$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
    ],
    'Session'             => $COG_USER_SESSION,
]);

Then I tried adding the user attributes like so...

$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
        'UserAttributes'  => '{"given_name":"Bob"}',
    ],
    'Session'             => $COG_USER_SESSION,
]);

But I'm still getting the same error. If I format the UserAttributes value as an array, I get an error saying that a string is expected.

Does anyone know how I should be passing the user attributes? I'm super lost on this one.

Body:
Ah, I think I figured it out after hours of trying many different variations... this is what finally ended up working.

$QUERY = $COG_CLIENT->respondToAuthChallenge([
    'ChallengeName'       => 'NEW_PASSWORD_REQUIRED',
    'ClientId'            => $COG_CLIENT_ID,
    'ChallengeResponses'  => [
        'USERNAME'        => $USER_EMAIL,
        'NEW_PASSWORD'    => $USER_NEW_PASS,
        'SECRET_HASH'     => $SEC_HASH,
        'userAttributes.given_name' => 'Bob',
    ],
    'Session'             => $COG_USER_SESSION,
]);

I can't believe this isn't documented somewhere.


问:
Converting TFRS to the tflite model
I am new to Tensorflow and I need to convert the TFRS to the tflite model. Does anyone have any idea or experience related to this topic?

I simply ran the retrieval code by Colab.
And added the recommended method to convert the final model to tflite. That was:

converter = tf.lite.TFLiteConverter.from_saved_model(path) # path to the SavedModel directory
tflite_model = converter.convert()

You can see the error in the following image.

enter image description here

答:
Try downloading the latest tf-nightly pip and then convert this model using new MLIR converter. You can enable the new converter by setting:</p>
```<code>converter.experimental_new_converter = True
</code>```

Title: Converting TFRS to the tflite model

Body:
Try downloading the latest tf-nightly pip and then convert this model using new MLIR converter. You can enable the new converter by setting:

converter.experimental_new_converter = True


问:
Error: No provider for t
I am trying to compile my angular code to production mode via ng build --prod and its successful but in browser I get the error :

```<code>ERROR p {__zone_symbol__error: Error: Uncaught (in promise): Error: NullInjectorError: No provider for t!
</code>```

Error: NullInjectorError:…, …}

where as when I run just ng build then the html works fine.

I have tried several links mentioned on git hub:

https://github.com/angular/angular/issues/19219
https://github.com/angular/angular-cli/issues/6851

Doesn't help much.

Attaching my Package.json file content:

{
  "name": "xxx",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build && node server.js",
    "dev": "ng build -w & nodemon server.js --watch dist --watch server",
    "production": "ng build --prod & node server.js dist server "
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~5.0.0",
    "@angular/common": "~5.0.0",
    "@angular/compiler": "~5.0.0",
    "@angular/compiler-cli": "~5.0.0",
    "@angular/core": "~5.0.0",
    "@angular/forms": "~5.0.0",
    "@angular/http": "~5.0.0",
    "@angular/platform-browser": "~5.0.0",
    "@angular/platform-browser-dynamic": "~5.0.0",
    "@angular/router": "~5.0.0",
    "@jaspero/ng2-alerts": "0.0.7",
    "axios": "^0.17.0",
    "body-parser": "^1.18.2",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "ethereumjs-tx": "^1.3.3",
    "express": "^4.16.2",
    "express-session": "^1.15.6",
    "mongoose": "^4.12.6",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "web3": "^1.0.0-beta.24",
    "web3-provider-engine": "^13.3.3",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.0",
    "@angular/compiler-cli": "1.5.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.3.0",
    "typescript": "2.4.2"
  }
}```
</div>
</div>
</p>

<p>also  app.module.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {JasperoAlertsModule} from '@jaspero/ng2-alerts';
// Imports commented out for brevity
import {RouterModule} from '@angular/router';
// Components
import {AppComponent} from './app.component';
import {LoginComponent} from './component/login/login.component';
import {DashboardComponent} from './component/dashboard/dashboard.component';
// Services
import {RecordsService} from './services/records.service';
import {AccountService} from './services/account.service';
import {AuthenticateService} from './services/authenticate.service';
import {FooterComponent} from './component/footer/footer.component';
import {HeaderComponent} from './component/header/header.component';

// Define the routes
const ROUTES = [
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    JasperoAlertsModule,
    RouterModule.forRoot(ROUTES) // Add routes to the app
  ],
  providers: [
    RecordsService,
    AccountService,
    AuthenticateService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}</code>```

答: One of my teammate faced this. He was missing HttpClientModule in imports in app.module.ts

Title: Error: No provider for t

Body:
I am trying to compile my angular code to production mode via ng build --prod and its successful but in browser I get the error :

ERROR p {__zone_symbol__error: Error: Uncaught (in promise): Error: NullInjectorError: No provider for t!

Error: NullInjectorError:…, …}

where as when I run just ng build then the html works fine.

I have tried several links mentioned on git hub:

https://github.com/angular/angular/issues/19219
https://github.com/angular/angular-cli/issues/6851

Doesn't help much.

Attaching my Package.json file content:

{
  "name": "xxx",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build && node server.js",
    "dev": "ng build -w & nodemon server.js --watch dist --watch server",
    "production": "ng build --prod & node server.js dist server "
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~5.0.0",
    "@angular/common": "~5.0.0",
    "@angular/compiler": "~5.0.0",
    "@angular/compiler-cli": "~5.0.0",
    "@angular/core": "~5.0.0",
    "@angular/forms": "~5.0.0",
    "@angular/http": "~5.0.0",
    "@angular/platform-browser": "~5.0.0",
    "@angular/platform-browser-dynamic": "~5.0.0",
    "@angular/router": "~5.0.0",
    "@jaspero/ng2-alerts": "0.0.7",
    "axios": "^0.17.0",
    "body-parser": "^1.18.2",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "ethereumjs-tx": "^1.3.3",
    "express": "^4.16.2",
    "express-session": "^1.15.6",
    "mongoose": "^4.12.6",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "web3": "^1.0.0-beta.24",
    "web3-provider-engine": "^13.3.3",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.0",
    "@angular/compiler-cli": "1.5.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.3.0",
    "typescript": "2.4.2"
  }
}

also  app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {JasperoAlertsModule} from '@jaspero/ng2-alerts';
// Imports commented out for brevity
import {RouterModule} from '@angular/router';
// Components
import {AppComponent} from './app.component';
import {LoginComponent} from './component/login/login.component';
import {DashboardComponent} from './component/dashboard/dashboard.component';
// Services
import {RecordsService} from './services/records.service';
import {AccountService} from './services/account.service';
import {AuthenticateService} from './services/authenticate.service';
import {FooterComponent} from './component/footer/footer.component';
import {HeaderComponent} from './component/header/header.component';

// Define the routes
const ROUTES = [
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    JasperoAlertsModule,
    RouterModule.forRoot(ROUTES) // Add routes to the app
  ],
  providers: [
    RecordsService,
    AccountService,
    AuthenticateService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}


问:
Saving SBCL Image From Emacs Multiple Threads Error
I have been playing with saving running Common Lisp images to save time upon restart and make the development more efficient. However, I am having a bit of a problem since when I run the following command in the Emacs/SLIME:

```<code>(sb-ext:save-lisp-and-die "rest-api-image" :purify t)
</code>```

I get the following error. Clearly, it is complaining about seeing multiple threads. As far as I can see, these are not threads I created programmatically. Instead, these are Lisp- and Emacs-created. Is there a workaround here? Can the image still be saved?

```<code>Cannot save core with multiple threads running.

Interactive thread (of current session):
  #<THREAD "main thread" RUNNING {1000550853}>

Other threads:
  #<THREAD "Swank Sentinel" #1=waiting on:
       #<WAITQUEUE  {1004AB8003}>
     {1004AB4753}>,
  #<THREAD "control-thread" #1#
       #<WAITQUEUE  {1005BC54D3}>
     {1004D87F03}>,
  #<THREAD "reader-thread" RUNNING {1004D88063}>,
  #<THREAD "swank-indentation-cache-thread" #1#
       #<WAITQUEUE  {1004D980E3}>
     {1004D88183}>,
  #<THREAD "auto-flush-thread" RUNNING {10022FFDA3}>,
  #<THREAD "repl-thread" RUNNING {1002300003}>
   [Condition of type SB-IMPL::SAVE-WITH-MULTIPLE-THREADS-ERROR]
See also:
  SBCL Manual, Saving a Core Image [:node]
</code>```

答:
If I remember correctly I had similar error and I managed to still save the image. I used the package trivial-dump-core.

It guides you to go to buffer *inferior lisp* in Emacs and running the expression (trivial-dump-core::sbcl-dump-image-slime "sbcl-slime").

Body:
I have been playing with saving running Common Lisp images to save time upon restart and make the development more efficient. However, I am having a bit of a problem since when I run the following command in the Emacs/SLIME:

(sb-ext:save-lisp-and-die "rest-api-image" :purify t)

I get the following error. Clearly, it is complaining about seeing multiple threads. As far as I can see, these are not threads I created programmatically. Instead, these are Lisp- and Emacs-created. Is there a workaround here? Can the image still be saved?

Cannot save core with multiple threads running.

Interactive thread (of current session):
  #<THREAD "main thread" RUNNING {1000550853}>

Other threads:
  #<THREAD "Swank Sentinel" #1=waiting on:
       #<WAITQUEUE  {1004AB8003}>
     {1004AB4753}>,
  #<THREAD "control-thread" #1#
       #<WAITQUEUE  {1005BC54D3}>
     {1004D87F03}>,
  #<THREAD "reader-thread" RUNNING {1004D88063}>,
  #<THREAD "swank-indentation-cache-thread" #1#
       #<WAITQUEUE  {1004D980E3}>
     {1004D88183}>,
  #<THREAD "auto-flush-thread" RUNNING {10022FFDA3}>,
  #<THREAD "repl-thread" RUNNING {1002300003}>
   [Condition of type SB-IMPL::SAVE-WITH-MULTIPLE-THREADS-ERROR]
See also:
  SBCL Manual, Saving a Core Image [:node]


问:
UnexpectedTagNameException: Element should have been "select" but was "a" while trying to get the texts of dropdown menu using Selenium and Java
While trying to get the menu list, I'm getting this error message:

```<code>Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a".
</code>```

Here below is the code:

```<code>public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "D:\\selenium files\\chromedriver_win32_new\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.tutorialspoint.com/tutor_connect/index.php");

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement ele = driver.findElement(By.xpath("//*[@id=\"logo-menu\"]/div/div[1]/div/a"));

        Select s = new Select(ele);

    //getting list of menu
         List <WebElement> op = s.getOptions();
          int size = op.size();
          for(int i =0; i<size ; i++){
             String options = op.get(i).getText();
             System.out.println(options);
          }
    }
}
</code>```

答:
The desired element is not a <select> element but a
 element. Once you click on the  element then only the classname mui--is-open is appended to the desired
 element.

Solution

So to get the contents of the dropdown menu you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use Java8 stream() and map() and you can use either of the following Locator Strategies:

Using cssSelector:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.mui-btn.mui-btn--primary.categories"))).click();
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("ul.mui-dropdown__menu.cat-menu.mui--is-open a"))).stream().map(element->element.getText()).collect(Collectors.toList()));
</code>```

Using xpath:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='mui-btn mui-btn--primary categories']"))).click();
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='mui-dropdown__menu cat-menu mui--is-open']//a"))).stream().map(element->element.getText()).collect(Collectors.toList()));
</code>```

References

You can find a couple of relevant detailed discussions in:

How to extract the text iterating specific rows within a table using XPath with Selenium and Java

How to extract the dynamic values of the id attributes of the table elements using Selenium and Java

How to print runs scored by a batsmen in a scoreboard format webelements through CSS selector using Selenium and Java

Body:
While trying to get the menu list, I'm getting this error message:

Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a".

Here below is the code:

public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "D:\\selenium files\\chromedriver_win32_new\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.tutorialspoint.com/tutor_connect/index.php");

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement ele = driver.findElement(By.xpath("//*[@id=\"logo-menu\"]/div/div[1]/div/a"));

        Select s = new Select(ele);

    //getting list of menu
         List <WebElement> op = s.getOptions();
          int size = op.size();
          for(int i =0; i<size ; i++){
             String options = op.get(i).getText();
             System.out.println(options);
          }
    }
}

Body:
The desired element is not a <select> element but a <ul> element. Once you click on the <a> element then only the classname mui--is-open is appended to the desired <ul> element.

Solution

So to get the contents of the dropdown menu you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use Java8 stream() and map() and you can use either of the following Locator Strategies:

Using cssSelector:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.mui-btn.mui-btn--primary.categories"))).click();
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("ul.mui-dropdown__menu.cat-menu.mui--is-open a"))).stream().map(element->element.getText()).collect(Collectors.toList()));

Using xpath:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='mui-btn mui-btn--primary categories']"))).click();
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='mui-dropdown__menu cat-menu mui--is-open']//a"))).stream().map(element->element.getText()).collect(Collectors.toList()));

References

You can find a couple of relevant detailed discussions in:

How to extract the text iterating specific rows within a table using XPath with Selenium and Java

How to extract the dynamic values of the id attributes of the table elements using Selenium and Java

How to print runs scored by a batsmen in a scoreboard format webelements through CSS selector using Selenium and Java


问:
Change order and labels of local tasks in Drupal 9
I've got local tasks displayed as tabs on my users' profile page.
Those local tasks are added by various modules.
I need to change the order of those tabs, and change some of their labels.

I can't figure out how to do that.

I tried using the menu_tokens module to replace those tabs by a real, customizable menu, but unfortunately it's not working correctly in Drupal 9 yet and breaks the whole website. Maybe there's another way which I'm not aware of?

答:
Use hook_local_tasks_alter hook inside your custom module. I've checked and it's still valid in d9.

Inside your module_name.module file place a function named according to the convention function module_name_local_tasks_alter(&$local_tasks) {

Place there a breakpoint or simply var dump the local tasks, you will see, how many local tasks tab goes through this function.

In the end you will find entity.user.canonical, just overwrite the item weight in similar manner:

```<code>$local_tasks['entity.user.canonical']['weight'] = -3;
$local_tasks['entity.user.edit_form']['weight'] = -2;
</code>```

Source: https://codimth.com/blog/web/drupal/how-override-local-task-drupal-8

Body:
Use hook_local_tasks_alter hook inside your custom module. I've checked and it's still valid in d9.

Inside your module_name.module file place a function named according to the convention function module_name_local_tasks_alter(&$local_tasks) {

Place there a breakpoint or simply var dump the local tasks, you will see, how many local tasks tab goes through this function.

In the end you will find entity.user.canonical, just overwrite the item weight in similar manner:

$local_tasks['entity.user.canonical']['weight'] = -3;
$local_tasks['entity.user.edit_form']['weight'] = -2;

Source: https://codimth.com/blog/web/drupal/how-override-local-task-drupal-8


问:
Show result of failed JUnit tests in the console
In a JUnit (4.x) test case I want to get some log information in case one of the assertion fails. Assume this is the test class:

```<code>package a.b.c.d;

import org.junit.Assert;
import org.junit.Test;

public class SomeTestClass {

    @Test
    public void someSimpleTest() {
        Assert.assertEquals("123", "456");
    }
}
</code>```

Obviously, Assert.assertEquals("123", "456"); will fail. When I run this test from within Eclipse I only get the Failure Trace with an exception. I would like to have some info printed onto the console about what actually failed, e.g.:

```<code>Expected Value: "123"; Actual Value "456";
</code>```

Searching the internet I stumbled upon this example here that provides the information that I need. However, I'm not able to get this log output in the console.

```<code>org.junit.ComparisonFailure: expected:<gradle is gr[8]> but was:<gradle is gr[eat]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.mrhaki.gradle.SampleTest.sample(SampleTest.java:8)
</code>```

What I tried so far is something like below, which didn't help.

```<code>-Djava.util.logging.ConsoleHandler.level=FINEST

static {
    Logger.getGlobal().setLevel(Level.FINEST);
}
</code>```

答:
According to the JUnit 4 documentation, there are other versions of assertEquals that take a message to be printed if the assertion fails:

```<code>public static void assertEquals(String message,
                                Object expected,
                                Object actual)

Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null, they are considered equal.
Parameters:
message - the identifying message for the AssertionError (null okay)
expected - expected value
actual - actual value
</code>```

Unfortunately I don't see a way to add the expected and actual values into that message, since it's just a predetermined string.

Body:
In a JUnit (4.x) test case I want to get some log information in case one of the assertion fails. Assume this is the test class:

package a.b.c.d;

import org.junit.Assert;
import org.junit.Test;

public class SomeTestClass {

    @Test
    public void someSimpleTest() {
        Assert.assertEquals("123", "456");
    }
}

Obviously, Assert.assertEquals("123", "456"); will fail. When I run this test from within Eclipse I only get the Failure Trace with an exception. I would like to have some info printed onto the console about what actually failed, e.g.:

Expected Value: "123"; Actual Value "456";

Searching the internet I stumbled upon this example here that provides the information that I need. However, I'm not able to get this log output in the console.

org.junit.ComparisonFailure: expected:<gradle is gr[8]> but was:<gradle is gr[eat]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.mrhaki.gradle.SampleTest.sample(SampleTest.java:8)

What I tried so far is something like below, which didn't help.

-Djava.util.logging.ConsoleHandler.level=FINEST

static {
    Logger.getGlobal().setLevel(Level.FINEST);
}

Body:
According to the JUnit 4 documentation, there are other versions of assertEquals that take a message to be printed if the assertion fails:

public static void assertEquals(String message,
                                Object expected,
                                Object actual)

Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null, they are considered equal.
Parameters:
message - the identifying message for the AssertionError (null okay)
expected - expected value
actual - actual value

Unfortunately I don't see a way to add the expected and actual values into that message, since it's just a predetermined string.


问:
Convert NCHW to NHWC in C++
OpenCV reads an image in NCHW format (Number of samples x Channels x Height x Width), I need to convert it to NHWC format (move 2nd dimension of array to last). Is there an efficient way to convert from NCHW to NHWC in C++? I can do this with a 3 for loops, but obviously this is not efficient at all.</p>

答:
This straightforward solution worked for me with OpenCV C++:</p>
```<code>static void hwc_to_chw(cv::InputArray src, cv::OutputArray dst) {
  std::vector<cv::Mat> channels;
  cv::split(src, channels);

  // Stretch one-channel images to vector
  for (auto &img : channels) {
    img = img.reshape(1, 1);
  }

  // Concatenate three vectors to one
  cv::hconcat( channels, dst );
}
</code>```

Title: Convert NCHW to NHWC in C++

Body:
This straightforward solution worked for me with OpenCV C++:

static void hwc_to_chw(cv::InputArray src, cv::OutputArray dst) {
  std::vector<cv::Mat> channels;
  cv::split(src, channels);

  // Stretch one-channel images to vector
  for (auto &img : channels) {
    img = img.reshape(1, 1);
  }

  // Concatenate three vectors to one
  cv::hconcat( channels, dst );
}


问:
Get separate elements with @Cacheable List
I'm using spring cache integration with hazelcast.

I need to get/set(1st call) all the movies list from/to a hazelcast cache map.
I also need to be able to get a specific movie from the cache map.

My problem is that by using List with @Cacheable, it returns a single key (SimpleKey[]) which holds all the movies objects, instead of adding the key/values individually, so I can then use @Cacheable with a key to get a specific map object.

```<code>@Cacheable(value = MOVIES_CACHE_NAME, unless = "#result==null or #result.isEmpty()")
public List<Movie> getAllMoviesFromCache() {
    log.debug("Going to call getAllMoviesFromCache");

    List<Movie> movies = null;
    MovieListDetailResponse response = getAllMovies(); //gets from db

    if (response != null && response.getMovies() != null) {
        movies = convertMovieListResponseToMovie(response.getMovies());
    }

    log.debug(String.format("Finished getAllMoviesFromCache, got Response %s", response));

    return movies;
}
</code>```

```<code>@Cacheable(value = MOVIES_CACHE_NAME, key = "{#movieId}", unless = "#result==null")
public Movie getMovieDetailsFromCache(String movieId) {
    Movie movie = null;
    MovieDetailResponse response = getMovie(movieId); //gets from db

    if (response != null && response.getMovie() != null) {
        movie = convertMovieDetailResponseToMovie(response.getMovie());
    }

    log.info(String.format("Movie by MovieId: '%s'. Response: %s", movieId, movie));
    return movie;
}
</code>```

答:
See my answer to this similar SO question and specifically have a look at this answer (#2 from my previous answer).

My answers also share example code on how to implement such logic with Spring's Cache Abstraction, see here.

Body:
I'm using spring cache integration with hazelcast.

I need to get/set(1st call) all the movies list from/to a hazelcast cache map.
I also need to be able to get a specific movie from the cache map.

My problem is that by using List with @Cacheable, it returns a single key (SimpleKey[]) which holds all the movies objects, instead of adding the key/values individually, so I can then use @Cacheable with a key to get a specific map object.

@Cacheable(value = MOVIES_CACHE_NAME, unless = "#result==null or #result.isEmpty()")
public List<Movie> getAllMoviesFromCache() {
    log.debug("Going to call getAllMoviesFromCache");

    List<Movie> movies = null;
    MovieListDetailResponse response = getAllMovies(); //gets from db

    if (response != null && response.getMovies() != null) {
        movies = convertMovieListResponseToMovie(response.getMovies());
    }

    log.debug(String.format("Finished getAllMoviesFromCache, got Response %s", response));

    return movies;
}

@Cacheable(value = MOVIES_CACHE_NAME, key = "{#movieId}", unless = "#result==null")
public Movie getMovieDetailsFromCache(String movieId) {
    Movie movie = null;
    MovieDetailResponse response = getMovie(movieId); //gets from db

    if (response != null && response.getMovie() != null) {
        movie = convertMovieDetailResponseToMovie(response.getMovie());
    }

    log.info(String.format("Movie by MovieId: '%s'. Response: %s", movieId, movie));
    return movie;
}


问:
How do I force make to clean and recompile after changes to Makefile itself?
I sometimes change the Makefile but that change itself does not cause make to recompile my sources.

I tried something like this (EXEC is my executable, clean is the usual deletion of source and intermediate compilation output)

```<code>$(EXEC): Makefile
         make clean
         make
</code>```

but this generates an infinite loop... any idea?

答:
What you have can't work because after make clean the $(EXEC) file won't exist, so it's always out of date, so it's always rebuilt, and the rebuild will run clean then re-exec itself, so again it will be out of date, so again make will run clean then re-exec itself, etc.

To do what you want you need to list the makefile as a prerequisite of all of the targets.  Then you don't need to run clean or re-run make, because all the targets will be out of date when the makefile changes, just as they'd be out of date if the source file changed.  So, as an example, add Makefile as a prerequisite to your object file targets:

```<code>%.o : %.c Makefile
        $(CC) $(CFLAGS) -c -o $@ $<
</code>```

Without knowing anything about the rest of your makefile we can't give more specific advice than that.

Body:
I sometimes change the Makefile but that change itself does not cause make to recompile my sources.

I tried something like this (EXEC is my executable, clean is the usual deletion of source and intermediate compilation output)

$(EXEC): Makefile
         make clean
         make

but this generates an infinite loop... any idea?

Body:
What you have can't work because after make clean the $(EXEC) file won't exist, so it's always out of date, so it's always rebuilt, and the rebuild will run clean then re-exec itself, so again it will be out of date, so again make will run clean then re-exec itself, etc.

To do what you want you need to list the makefile as a prerequisite of all of the targets.  Then you don't need to run clean or re-run make, because all the targets will be out of date when the makefile changes, just as they'd be out of date if the source file changed.  So, as an example, add Makefile as a prerequisite to your object file targets:

%.o : %.c Makefile
        $(CC) $(CFLAGS) -c -o $@ $<

Without knowing anything about the rest of your makefile we can't give more specific advice than that.


问:
SQL query to get multiple records into multiple columns
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

```<code>Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use
</code>```

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

```<code>LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use
</code>```

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

答:
This is very simple solution considering you have just 3 different types of statuses so the code is not so much replicated.

insert into new_locations (
    select distinct location,
        case when location in (select distinct location from old_locations where status = 'ready') then 'ready' else '' end,
        case when location in (select distinct location from old_locations where status = 'active') then 'active' else '' end,
        case when location in (select distinct location from old_locations where status = 'dead') then 'dead' else '' end
    from old_locations
);
```

SQL is quite handy and this is just the case where you can kind of cheat with using bit of code replication, it is very simple to understand and does its job. There usually is some pure SQL solution for this kind of problems without need of using T-SQL or other sql 'upgrades'.

Body:
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

Body:
This is very simple solution considering you have just 3 different types of statuses so the code is not so much replicated.

insert into new_locations (
    select distinct location,
        case when location in (select distinct location from old_locations where status = 'ready') then 'ready' else '' end,
        case when location in (select distinct location from old_locations where status = 'active') then 'active' else '' end,
        case when location in (select distinct location from old_locations where status = 'dead') then 'dead' else '' end
    from old_locations
);

SQL is quite handy and this is just the case where you can kind of cheat with using bit of code replication, it is very simple to understand and does its job. There usually is some pure SQL solution for this kind of problems without need of using T-SQL or other sql 'upgrades'.


问:
Persist authentication Laravel on iOS Devices
I'm currently building an app that basically wraps my Laravel webapp inside the react native web-view.
The problem I'm currently facing is the iOS doesn't seem to persist authentication at all.
Android seem to work fine even after I close the app and open it again but I've to log into the web-view every-time I open an app.
What would be the solution here?

I do have a solution which is basically storing the some auth information after user logs in and store that in the AsyncStorage of React Native but I just am not able to find what exactly to push to asyncStorage. The app_session and csrf_token obviously doesn't help to authenticate user otherwise i could have just passed those when user opens app on iOS but it doesn't help in authenticating user in anyway.

Basically, I want to pull some value when user login in and send that to asyncStorage and when user reopens app in iOS, I want to pass that as cookie and make Laravel feel like it is an authenticated user.
But I just don't seem to find what exactly should I pass to server via AsyncStorage.

Any help?

P.S. I'm not looking for any API authentication, just want a solution from existing web app.

Thanks!

答: I had to solve it by passing encrypted id and password stored in AsyncStorage and create middleware on backend if any valid auth has been passed.</p>


问:
How cv::MAT convert to NHCW format?
In User Guide.html, Input/output of tensorRT is need to use NCHW format.

What's NCHW fomat ?

How can I convert cv::MAT to NCHW format?

I run inference using TensorRT like below code.

Nothing error. But, It's not right result of output.

```<code>int batchSize = 1;
int size_of_single_input = 256 * 256 * 3 * sizeof(float);
int size_of_single_output = 100 * 1 * 1 * sizeof(float);

IBuilder* builder = createInferBuilder(gLogger);

INetworkDefinition* network = builder->createNetwork();

CaffeParser parser;
auto blob_name_to_tensor = parser.parse(“deploy.prototxt”,
                                        "sample.caffemodel",
                                        *network,
                                        DataType::kFLOAT);

network->markOutput(*blob_name_to_tensor->find("prob"));

builder->setMaxBatchSize(1);
builder->setMaxWorkspaceSize(1 << 30);
ICudaEngine* engine = builder->buildCudaEngine(*network);

IExecutionContext *context = engine->createExecutionContext();

int inputIndex = engine->getBindingIndex(INPUT_LAYER_NAME),
int outputIndex = engine->getBindingIndex(OUTPUT_LAYER_NAME);

cv::Mat input;
input = imread("./sample.jpg");
cvtColor(input, input, CV_BGR2RGB);
cv::resize(input, input, cv::Size(256, 256));

float output[OUTPUTSIZE];

void* buffers = malloc(engine->getNbBindings() * sizeof(void*));
cudaMalloc(&buffers[inputIndex], batchSize * size_of_single_input);
cudaMalloc(&buffers[outputIndex], batchSize * size_of_single_output);

cudaStream_t stream;
cudaStreamCreate(&stream);

cudaMemcpyAsync(buffers[inputIndex], (float *)input,
                batchSize * size_of_single_input,
                cudaMemcpyHostToDevice, stream);

context.enqueue(batchSize, buffers, stream, nullptr);

cudaMemcpyAsync(output, buffers[outputIndex],
                batchSize * size_of_single_output,
                cudaMemcpyDeviceToHost, stream));

cudaStreamSynchronize(stream);
</code>```

答:
Here's a short a straightforward solution for NHWC to NCHW on the CPU:</p>
```<code>static void hwc_to_chw(cv::InputArray src, cv::OutputArray dst) {
  std::vector<cv::Mat> channels;
  cv::split(src, channels);

  // Stretch one-channel images to vector
  for (auto &img : channels) {
    img = img.reshape(1, 1);
  }

  // Concatenate three vectors to one
  cv::hconcat( channels, dst );
}
</code>```

Title: How cv::MAT convert to NHCW format?

Body:
In User Guide.html, Input/output of tensorRT is need to use NCHW format.

What's NCHW fomat ?

How can I convert cv::MAT to NCHW format?

I run inference using TensorRT like below code.

Nothing error. But, It's not right result of output.

int batchSize = 1;
int size_of_single_input = 256 * 256 * 3 * sizeof(float);
int size_of_single_output = 100 * 1 * 1 * sizeof(float);

IBuilder* builder = createInferBuilder(gLogger);

INetworkDefinition* network = builder->createNetwork();

CaffeParser parser;
auto blob_name_to_tensor = parser.parse(“deploy.prototxt”,
                                        "sample.caffemodel",
                                        *network,
                                        DataType::kFLOAT);

network->markOutput(*blob_name_to_tensor->find("prob"));

builder->setMaxBatchSize(1);
builder->setMaxWorkspaceSize(1 << 30);
ICudaEngine* engine = builder->buildCudaEngine(*network);

IExecutionContext *context = engine->createExecutionContext();

int inputIndex = engine->getBindingIndex(INPUT_LAYER_NAME),
int outputIndex = engine->getBindingIndex(OUTPUT_LAYER_NAME);

cv::Mat input;
input = imread("./sample.jpg");
cvtColor(input, input, CV_BGR2RGB);
cv::resize(input, input, cv::Size(256, 256));

float output[OUTPUTSIZE];

void* buffers = malloc(engine->getNbBindings() * sizeof(void*));
cudaMalloc(&buffers[inputIndex], batchSize * size_of_single_input);
cudaMalloc(&buffers[outputIndex], batchSize * size_of_single_output);

cudaStream_t stream;
cudaStreamCreate(&stream);

cudaMemcpyAsync(buffers[inputIndex], (float *)input,
                batchSize * size_of_single_input,
                cudaMemcpyHostToDevice, stream);

context.enqueue(batchSize, buffers, stream, nullptr);

cudaMemcpyAsync(output, buffers[outputIndex],
                batchSize * size_of_single_output,
                cudaMemcpyDeviceToHost, stream));

cudaStreamSynchronize(stream);

Body:
Here's a short a straightforward solution for NHWC to NCHW on the CPU:

static void hwc_to_chw(cv::InputArray src, cv::OutputArray dst) {
  std::vector<cv::Mat> channels;
  cv::split(src, channels);

  // Stretch one-channel images to vector
  for (auto &img : channels) {
    img = img.reshape(1, 1);
  }

  // Concatenate three vectors to one
  cv::hconcat( channels, dst );
}


问:
Python 3 sorting "TypeError: 'NoneType' object is not iterable"
When sorting in Python 3, I get:

```<code>TypeError: 'NoneType' object is not iterable
</code>```

Here is my code:

for f in self.db[key].sort():
  yield f
```

I have confirmed none of the items in my list are None.

答:
The reason for this is simple, Python3 provides two methods and you're using the wrong one,

sorted(foo) returns a copy sorted, uses core sorted().

.sort() sorts the stuff in place, returns None

You need to call sorted(foo) instead. For more information see the docs on Sorting HOW TO

Body:
When sorting in Python 3, I get:

TypeError: 'NoneType' object is not iterable

Here is my code:

for f in self.db[key].sort():
  yield f

I have confirmed none of the items in my list are None.


问:
webpack file-loader does not load background image
I've been having this problem for a while and I see that other people have it too, but even though I have the same code as them it is still not working and I don't know what I'm doing wrong.
I'm working with react, webpack, babel and scss for a project. At first I create a main component which has a background image tha loaded without problems, but when I added a carousel component I had an error that said that I needed a loader for the images to appear (html images, not bakground). So I looked it up  on the internet and  two loaders appeared: url-loader and file-loader, I installed both and added one in my webpack config file as it was said in the documentation. The images loaded, but the background image of the main component didn't, and not only that, all the styles for the background didn't apply either.

This is my webpack config file, I tried putting both loaders, then only one, then the other, but none of them worked. I tried every solution tha came across stackoverflow but the code isn't working and there is no errors in my terminal.

///////EDIT

I added absolute paht but it's still not working. The image gets fetched because I'd get an error if it isn't so I don't think this is a path issue.
I updated the webpack config file

```<code>const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const htmlPlugin = new HtmlWebPackPlugin({
 template: "./src/index.html",
 filename: "./index.html"
});

module.exports = {
mode: "development",
resolve: {
  alias: {
    Assets: path.resolve(__dirname, 'src/assets/')
  }
},
  module: {
    rules: [{
   test: /\.js$/,
   exclude: /node_modules/,
   use: {
     loader: "babel-loader"
   }
 },
  {
   test: /\.s?css$/,
   use: ["style-loader", "css-loader", "sass-loader"]
  },
  {
    test: /\.(png|jpg|gif)$/i,
    use: [
      {
        loader: 'url-loader',
        options: {
          limit: 10000,
          esModule: false
        },
      },
    ]
  }
]},
 plugins: [htmlPlugin],
 devServer:{
   historyApiFallback : true
 }
}
</code>```

And this is my main component and its scss file (where the bakground image lies)

React component

```<code>import React from "react";
import { NavBar } from "../components/NavBar";
import CarouselComponent from "../components/Carousel";

export const MainPage = () => {
    return (
        <div>
        <NavBar />
        <div>
            <div className="main">
                <h1>Find a new musical to watch!</h1>
                <a className="main__btn" href="/musicals">See categories</a>
            </div>
            <div className="login-info">
                <h2 className= "login-info__login">See our forum for reacomendations and post your own!</h2>
                <div className="login-info__btn-login-position">
                    <a className="btn login-btn-position-config" href="#"><strong>Loging</strong></a>
                </div>
                <span></span>
                <h2 className= "login-info__create-account">Don't have an account? Create one!</h2>
                <div className="login-info__btn-create-position">
                <   a className="btn login-btn-position-config" href="#"><strong>Create account</strong></a>
                </div>
           </div>
            <CarouselComponent />
        </div>
        </div>
    )
}
</code>```

Scss component

```<code>body{
    padding: 56px 50px 0 50px;
    background-color: $color-background;
}

.main{
    font-family: $primary-title-font;
    height: 90%;
    background: url(Assets/main_background.jpg) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    h1{
        background-image: linear-gradient(90deg, rgba(1,50,1,1) 5%, rgba(70,82,25,1) 51%, rgba(78,82,29,1) 87%);
        background-size: 100%;
        background-clip: text;
        -webkit-background-clip: text;
        -moz-background-clip: text;
        -webkit-text-fill-color: transparent;
        -moz-text-fill-color: transparent;
        position: absolute;
        top: 15rem;
        left: 5rem;
        font-size: 5rem;

    }

    &__btn{
        position: absolute;
        top: 350px;
        left: 459px;
        border-radius: 10% / 20%;
        padding: 1rem;
        text-decoration: none;
        color: $primary-black-color;
        background: $golden-button;
        font-size: 1.5rem;

        &:hover{
            color: $primary-black-color;
        }

        &:active{
            transform: translateY(2px);
        }
    }
}

</code>```

And this is the carousel component with its scss

React component

```<code>import React, { Component } from "react";
import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from 'react-responsive-carousel';
import hamilton from "../assets/hamilton.jpg";
import six from "../assets/six_the_musical.jpg";
import hadestown from "../assets/hadestown.jpg";
import theGuy from "../assets/the_guy_who_didnt_like_musicals.png";

class CarouselComponent extends Component {
    render (){
        return (
            <Carousel autoPlay = {true} infiniteLoop={true} interval={4000} showStatus={false} useKeyboardArrows={true} showThumbs={false}>
                <div className="carousel__box-1">
                    <img src={hamilton} alt="Hamilton wallpaper"/>
                </div>
                <div className="carousel__box-2">
                    <img src={six} alt="Six wallpaper"/>
                </div>
                <div className="carousel__box-3">
                    <img src={hadestown} alt="Hadestown wallpaper"/>
                </div>
                <div className="carousel__box-4">
                    <img src={theGuy} alt="The guy who didnt like musicals wallpaper"/>
                </div>
            </Carousel>
        )
    }
}

export default CarouselComponent;
</code>```

Scss component

```<code>.carousel__box{
    height: 9rem;

    img{
        min-width: 100%;
        min-height: 100%;
    }
}

</code>```

I'll also add my folder structure in case it's necessary

```<code>/project
  /dist
  /node_modules
  /src
    /assets
       (all the images are stored here)
    /components
       card.js
       cardBlock.js
       carousel.js
       navbar.js
    /pages
       main.js
       musicals.js
       notFound.js
    /sass
       (all scss are stored here, there is a styles.scss that imports the rest of files and it's
       called in index.js)
    index.html
    index.js (imports all react component an renders them in index.html)
    .babelrc
    packaje.json
    packaje-lock.json
    webpack.config.js

</code>```

////// NEW EDIT

I found that if you put esModule: false inside the url-loader options the image gets loaded.

答:
if you have webpack 5 then don't install (file-loader, url-loader, raw-loader) they come with 5. Everything will work, just include the image in the css file as you would without webpack.

https://webpack.js.org/guides/asset-modules/

Body:
I've been having this problem for a while and I see that other people have it too, but even though I have the same code as them it is still not working and I don't know what I'm doing wrong.
I'm working with react, webpack, babel and scss for a project. At first I create a main component which has a background image tha loaded without problems, but when I added a carousel component I had an error that said that I needed a loader for the images to appear (html images, not bakground). So I looked it up  on the internet and  two loaders appeared: url-loader and file-loader, I installed both and added one in my webpack config file as it was said in the documentation. The images loaded, but the background image of the main component didn't, and not only that, all the styles for the background didn't apply either.

This is my webpack config file, I tried putting both loaders, then only one, then the other, but none of them worked. I tried every solution tha came across stackoverflow but the code isn't working and there is no errors in my terminal.

///////EDIT

I added absolute paht but it's still not working. The image gets fetched because I'd get an error if it isn't so I don't think this is a path issue.
I updated the webpack config file

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const htmlPlugin = new HtmlWebPackPlugin({
 template: "./src/index.html",
 filename: "./index.html"
});

module.exports = {
mode: "development",
resolve: {
  alias: {
    Assets: path.resolve(__dirname, 'src/assets/')
  }
},
  module: {
    rules: [{
   test: /\.js$/,
   exclude: /node_modules/,
   use: {
     loader: "babel-loader"
   }
 },
  {
   test: /\.s?css$/,
   use: ["style-loader", "css-loader", "sass-loader"]
  },
  {
    test: /\.(png|jpg|gif)$/i,
    use: [
      {
        loader: 'url-loader',
        options: {
          limit: 10000,
          esModule: false
        },
      },
    ]
  }
]},
 plugins: [htmlPlugin],
 devServer:{
   historyApiFallback : true
 }
}

And this is my main component and its scss file (where the bakground image lies)

React component

import React from "react";
import { NavBar } from "../components/NavBar";
import CarouselComponent from "../components/Carousel";

export const MainPage = () => {
    return (

        <NavBar />

Find a new musical to watch!

                See categories

See our forum for reacomendations and post your own!

                    Loging

Don't have an account? Create one!

                Create account

            <CarouselComponent />

    )
}

Scss component

body{
    padding: 56px 50px 0 50px;
    background-color: $color-background;
}

.main{
    font-family: $primary-title-font;
    height: 90%;
    background: url(Assets/main_background.jpg) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    h1{
        background-image: linear-gradient(90deg, rgba(1,50,1,1) 5%, rgba(70,82,25,1) 51%, rgba(78,82,29,1) 87%);
        background-size: 100%;
        background-clip: text;
        -webkit-background-clip: text;
        -moz-background-clip: text;
        -webkit-text-fill-color: transparent;
        -moz-text-fill-color: transparent;
        position: absolute;
        top: 15rem;
        left: 5rem;
        font-size: 5rem;

    }

    &__btn{
        position: absolute;
        top: 350px;
        left: 459px;
        border-radius: 10% / 20%;
        padding: 1rem;
        text-decoration: none;
        color: $primary-black-color;
        background: $golden-button;
        font-size: 1.5rem;

        &:hover{
            color: $primary-black-color;
        }

        &:active{
            transform: translateY(2px);
        }
    }
}

And this is the carousel component with its scss

React component

import React, { Component } from "react";
import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from 'react-responsive-carousel';
import hamilton from "../assets/hamilton.jpg";
import six from "../assets/six_the_musical.jpg";
import hadestown from "../assets/hadestown.jpg";
import theGuy from "../assets/the_guy_who_didnt_like_musicals.png";

class CarouselComponent extends Component {
    render (){
        return (
            <Carousel autoPlay = {true} infiniteLoop={true} interval={4000} showStatus={false} useKeyboardArrows={true} showThumbs={false}>

            </Carousel>
        )
    }
}

export default CarouselComponent;

Scss component

.carousel__box{
    height: 9rem;

    img{
        min-width: 100%;
        min-height: 100%;
    }
}

I'll also add my folder structure in case it's necessary

/project
  /dist
  /node_modules
  /src
    /assets
       (all the images are stored here)
    /components
       card.js
       cardBlock.js
       carousel.js
       navbar.js
    /pages
       main.js
       musicals.js
       notFound.js
    /sass
       (all scss are stored here, there is a styles.scss that imports the rest of files and it's
       called in index.js)
    index.html
    index.js (imports all react component an renders them in index.html)
    .babelrc
    packaje.json
    packaje-lock.json
    webpack.config.js

////// NEW EDIT

I found that if you put esModule: false inside the url-loader options the image gets loaded.