问:
Modify CSV file to add a digit character to a column
I have a problem making a batch file.
This text is inside a file with name export.dat and I have no means to change the CSV field item from 5 to 6 digits.
This is a preferred older program.
As for newer program I can add the required.

```<code>D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
</code>```

Has to be after modification:

```<code>D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,078330,300.00,078330 - A03.1 - Shigellosis d,,etc
</code>```

So we have a leading capital D followed by 13 commas and batch should ad a zero before the comma 13.

答:
```<code>@echo off
setlocal

set "target=.\export.dat"
set "destination=.\updated.dat"

powershell -noprofile -command^
 "$content = get-content -literalpath '%target%';"^
 "$modifiedContent = @();"^
 "$modifiedContent += $content[0];"^
 "ForEach ($line in $content[1 .. ($content.count - 1)]) {"^
 " if ($line.startswith('D,')) {"^
 "  $items = $line.split(',');"^
 "  if ($items.length -gt 14) {$items[14] += '0'; $line = $items -join ','};"^
 " };"^
 " $modifiedContent += $line"^
 "};"^
 "$modifiedContent | set-content -literalpath '%destination%'"
</code>```

Powershell has Import-CSV and Export-CSV which can handle CSV files, though Export-CSV outputs data with double quoted field items. Powershell 7 introduces arguments for quotes for Export-CSV, though is still new at this time. With Powershell less than 7, the suggestions are to read the file with Get-Content, remove double quotes and use Set-Content. Since the example content lacks double quotes, I decided to use Get-Content, split on commas and write with Set-Content.

The following code is a hybrid batch-file with powershell which I used as a basis to construct the previous code.
It has some comments that explains the code which is not suitable for inserting into a single powershell command.

```<code><# :: Begin bat code

@echo off
setlocal

set "target=.\export.dat"
set "destination=.\updated.dat"

powershell -noprofile "invoke-expression(get-content '%~f0' | out-string)"

exit /b 0

#> ## Begin ps1 code

# Filepaths from environment variables.
$target = $env:target
$destination = $env:destination

# Read file content into a variable.
$content = get-content -literalpath $target

# Create an empty array for modified content.
$modifiedContent = @()

# Add 1st line as unmodified header.
$modifiedContent += $content[0]

# Add the rest of the lines.
foreach ($line in $content[1 .. ($content.length - 1)]) {

    # Require a leading capital D to modify a line.
    if ($line.startswith('D,')) {

        # Split by commas.
        $items = $line.split(',')

        # Modify item 14.
        if ($items.length -gt 14) {
            $items[14] += '0'
            $line = $items -join ','
        }
    }

    # Add line to array.
    $modifiedContent += $line
}

# Write modified content to destination file.
$modifiedContent | set-content -literalpath $destination
</code>```

If suitable, the powershell code portion could be copied to a .ps1 file and just replace $target = $env:target and $destination = $env:destination with  $target = '.\export.dat' and $destination = '.\updated.dat'.

Input export.dat:

```<code>0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00
d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
</code>```

Output updated.dat:

```<code>0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,078330,300.00,078330
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00
d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
</code>```

1st line is the header unmodified.

2nd line is modified.

3rd line is too short in length to modify.

4th line does not start with D, as d, does not match same case so is not modified.

Body:
I have a problem making a batch file.
This text is inside a file with name export.dat and I have no means to change the CSV field item from 5 to 6 digits.
This is a preferred older program.
As for newer program I can add the required.

D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330

Has to be after modification:

D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,078330,300.00,078330 - A03.1 - Shigellosis d,,etc

So we have a leading capital D followed by 13 commas and batch should ad a zero before the comma 13.

Body:
@echo off
setlocal

set "target=.\export.dat"
set "destination=.\updated.dat"

powershell -noprofile -command^
 "$content = get-content -literalpath '%target%';"^
 "$modifiedContent = @();"^
 "$modifiedContent += $content[0];"^
 "ForEach ($line in $content[1 .. ($content.count - 1)]) {"^
 " if ($line.startswith('D,')) {"^
 "  $items = $line.split(',');"^
 "  if ($items.length -gt 14) {$items[14] += '0'; $line = $items -join ','};"^
 " };"^
 " $modifiedContent += $line"^
 "};"^
 "$modifiedContent | set-content -literalpath '%destination%'"

Powershell has Import-CSV and Export-CSV which can handle CSV files, though Export-CSV outputs data with double quoted field items. Powershell 7 introduces arguments for quotes for Export-CSV, though is still new at this time. With Powershell less than 7, the suggestions are to read the file with Get-Content, remove double quotes and use Set-Content. Since the example content lacks double quotes, I decided to use Get-Content, split on commas and write with Set-Content.

The following code is a hybrid batch-file with powershell which I used as a basis to construct the previous code.
It has some comments that explains the code which is not suitable for inserting into a single powershell command.

<# :: Begin bat code

@echo off
setlocal

set "target=.\export.dat"
set "destination=.\updated.dat"

powershell -noprofile "invoke-expression(get-content '%~f0' | out-string)"

exit /b 0

#> ## Begin ps1 code

# Filepaths from environment variables.
$target = $env:target
$destination = $env:destination

# Read file content into a variable.
$content = get-content -literalpath $target

# Create an empty array for modified content.
$modifiedContent = @()

# Add 1st line as unmodified header.
$modifiedContent += $content[0]

# Add the rest of the lines.
foreach ($line in $content[1 .. ($content.length - 1)]) {

    # Require a leading capital D to modify a line.
    if ($line.startswith('D,')) {

        # Split by commas.
        $items = $line.split(',')

        # Modify item 14.
        if ($items.length -gt 14) {
            $items[14] += '0'
            $line = $items -join ','
        }
    }

    # Add line to array.
    $modifiedContent += $line
}

# Write modified content to destination file.
$modifiedContent | set-content -literalpath $destination

If suitable, the powershell code portion could be copied to a .ps1 file and just replace $target = $env:target and $destination = $env:destination with  $target = '.\export.dat' and $destination = '.\updated.dat'.

Input export.dat:

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00
d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330

Output updated.dat:

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,078330,300.00,078330
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00
d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330

1st line is the header unmodified.

2nd line is modified.

3rd line is too short in length to modify.

4th line does not start with D, as d, does not match same case so is not modified.


来源: stackexchange

问:
How do you properly determine the current script directory?
I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is hard to find a good solution.

Here are some problems:

__file__ is not defined if the script is executed with exec, execfile

__module__ is defined only in modules

Use cases:

./myfile.py

python myfile.py

./somedir/myfile.py

python somedir/myfile.py

execfile('myfile.py') (from another script, that can be located in another directory and that can have another current directory.

I know that there is no perfect solution, but I'm looking for the best approach that solves most of the cases.

The most used approach is os.path.dirname(os.path.abspath(__file__)) but this really doesn't work if you execute the script from another one with exec().

Warning

Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.

答:
If you really want to cover the case that a script is called via execfile(...), you can use the inspect module to deduce the filename (including the path).  As far as I am aware, this will work for all cases you listed:

```<code>filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you really want to cover the case that a script is called via execfile(...), you can use the inspect module to deduce the filename (including the path).  As far as I am aware, this will work for all cases you listed:

filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))

ContentLicense: CC BY-SA 3.0


问:
How do I create a header style which spans from left most end to right end of the screen irrespective of screensize?
I want to Stretch this BLUE BAR, from one end of the screen to the other end. Now it is stretching 980px. Depending upon the screen size it should span itself from one end to the other end.

If I increase 980px, allignment will change. How to make the bar responsive ?

What CSS should I use ?

html {
  height: 100%;
  width: 100%;
}

body {
  height: 980px;
  width: 100%;
  margin: 0;
  padding: 0;
}

header {
  width: 980px;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0;
  background: #0B61A5;
  color: white;
}

navigation {
  width: 980px;
  margin: 0;
  padding: 0;
  text-align: center;
}

navigation ul {
  width: 980px;
  list-style: none;
  padding: 0;
  margin: 0;
}

navigation ul li {
  display: inline;
  margin-right: 1em;
}

footer {
  width: 940px;
  height: 20px;
  margin: 0 0 10px 0;
  padding: 10px 20px;
  background: #0B61A5;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<html>
 <body>

  <header>
   <h1>OEMS User Area</h1>
  </header>

  <navigation>
   <ul>
    <li>User: </li>
    <li> Home </li>
    <li> Logout </li>
   </ul>
  </navigation>

  <footer> O.E.M.S </footer>

 </body>
</html></code>```

答:
Try this, it will stretch the bars. And put the content of your page in the .wrapper section, it will be 980px and centered

html {

  width: 100%;
}

body {

  width: 100%;
  margin: 0;
  padding: 0;
}

header {
  width: 100%;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0;
  background: #0B61A5;
  text-align: center;
  color: white;
}

navigation {
  width: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

navigation ul {
  width: 100%;
  list-style: none;
  padding: 0;
  margin: 0;
}

navigation ul li {
  display: inline;
  margin-right: 1em;
}

footer p {
   padding: 10px 20px;
}
footer {
  width: 100%;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0px;
  background: #0B61A5;
  color: white;
}
.wrapper {
   min-height: 900px;
   width: 980px;
   margin: auto;
   display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
 <body>

  <header>
   <h1>OEMS User Area</h1>
  </header>
  <navigation>
   <ul>
    <li>User: </li>
    <li> Home </li>
    <li> Logout </li>
   </ul>
     </navigation>
  <section class='wrapper'>
      THE CONTENT GOES HERE !
        </section>
  <footer><p> O.E.M.S </p></footer>
 </body>
</html></code>```

Body:
I want to Stretch this BLUE BAR, from one end of the screen to the other end. Now it is stretching 980px. Depending upon the screen size it should span itself from one end to the other end.

If I increase 980px, allignment will change. How to make the bar responsive ?

What CSS should I use ?

html {
  height: 100%;
  width: 100%;
}

body {
  height: 980px;
  width: 100%;
  margin: 0;
  padding: 0;
}

header {
  width: 980px;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0;
  background: #0B61A5;
  color: white;
}

navigation {
  width: 980px;
  margin: 0;
  padding: 0;
  text-align: center;
}

navigation ul {
  width: 980px;
  list-style: none;
  padding: 0;
  margin: 0;
}

navigation ul li {
  display: inline;
  margin-right: 1em;
}

footer {
  width: 940px;
  height: 20px;
  margin: 0 0 10px 0;
  padding: 10px 20px;
  background: #0B61A5;
  color: white;
}

OEMS User Area

  <navigation>

User:

 Home

 Logout

  </navigation>

   O.E.M.S

Body:
Try this, it will stretch the bars. And put the content of your page in the .wrapper section, it will be 980px and centered

html {

  width: 100%;
}

body {

  width: 100%;
  margin: 0;
  padding: 0;
}

header {
  width: 100%;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0;
  background: #0B61A5;
  text-align: center;
  color: white;
}

navigation {
  width: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

navigation ul {
  width: 100%;
  list-style: none;
  padding: 0;
  margin: 0;
}

navigation ul li {
  display: inline;
  margin-right: 1em;
}

footer p {
   padding: 10px 20px;
}
footer {
  width: 100%;
  height: 40px;
  margin: 0 0 10px 0;
  padding: 0px;
  background: #0B61A5;
  color: white;
}
.wrapper {
   min-height: 900px;
   width: 980px;
   margin: auto;
   display: block;
}

<html>
 <body>

  <header>
   <h1>OEMS User Area</h1>
  </header>
  <navigation>
   <ul>
    <li>User: </li>
    <li> <a href="">Home</a> </li>
    <li> <a href="">Logout</a> </li>
   </ul>
     </navigation>
  <section class='wrapper'>
      THE CONTENT GOES HERE !
        </section>
  <footer><p> O.E.M.S </p></footer>
 </body>
</html>


问:
ExpressJS: localhost didn’t send any data
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then  the browser shows a message:

```<code>localhost didn’t send any data.
ERR_EMPTY_RESPONSE
</code>```

Here is my app.js:

```<code>const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());

//const userRouter = require('./routes/user');
//app.use('/user', userRouter);

const startApp = async () => {
    try {
        await mongoose.connect('mongodb+srv://username:pass@cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
        { useUnifiedTopology: true,useNewUrlParser: true });
        console.log(`successfully connected to database`);
        const port = process.env.PORT || 5000
        app.listen(port, () => {
            console.log(`server runnin at ${port}`);
        });
    } catch (error) {
        console.log(error.message)
    }
}

startApp();

app.get('/', (req, res) => {
    console.log("I am in the root");
    res.send("hello World");
})
</code>```

Why server is not responding from the browser?

答:
I had the same problem db is connected but not able to send data. it looks weird but it works for me.

Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user

here is my db connection may it helps you too

```<code>mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true  })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))

app.use(express.json())
</code>```

Body:
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then  the browser shows a message:

localhost didn’t send any data.
ERR_EMPTY_RESPONSE

Here is my app.js:

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());

//const userRouter = require('./routes/user');
//app.use('/user', userRouter);

const startApp = async () => {
    try {
        await mongoose.connect('mongodb+srv://username:pass@cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
        { useUnifiedTopology: true,useNewUrlParser: true });
        console.log(`successfully connected to database`);
        const port = process.env.PORT || 5000
        app.listen(port, () => {
            console.log(`server runnin at ${port}`);
        });
    } catch (error) {
        console.log(error.message)
    }
}

startApp();

app.get('/', (req, res) => {
    console.log("I am in the root");
    res.send("hello World");
})

Why server is not responding from the browser?

Body:
I had the same problem db is connected but not able to send data. it looks weird but it works for me.

Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user

here is my db connection may it helps you too

mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true  })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))

app.use(express.json())


问:
System.IO.FileLoadException:
This is the segment of code I used, note the **** is the replacement for my name

```<code>using System;
using ArduinoUploader;
using ArduinoUploader.Hardware;

namespace SoftwareAssignment
{
    class Program
    {
        static void Main(string[] args)
        {
            var uploader = new ArduinoSketchUploader(
                new ArduinoSketchUploaderOptions()
                {
                     FileName = @"C:\Users\****\OneDrive\Desktop\Blink\Blink.hex",
                     PortName = "COM5",
                     ArduinoModel = ArduinoModel.Micro
                });

            uploader.UploadSketch();
        }
    }
</code>```

I recieved the exception whilst using the ArduinoUploader to upload a .hex file onto an arduino whilst in Visual Studio 2019.

```<code>System.IO.FileLoadException: 'Could not load file or assembly 'IntelHexFormatReader, Version=2.2.3.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)'
</code>```

These are the details

```<code>System.IO.FileLoadException
  HResult=0x80131040
  Message=Could not load file or assembly 'IntelHexFormatReader, Version=2.2.3.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
  Source=ArduinoUploader
  StackTrace:
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch(IEnumerable`1 hexFileContents)
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch()
   at SoftwareAssignment.Program.Main(String[] args) in C:\Users\****\source\repos\SoftwareAssignment\SoftwareAssignment\Program.cs:line 20

</code>```

I do not know how I should go around troubleshooting this or if it is a resultant of the ArduinoUploader package using an older verison of the .NET framework, or if there is anyway to fix this at all. The code is written in C#.

答:
You can rebind assemblies in many ways, the easiest for me personally is in the config file. Below from

https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/redirect-assembly-versions

```<code><dependentAssembly>
  <assemblyIdentity name="someAssembly"
    publicKeyToken="32ab4ba45e0a69a1"
    culture="en-us" />
  <bindingRedirect oldVersion="7.0.0.0"
newVersion="8.0.0.0" />
</dependentAssembly>
</code>```

Do note however that there are no guarantees the assembly you have will work as you expect, be it older or newer. I'd suggest you try to find the right one. That said, if you can't, then above is your best shot.

Title: System.IO.FileLoadException:

Body:
This is the segment of code I used, note the **** is the replacement for my name

using System;
using ArduinoUploader;
using ArduinoUploader.Hardware;

namespace SoftwareAssignment
{
    class Program
    {
        static void Main(string[] args)
        {
            var uploader = new ArduinoSketchUploader(
                new ArduinoSketchUploaderOptions()
                {
                     FileName = @"C:\Users\****\OneDrive\Desktop\Blink\Blink.hex",
                     PortName = "COM5",
                     ArduinoModel = ArduinoModel.Micro
                });

            uploader.UploadSketch();
        }
    }

I recieved the exception whilst using the ArduinoUploader to upload a .hex file onto an arduino whilst in Visual Studio 2019.

System.IO.FileLoadException: 'Could not load file or assembly 'IntelHexFormatReader, Version=2.2.3.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)'

These are the details

System.IO.FileLoadException
  HResult=0x80131040
  Message=Could not load file or assembly 'IntelHexFormatReader, Version=2.2.3.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
  Source=ArduinoUploader
  StackTrace:
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch(IEnumerable`1 hexFileContents)
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch()
   at SoftwareAssignment.Program.Main(String[] args) in C:\Users\****\source\repos\SoftwareAssignment\SoftwareAssignment\Program.cs:line 20

I do not know how I should go around troubleshooting this or if it is a resultant of the ArduinoUploader package using an older verison of the .NET framework, or if there is anyway to fix this at all. The code is written in C#.

Body:
You can rebind assemblies in many ways, the easiest for me personally is in the config file. Below from

https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/redirect-assembly-versions

<dependentAssembly>
  <assemblyIdentity name="someAssembly"
    publicKeyToken="32ab4ba45e0a69a1"
    culture="en-us" />
  <bindingRedirect oldVersion="7.0.0.0"
newVersion="8.0.0.0" />
</dependentAssembly>

Do note however that there are no guarantees the assembly you have will work as you expect, be it older or newer. I'd suggest you try to find the right one. That said, if you can't, then above is your best shot.


问:
google recaptcha error in codeigniter php while submiting form
i have created a form in codeigniter and given a google captcha v2, i have created the site key and secret key added it to config files, and also added the js and the recaptcha div including my site key. the following is my captcha function in controller:

public function validate_captcha() {
          $recaptcha = trim($this->input->post('g-recaptcha-response'));
          $userIp= $this->input->ip_address();
          $secret='xxxxxxxxxxxx'; (i have given my scret key here)
          $secretdata = array(
              'secret' => "$secret",
              'response' => "$recaptcha",
              'remoteip' =>"$userIp"
          );

          $verify = curl_init();
          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($verify);
          $status= json_decode($response, true);
          if(empty($status['success'])){
              return FALSE;
          }else{
              return TRUE;
          }
      }```
</div>
</div>
</p>

<p>the following is my register form function in same controller:</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-html lang-html prettyprint-override"><code>public function ajaxRegAction() {
   $this->load->library('session');
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
  header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
  $this->load->library('form_validation');
  $utype='W';
    $dhamu = $this->validate_captcha();
  $createddate  = date('Y-m-d h:i:s');
  $createdby = '0';
  $mobile = $this->input->post('phone');
  $form_data = array(
    'type' => $utype,
    'unique_id' => $this->mainModel->generateIndividualID(),
    'phone_num' => $mobile,
    'email' => $this->input->post('email'),
    'first_name' => $this->input->post('firstname'),
    'last_name' => $this->input->post('lastname'),
    'created_by' => $createdby,
    'created_date' => $createddate,
  );
  $name = $this->input->post('firstname')." ".$this->input->post('lastname');
  $access_info = array('user_type'=>$utype);

   $check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
   $checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
   if($check==0) {

        if($dhamu==1){

    $insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));

    $message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
    $email_message=$message;
    $message=rawurlencode($message);
    $this->mainModel->sendOtptoCustomer($mobile,$message);
    $this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);

echo "success";
}

else{ echo "Captcha Error";}

}

else{
echo "Registration Failed !";

   }</code>```

even if i check the google recaptcha box and press register, the form is showing  "Captcha Error", values are not being added to the database also. can anyone please tell me what could be wrong here, thanks in advance

答:
Step 1:
Make sure you have added localhost in your domain in Google Captcha V2 dashboard.

Step 2:

I am modifying your function you can use it like this:

```<code>public function validate_captcha()
{
    if(isset($_POST['g-recaptcha-response']))
    {
        $captcha=$_POST['g-recaptcha-response'];
    }

    $secretKey = "Put your secret key here";
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response,true);
    // should return JSON with success as true
    if($responseKeys["success"]) {
        return TRUE;
    } else {
        return FALSE;
    }
}
</code>```

instead of CURL

Do let me know if this works

Body:
i have created a form in codeigniter and given a google captcha v2, i have created the site key and secret key added it to config files, and also added the js and the recaptcha div including my site key. the following is my captcha function in controller:

public function validate_captcha() {
          $recaptcha = trim($this->input->post('g-recaptcha-response'));
          $userIp= $this->input->ip_address();
          $secret='xxxxxxxxxxxx'; (i have given my scret key here)
          $secretdata = array(
              'secret' => "$secret",
              'response' => "$recaptcha",
              'remoteip' =>"$userIp"
          );

          $verify = curl_init();
          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($verify);
          $status= json_decode($response, true);
          if(empty($status['success'])){
              return FALSE;
          }else{
              return TRUE;
          }
      }

the following is my register form function in same controller:

public function ajaxRegAction() {
   $this->load->library('session');
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
  header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
  $this->load->library('form_validation');
  $utype='W';
    $dhamu = $this->validate_captcha();
  $createddate  = date('Y-m-d h:i:s');
  $createdby = '0';
  $mobile = $this->input->post('phone');
  $form_data = array(
    'type' => $utype,
    'unique_id' => $this->mainModel->generateIndividualID(),
    'phone_num' => $mobile,
    'email' => $this->input->post('email'),
    'first_name' => $this->input->post('firstname'),
    'last_name' => $this->input->post('lastname'),
    'created_by' => $createdby,
    'created_date' => $createddate,
  );
  $name = $this->input->post('firstname')." ".$this->input->post('lastname');
  $access_info = array('user_type'=>$utype);

   $check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
   $checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
   if($check==0) {

        if($dhamu==1){

    $insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));

    $message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
    $email_message=$message;
    $message=rawurlencode($message);
    $this->mainModel->sendOtptoCustomer($mobile,$message);
    $this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);

echo "success";
}

else{ echo "Captcha Error";}

}

else{
echo "Registration Failed !";

   }

even if i check the google recaptcha box and press register, the form is showing  "Captcha Error", values are not being added to the database also. can anyone please tell me what could be wrong here, thanks in advance

Body:
Step 1:
Make sure you have added localhost in your domain in Google Captcha V2 dashboard.

Step 2:

I am modifying your function you can use it like this:

public function validate_captcha()
{
    if(isset($_POST['g-recaptcha-response']))
    {
        $captcha=$_POST['g-recaptcha-response'];
    }

    $secretKey = "Put your secret key here";
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response,true);
    // should return JSON with success as true
    if($responseKeys["success"]) {
        return TRUE;
    } else {
        return FALSE;
    }
}

instead of CURL

Do let me know if this works


问:
NVENC ME-only mode OpenEncodeSessionEx() fail with "invalid struct version" error
I got stuck with a strange behavior, trying to initialize NVENC in ME-only mode. OpenEncodeSessionEx() always fail with #15 - "This indicates that an invalid struct version was used by the client."

Parameters struct is as follow:

```<code>  NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = {
    .version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER,
    .deviceType = NV_ENC_DEVICE_TYPE_CUDA,
    .device = ctx,
    .reserved = 0,
    .apiVersion = NVENCAPI_VERSION,
    .reserved1 = 0,
    .reserved2 = NULL
  };
  int ret = encOpenEncodeSessionEx(&session_params, &encoder->enc);
</code>```

I tried to invoke it from different C and Golang environments, but whatever I do I get that error. Encoder from NVENC samples just crashed (segfault). Decoder works flawlessly, while encoder doesn't.

Does anyone know, what exact conditions may cause the error #15 - NV_ENC_ERR_INVALID_VERSION?

I upgraded Cuda to 10.2 with 440.82 driver - no luck. Tried to downgrade to Cuda 10.0 - still the same. I use 1060ti GPU.

Anyone help me please))

答:
Ok, I finally figure it out.

It was so stupid of me but the problem was in the static keyword (C-language). I wrote simple wrapper to call NVENC function, like this:

```<code>static NVENCSTATUS encOpenEncodeSessionEx(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS *params, void **encoder) {
  return nvenc_api.nvEncOpenEncodeSessionEx(params, encoder);
}
</code>```

Use it in this manner and you're always get NV_ENC_ERR_INVALID_VERSION error. Just remove static keyword and the function works as expected.

I have no idea, if it is expected behavior or not, but it works.
Thanks to all.

Body:
I got stuck with a strange behavior, trying to initialize NVENC in ME-only mode. OpenEncodeSessionEx() always fail with #15 - "This indicates that an invalid struct version was used by the client."

Parameters struct is as follow:

  NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = {
    .version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER,
    .deviceType = NV_ENC_DEVICE_TYPE_CUDA,
    .device = ctx,
    .reserved = 0,
    .apiVersion = NVENCAPI_VERSION,
    .reserved1 = 0,
    .reserved2 = NULL
  };
  int ret = encOpenEncodeSessionEx(&session_params, &encoder->enc);

I tried to invoke it from different C and Golang environments, but whatever I do I get that error. Encoder from NVENC samples just crashed (segfault). Decoder works flawlessly, while encoder doesn't.

Does anyone know, what exact conditions may cause the error #15 - NV_ENC_ERR_INVALID_VERSION?

I upgraded Cuda to 10.2 with 440.82 driver - no luck. Tried to downgrade to Cuda 10.0 - still the same. I use 1060ti GPU.

Anyone help me please))

Body:
Ok, I finally figure it out.

It was so stupid of me but the problem was in the static keyword (C-language). I wrote simple wrapper to call NVENC function, like this:

static NVENCSTATUS encOpenEncodeSessionEx(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS *params, void **encoder) {
  return nvenc_api.nvEncOpenEncodeSessionEx(params, encoder);
}

Use it in this manner and you're always get NV_ENC_ERR_INVALID_VERSION error. Just remove static keyword and the function works as expected.

I have no idea, if it is expected behavior or not, but it works.
Thanks to all.


问:
Change start of weekday from monday to sunday in datetimeindex in python
The default start of the weekday is Monday (0) in Pandas. Am trying to make this as Sunday instead on datetimeindex for getting weekly counts ending on Saturday to forecast a timeseries model.</p>

答:
I got a breakthrough, yes.

From my previous code, I redefined W-SAT instead of the default W.
Previous code:
weekreq = daysreq.resample('W').apply({'Numbers':'sum'})

to
New code:
weekreq = daysreq.resample('W-SAT').apply({'Numbers':'sum'})


问:
Extract links_Using Python
I am looking out to extract links found in "Next" across all pages and append them to lists...............................................................................................................................................................
  Please guide me on this.</p>

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
  return 'http:' + url
 return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,'html.parser')
 pagination_container_company = soup.find_all("table", class_="pagination-container-company")[0].text
 sub_link = re.search('href="(.*)">Next', pagination_container_company).group(1)
 sub_link_edit.append(convert(sub_link))
 next_link=convert(sub_link)

 data_df = pd.DataFrame()
 df = pd.DataFrame(
  {
 'Link': sub_link_edit
  })
 data_df = pd.concat([data_df, df], sort=False)

 print(df.shape)
 tot_sub=len(sub_link_edit)
 print(tot_sub)

 data_df.to_csv('results_1.csv')
</code>```

答:
you should probably use a webscraper for this kind of problem, otherwise you will be unable to handle any javascript magic (e.g. on page load)...although it might not be a problem in this case.

you also need to pass bs4 the content of the page, not the entire response object

```<code>soup = BeautifulSoup(page.content)
</code>```

since you are already using bs4 to search for the table, why not use it to search directly for the link you are interested in? like so:

```<code>sub_link = soup.body.findAll("a", text="Next")[0].get('href')
</code>```

Title: Extract links_Using Python

Body:
I am looking out to extract links found in "Next" across all pages and append them to lists...............................................................................................................................................................
  Please guide me on this.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
  return 'http:' + url
 return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,'html.parser')
 pagination_container_company = soup.find_all("table", class_="pagination-container-company")[0].text
 sub_link = re.search('href="(.*)">Next', pagination_container_company).group(1)
 sub_link_edit.append(convert(sub_link))
 next_link=convert(sub_link)

 data_df = pd.DataFrame()
 df = pd.DataFrame(
  {
 'Link': sub_link_edit
  })
 data_df = pd.concat([data_df, df], sort=False)

 print(df.shape)
 tot_sub=len(sub_link_edit)
 print(tot_sub)

 data_df.to_csv('results_1.csv')

Body:
you should probably use a webscraper for this kind of problem, otherwise you will be unable to handle any javascript magic (e.g. on page load)...although it might not be a problem in this case.

you also need to pass bs4 the content of the page, not the entire response object

soup = BeautifulSoup(page.content)

since you are already using bs4 to search for the table, why not use it to search directly for the link you are interested in? like so:

sub_link = soup.body.findAll("a", text="Next")[0].get('href')


问:
PHP cURL Cancel Subscription PayPal issues
I will admit, I have been on this for 3 days, back and forth through documentation, and even learned how to create my own products and plans through Postman.

So I have a complete working subscription button, now I learned I need to save the Subscription ID in order to cancel the subscription so now that is saving and loading perfectly.

To my sad surprise, I need to get an AuthKey every time someone wants to cancel, so I need to run 2 cURL commands, 1 GET Auth Key, and 1 POST cancel a subscription. How would I do this in PHP?

I don't get any errors when these commands run just no data.

Paypal cURL Example:
https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_cancel

```<code>////////////////////////////// GET TEMP ACCESS TOKEN/////////////////////////////////
$ch = curl_init();
$clientId = "x";
$secret = "x";
$myIDKEY = "";

curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$result = curl_exec($ch);

if(empty($result))die("Error: No response.");
else
{
    $json = json_decode($result);
    print_r($json->access_token);
    $myIDKEY = $json->access_token;
}

curl_close($ch);

/////////////////////////////// SEND CANCEL POST ////////////////////////////////
$ch = curl_init();
$headers  = [
            'Authorization: Bearer '.$myIDKEY,
            'Content-Type: application/json'
        ];
$postData = [
    'reason' => 'clicked cancel subscription button'
];
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/billing/subscriptions/".$_SESSION['honeybeesubID']."/cancel");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result     = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo $myIDKEY
</code>```

Thank you so much!

答:
As documented at https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_cancel , a success response is an HTTP 204 with no data.

So, it will be normal to receive an empty response, along with that status code.

Body:
I will admit, I have been on this for 3 days, back and forth through documentation, and even learned how to create my own products and plans through Postman.

So I have a complete working subscription button, now I learned I need to save the Subscription ID in order to cancel the subscription so now that is saving and loading perfectly.

To my sad surprise, I need to get an AuthKey every time someone wants to cancel, so I need to run 2 cURL commands, 1 GET Auth Key, and 1 POST cancel a subscription. How would I do this in PHP?

I don't get any errors when these commands run just no data.

Paypal cURL Example:
https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_cancel

////////////////////////////// GET TEMP ACCESS TOKEN/////////////////////////////////
$ch = curl_init();
$clientId = "x";
$secret = "x";
$myIDKEY = "";

curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$result = curl_exec($ch);

if(empty($result))die("Error: No response.");
else
{
    $json = json_decode($result);
    print_r($json->access_token);
    $myIDKEY = $json->access_token;
}

curl_close($ch);

/////////////////////////////// SEND CANCEL POST ////////////////////////////////
$ch = curl_init();
$headers  = [
            'Authorization: Bearer '.$myIDKEY,
            'Content-Type: application/json'
        ];
$postData = [
    'reason' => 'clicked cancel subscription button'
];
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/billing/subscriptions/".$_SESSION['honeybeesubID']."/cancel");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result     = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo $myIDKEY

Thank you so much!


问:
How to implement "hold and drag" gesture in flutter?
"hold and drag" - would be holding down with one finger and dragging horizontally (or vertically) with another.

GestureDetector would recognize it as Scale gesture. I want to differentiate between these 2:

Two fingers moving closer or further apart (normal scale)

One finger holding and another finger moving closer or further (I want to detect this)

答:
There's  a built-in Widget for that called LongPressDraggable you can use it similar to the Draggable widget.

The one main common difference being the ability to directly drag using the Draggable widget or hold and drag using the LongPressDraggable Widget.


问:
Can someone please point out what's wrong here
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

```<code>public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }
</code>```

答:
It sounds like FileNotFoundException extends IOException. Try inverting the two catch statements and you should be good.

Class FileNotFoundException
  java.lang.Object
  java.lang.Throwable
  java.lang.Exception
  java.io.IOException
  java.io.FileNotFoundException

See https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

Body:
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }


问:
How to unpack result of `zip` which might be empty?
I have a generator for tuples which I want to use like this:

```<code>def pairs():
    yield from [("key1", 2), ("key2", 4), ("key3", 6)]

keys, values = zip(*pairs())
</code>```

Works like a charm, but now pairs() can also yield nothing resulting in an expression equivalent to

```<code>keys, values = []
</code>```

Is it possible to force the output of zip to have a given dimension in a nice single expression?

What I'd like to have is something like this:

>>> keys, values = magic_extender(zip(*pairs()), 2)
>>> keys, values
((), ())
```

答:
My Python version (3.7)

I suggest that if you working with keys and values you should use dictionary's

and then the solution is not hard...

solution

def pairs():
    """
    documentation of the function.

    Returns
    -------
        dict
            The function returns dictionary...
    """
    yield {"key1": 2, "key2": 4, "key3": 6}

def main():
    pair = dict(next(pairs()))
    keys, values = list(pair.keys()), list(pair.values())
    print(keys, values)

if __name__ == '__main__':
    main()
```
<p>In this solution the output will be:</p>
```['key1', 'key2', 'key3'] [2, 4, 6]
```
<p>and if the dictionary is empty the output will be:</p>
```[] []
```

Body:
I have a generator for tuples which I want to use like this:

def pairs():
    yield from [("key1", 2), ("key2", 4), ("key3", 6)]

keys, values = zip(*pairs())

Works like a charm, but now pairs() can also yield nothing resulting in an expression equivalent to

keys, values = []

Is it possible to force the output of zip to have a given dimension in a nice single expression?

What I'd like to have is something like this:

>>> keys, values = magic_extender(zip(*pairs()), 2)
>>> keys, values
((), ())

Body:
My Python version (3.7)

I suggest that if you working with keys and values you should use dictionary's

and then the solution is not hard...

solution

def pairs():
    """
    documentation of the function.

    Returns
    -------
        dict
            The function returns dictionary...
    """
    yield {"key1": 2, "key2": 4, "key3": 6}

def main():
    pair = dict(next(pairs()))
    keys, values = list(pair.keys()), list(pair.values())
    print(keys, values)

if __name__ == '__main__':
    main()

In this solution the output will be:

['key1', 'key2', 'key3'] [2, 4, 6]

and if the dictionary is empty the output will be:

[] []


问:
Is there anyway to have Dynamic Controller in PHP Codeigniter
I am new to PHP coding and I need to know is there anyway to have a dynamic controller name(not controller function name) in Codeigniter.

I am having around 5 Controllers like Sf_client.php, Sf_network.php, Sf_display.php etc... and coding are same in all these 5 controllers except one variable name which is different.

```<code> <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Sf_client extends UTF_Controller
    {

        function __construct() {
            parent::__construct();
            $this->resource_subtype = "client";
        }

        public function list() {
            $data['page_title'] = 'Client list';
            $this->template->set_title('CTL - '.$data['page_title']);
            $this->template->build('resources/list',$data);
        }
    }
?>
</code>```

Other Controllers are similar to the above except the $this->resource_subtype = "client", it will be like "network", "display" etc...

Now the url is like, http://localhost/Sf_client/, http://localhost/Sf_network/ etc...

Is there anyway to have one Controller file and passing the variable name ? So that I can eliminate the duplicate Controller files.

I am having other Controllers as well. So, i need something like if it matches "sf" in the url.

Any help will be most appreciated. Thank you.

答:
Creating dynamic controllers is not possible because even if you name the class dynamically, you still would have to have a file of the same name. That's how CI's URL work.

What you could do, however, is that configure the routing so that when
  you hit a certain URL it corresponds to another controller, then
  in that controller you can check the URL and assign desired value
  to the variable accordingly.

I created a demo for your problem and this ↓ worked for me. See, if it works for you as well.

routes.php

```<code>$route['default']    = 'Sf_client'; // say default is 'Sf_client' -- you can ignore it if you already have a default. We'll be creating only this controller.
$route['Sf_network'] = 'Sf_client'; // route requests to this controller
$route['Sf_display'] = 'Sf_client'; // ...
</code>```

view

```<code><a href="<?PHP echo base_url(); ?>">Sf_client</a> <!-- OR base_url('Sf_client'); // if not default -->
<a href="<?PHP echo base_url('Sf_network'); ?>">Sf_network</a> <!-- will correspond to Sf_client but the URL won't change -->
<a href="<?PHP echo base_url('Sf_display'); ?>">Sf_display</a> <!-- ... -->
</code>```

Sf_client.php(controller)

```<code>class Sf_client extends UTF_Controller{

    function __construct() {

        parent::__construct();

        $segment = $this->uri->segment(1); // get the first segment from the URL which is controller's name

        switch($segment){ // check the segment value

            case 'Sf_network':
                $this->resource_subtype = 'network';
                break;

            case 'Sf_display':
                $this->resource_subtype = 'display';
                break;

            // ignore if default ↓↓
            /* case 'Sf_client':
                $this->resource_subtype = 'client';
                break; */

            default:
                $this->resource_subtype = 'client';
        }
        echo $this->resource_subtype; // will return network if in http://localhost/Sf_network
    }
</code>```

Body:
I am new to PHP coding and I need to know is there anyway to have a dynamic controller name(not controller function name) in Codeigniter.

I am having around 5 Controllers like Sf_client.php, Sf_network.php, Sf_display.php etc... and coding are same in all these 5 controllers except one variable name which is different.

 <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Sf_client extends UTF_Controller
    {

        function __construct() {
            parent::__construct();
            $this->resource_subtype = "client";
        }

        public function list() {
            $data['page_title'] = 'Client list';
            $this->template->set_title('CTL - '.$data['page_title']);
            $this->template->build('resources/list',$data);
        }
    }
?>

Other Controllers are similar to the above except the $this->resource_subtype = "client", it will be like "network", "display" etc...

Now the url is like, http://localhost/Sf_client/, http://localhost/Sf_network/ etc...

Is there anyway to have one Controller file and passing the variable name ? So that I can eliminate the duplicate Controller files.

I am having other Controllers as well. So, i need something like if it matches "sf" in the url.

Any help will be most appreciated. Thank you.

Body:
Creating dynamic controllers is not possible because even if you name the class dynamically, you still would have to have a file of the same name. That's how CI's URL work.

What you could do, however, is that configure the routing so that when
  you hit a certain URL it corresponds to another controller, then
  in that controller you can check the URL and assign desired value
  to the variable accordingly.

I created a demo for your problem and this ↓ worked for me. See, if it works for you as well.

routes.php

$route['default']    = 'Sf_client'; // say default is 'Sf_client' -- you can ignore it if you already have a default. We'll be creating only this controller.
$route['Sf_network'] = 'Sf_client'; // route requests to this controller
$route['Sf_display'] = 'Sf_client'; // ...

view

<a href="<?PHP echo base_url(); ?>">Sf_client</a> <!-- OR base_url('Sf_client'); // if not default -->
<a href="<?PHP echo base_url('Sf_network'); ?>">Sf_network</a> <!-- will correspond to Sf_client but the URL won't change -->
<a href="<?PHP echo base_url('Sf_display'); ?>">Sf_display</a> <!-- ... -->

Sf_client.php(controller)

class Sf_client extends UTF_Controller{

    function __construct() {

        parent::__construct();

        $segment = $this->uri->segment(1); // get the first segment from the URL which is controller's name

        switch($segment){ // check the segment value

            case 'Sf_network':
                $this->resource_subtype = 'network';
                break;

            case 'Sf_display':
                $this->resource_subtype = 'display';
                break;

            // ignore if default ↓↓
            /* case 'Sf_client':
                $this->resource_subtype = 'client';
                break; */

            default:
                $this->resource_subtype = 'client';
        }
        echo $this->resource_subtype; // will return network if in http://localhost/Sf_network
    }


问:
BASH: Best way to set variable from array
Bash 4 on Linux ~

I have an array of possible values. I must restrict user input to these values.

```<code>Arr=(hello kitty goodbye quick fox)
</code>```

User supplies value as argument to script:

```<code>bash myscript.sh -b var
</code>```

Currently, I'm trying the following:

```<code>function func_exists () {
_var="$1"
for i in ${Arr[@]}
do
    if [ "$i" == "$_var" ]
    then
        echo hooray for "$_var"
        return 1
    fi
done
    return 0
}

func_exists $var
if [ $? -ne 1 ];then
    echo "Not a permitted value."
    func_help
    exit $E_OPTERROR
fi
</code>```

Seems to work fine, are there better methods for testing user input against an array of allowed values?

UPDATE: I like John K's answer ...can someone clarify the use of $@? I understand that this represents all positional parameters -- so we shift the first param off the stack and $@ now represents all remaining params, those being the passed array ...is that correct? I hate blindly using code without understanding ...even if it works!

答:
Your solution is what I'd do. Maybe using a few more shell-isms, such as returning 0 for success and non-0 for failure like UNIX commands do in general.

```<code># Tests if $1 is in the array ($2 $3 $4 ...).
is_in() {
    value=$1
    shift

    for i in "$@"; do
        [[ $i == $value ]] && return 0
    done

    return 1
}

if ! is_in "$var" "${Arr[@]}"; then
    echo "Not a permitted value." >&2
    func_help
    exit $E_OPTERROR
fi
</code>```

Careful use of double quotes makes sure this will work even if the individual array entries contain spaces, which is allowed. This is a two element array: list=('hello world' 'foo bar').

Body:
Bash 4 on Linux ~

I have an array of possible values. I must restrict user input to these values.

Arr=(hello kitty goodbye quick fox)

User supplies value as argument to script:

bash myscript.sh -b var

Currently, I'm trying the following:

function func_exists () {
_var="$1"
for i in ${Arr[@]}
do
    if [ "$i" == "$_var" ]
    then
        echo hooray for "$_var"
        return 1
    fi
done
    return 0
}

func_exists $var
if [ $? -ne 1 ];then
    echo "Not a permitted value."
    func_help
    exit $E_OPTERROR
fi

Seems to work fine, are there better methods for testing user input against an array of allowed values?

UPDATE: I like John K's answer ...can someone clarify the use of $@? I understand that this represents all positional parameters -- so we shift the first param off the stack and $@ now represents all remaining params, those being the passed array ...is that correct? I hate blindly using code without understanding ...even if it works!

Body:
Your solution is what I'd do. Maybe using a few more shell-isms, such as returning 0 for success and non-0 for failure like UNIX commands do in general.

# Tests if $1 is in the array ($2 $3 $4 ...).
is_in() {
    value=$1
    shift

    for i in "$@"; do
        [[ $i == $value ]] && return 0
    done

    return 1
}

if ! is_in "$var" "${Arr[@]}"; then
    echo "Not a permitted value." >&2
    func_help
    exit $E_OPTERROR
fi

Careful use of double quotes makes sure this will work even if the individual array entries contain spaces, which is allowed. This is a two element array: list=('hello world' 'foo bar').


问:
How to send email in post_save without asking user to wait in form submission?
Here is my post_save method:

```<code>from asgiref.sync import sync_to_async

@receiver(post_save, sender=SubmissionDetails)
def create_submission_email(sender, instance, created, **kwargs):
    if created:
        data = sync_to_async(call_submssion_email(instance))

def call_manuscript_submssion_email(instance):
    print("Hi")
    message = '''Submitted with the title, <br>
    {0}'''.format(instance.title)
    subject = 'Article Submitted'
    to_address = 'example@gmail.com'
    from_address = "from@mail.example.com"
    msg = EmailMessage(
                    subject, message,from_address,[to_address]
                    )
    msg.content_subtype = "html"
    msg.send()
</code>```

The problem is while submitting the form, the user has to wait till email is sent to see the results. I am using django 3.0 with some async support.

答:
Asynchronous support

New in Django 3.0

Django has developing support for asynchronous (“async”) Python, but
  does not yet support asynchronous views or middleware; they will be
  coming in a future release.

There is limited support for other parts of the async ecosystem;
  namely, Django can natively talk ASGI, and some async safety support.

Django Asynchronous support official

You can use Django Channels or Celery for your asynchronous code.

You can also check How are Django channels different than celery?

Body:
Here is my post_save method:

from asgiref.sync import sync_to_async

@receiver(post_save, sender=SubmissionDetails)
def create_submission_email(sender, instance, created, **kwargs):
    if created:
        data = sync_to_async(call_submssion_email(instance))

def call_manuscript_submssion_email(instance):
    print("Hi")
    message = '''Submitted with the title,

    {0}'''.format(instance.title)
    subject = 'Article Submitted'
    to_address = 'example@gmail.com'
    from_address = "from@mail.example.com"
    msg = EmailMessage(
                    subject, message,from_address,[to_address]
                    )
    msg.content_subtype = "html"
    msg.send()

The problem is while submitting the form, the user has to wait till email is sent to see the results. I am using django 3.0 with some async support.


问:
Postman data array to variable in RAW Post Body
I'm using a data file for past man with the following JSON with the following data

```<code>{
    "FirstName": "Jennifer",
    "MiddleName": "Geraldine",
    "LastName": "Gemma",
    "email": "montes.nascetur@vulputatenisisem.net"
    "Phone":[{"Number":"55-(622)813-5953"},{"Number":"233-(935)372-8021"}]}
}
</code>```

I'm attempting to do a post with the following data variables in RAW

```<code>{
    "FirstName": "{{FirstName}}",
    "MiddleName": "{{MiddleName}}",
    "LastName": "{{LastName}}",
    "email": "{{email}}",
    "Phone": {{Phone}}
}
</code>```

All the data is being populated with the exception of the "Phone". {{Phone}} is not be substituted.

Is there a way of doing this or an alternative way of posting a JSON request?

OR

Is there an alternative way of posting this information in JSON using Postman from a data file?

答:
You can convert an array into a string as shown below in the data file. </p>

```<code>{
   "FirstName": "Jennifer",
   "MiddleName": "Geraldine",
   "LastName": "Gemma",
   "email": "montes.nascetur@vulputatenisisem.net",
   "Phone": "[{\"Number\":\"55-(622)813-5953\"},{\"Number\":\"233-(935)372-8021\"}]}"
}
</code>```

Body:
I'm using a data file for past man with the following JSON with the following data

{
    "FirstName": "Jennifer",
    "MiddleName": "Geraldine",
    "LastName": "Gemma",
    "email": "montes.nascetur@vulputatenisisem.net"
    "Phone":[{"Number":"55-(622)813-5953"},{"Number":"233-(935)372-8021"}]}
}

I'm attempting to do a post with the following data variables in RAW

{
    "FirstName": "{{FirstName}}",
    "MiddleName": "{{MiddleName}}",
    "LastName": "{{LastName}}",
    "email": "{{email}}",
    "Phone": {{Phone}}
}

All the data is being populated with the exception of the "Phone". {{Phone}} is not be substituted.

Is there a way of doing this or an alternative way of posting a JSON request?

OR

Is there an alternative way of posting this information in JSON using Postman from a data file?

Body:
You can convert an array into a string as shown below in the data file.

{
   "FirstName": "Jennifer",
   "MiddleName": "Geraldine",
   "LastName": "Gemma",
   "email": "montes.nascetur@vulputatenisisem.net",
   "Phone": "[{\"Number\":\"55-(622)813-5953\"},{\"Number\":\"233-(935)372-8021\"}]}"
}


问:
Angular routing not working when deployed statically with Node
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

```<code>...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});
</code>```

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

答:
above router.get, you should have :-</p>

```<code>// serve angular front end files from root path
router.use('/', express.static('public', { redirect: false }));
</code>```

Body:
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

Body:
above router.get, you should have :-

// serve angular front end files from root path
router.use('/', express.static('public', { redirect: false }));


问:
Gatsby always fetch cached data
I use gatsby-source-git to pull files from Github repository. It worked well, but I added some files into repository and I am not able to pull new files into my Gatsby project.

If I run this query in http://localhost:8000/___graphql:

```<code>query MyQuery {
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          title
        }
        fileAbsolutePath
      }
    }
  }
}
</code>```

I get this result:

```<code>{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "title": "Introduction"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/index.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Conceptual Guide"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/tau-conceptual-guide.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Tau & Agoras Overview"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/what-is-tauchain-tau.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "FAQs"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/tauchain-agoras-faqs.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Tutorials"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/index.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Analysis of TauBot.TML"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/analysis-of-taubot-tml.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "TML Bot Tutorial"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/tml-Bot-tutorial.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Understanding TML"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/understanding-tml-prolog-datalog-tau.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Quick Start"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/quick-start.md"
          }
        }
      ]
    }
  }
}
</code>```

Tutorials folder contains 6 files, which aren't included in query result. I don't know why.

gatsby-config.js

```<code>require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`
});

module.exports = {
  siteMetadata: {
    title: "Fan Site"
  },
  plugins: [
    "gatsby-plugin-react-helmet",
    "svgo",
    "gatsby-plugin-sass",
    "gatsby-plugin-postcss",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "data",
        path: `${__dirname}/src/data/`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/pages`,
        name: "pages"
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [`gatsby-remark-autolink-headers`]
      }
    },
    "gatsby-transformer-json",
    "gatsby-plugin-dark-mode",
    {
      resolve: "gatsby-source-prismic-graphql",
      options: {
        repositoryName: "funsite",
        accessToken: `${process.env.API_KEY}`
      }
    },
    {
      resolve: `gatsby-source-git`,
      options: {
        name: `tau-guide-documents`,
        remote: `https://github.com/TauGuide/tau-guide-documents.git`,
        branch: `master`,
        // Only import the docs folder from a codebase.
        patterns: `docs/**`
      }
    }
  ]
};
</code>```

I tried to add local: "/dev/tauguide/tau-guide-documents", as gatsby-source-git option, but it didn't help.

I tried to run gatsby clean which removed .cache folder and gatsby develop, but I got the same result. When .cache folder is generated, all files are there, only query result doesn't include them.

I tried to remove the project and pull it from git again, but it didn't help.

package.json

```<code>{
  "name": "fan-site",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "develop": "gatsby develop",
    "build": "gatsby build",
    "serve": "gatsby serve",
    "start": "node server.js",
    "gh-pages": "gatsby build --prefix-paths && gh-pages -d public",
    "lint": "eslint src --fix",
    "dev": "(shx --silent rm -rf public .cache || shx true) && gatsby develop",
    "server": "cross-env NODE_ENV=development DEBUG=api nodemon server.js",
    "postinstall": "npm rebuild node-sass"
  },
  "author": "Prototype Interactive",
  "license": "MIT",
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.25",
    "@fortawesome/free-brands-svg-icons": "^5.12.0",
    "@fortawesome/free-solid-svg-icons": "^5.11.2",
    "@fortawesome/react-fontawesome": "^0.1.7",
    "@kunukn/react-collapse": "1",
    "@material-ui/core": "^4.9.5",
    "@popperjs/core": "^2.3.3",
    "add": "^2.0.6",
    "axios": "^0.19.0",
    "basic-auth": "^2.0.1",
    "bootstrap": "4.2.1",
    "chart.js": "^2.9.3",
    "d3-node": "^2.2.1",
    "debug": "^4.1.1",
    "font-awesome": "4.7.0",
    "framer-motion": "^1.10.3",
    "gatsby": "^2.18.12",
    "gatsby-plugin-canonical-urls": "^2.3.0",
    "gatsby-plugin-dark-mode": "^1.1.0",
    "gatsby-remark-autolink-headers": "^2.3.3",
    "gatsby-source-git": "^1.0.2",
    "gatsby-source-prismic-graphql": "3.6.2",
    "gatsby-transformer-remark": "^2.6.53",
    "lodash.get": "^4.4.2",
    "lodash.groupby": "^4.6.0",
    "lodash.pickby": "^4.6.0",
    "lodash.set": "^4.3.2",
    "lodash.update": "^4.10.2",
    "marked": "^0.8.0",
    "moment": "^2.24.0",
    "prismic-reactjs": "^1.3.1",
    "prop-types": "^15.7.2",
    "react-chartjs-2": "^2.8.0",
    "react-collapsible": "^2.6.3",
    "react-d3-components": "^0.9.1",
    "react-d3-library": "^1.1.8",
    "react-headroom": "^3.0.0",
    "react-helmet": "^5.2.0",
    "react-lazyload": "^2.6.5",
    "react-moment": "^0.9.6",
    "react-onclickout": "^2.0.8",
    "react-popper": "^2.2.3",
    "react-popper-tooltip": "^2.11.1",
    "react-responsive": "^8.0.1",
    "react-scroll-to": "^3.0.0-beta.3",
    "react-select": "^3.1.0",
    "react-sidebar": "^3.0.2",
    "react-slick": "^0.25.2",
    "react-svg-donuts": "^1.0.0",
    "react-telegram-embed": "^0.0.10",
    "react-toastify": "^5.4.1",
    "react-twitter-embed": "^3.0.3",
    "react-window": "^1.8.5",
    "reactstrap": "^8.4.1",
    "slick-carousel": "^1.8.1",
    "underscore": "^1.9.1",
    "yarn": "^1.21.1"
  },
  "devDependencies": {
    "@prototype-interactive/eslint-config": "^0.1.1",
    "autoprefixer": "^9.4.4",
    "cross-env": "^5.2.0",
    "dotenv": "^8.2.0",
    "eslint": "^5.12.0",
    "gatsby-plugin-google-analytics": "^2.3.0",
    "gatsby-plugin-postcss": "^2.0.2",
    "gatsby-plugin-postcss-sass": "^1.0.22",
    "gatsby-plugin-react-helmet": "^3.0.5",
    "gatsby-plugin-sass": "^2.0.7",
    "gatsby-source-filesystem": "^2.2.2",
    "gatsby-transformer-json": "^2.1.7",
    "gh-pages": "^2.0.1",
    "husky": "^1.3.1",
    "prettier": "^1.15.3",
    "pretty-quick": "^1.8.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "shx": "^0.3.2",
    "svg-sprite-loader": "^4.1.3"
  },
  "resolutions": {
    "gatsby-source-graphql-universal": "3.3.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/PrototypeInteractive/gatsby-react-boilerplate.git"
  },
  "bugs": {
    "url": "https://github.com/PrototypeInteractive/gatsby-react-boilerplate/issues"
  },
  "homepage": "https://github.com/PrototypeInteractive/gatsby-react-boilerplate#readme"
}
</code>```

gatsby-node.js

```<code>const path = require(`path`);
const { createFilePath } = require(`gatsby-source-git`);

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions;
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` });
    createNodeField({
      node,
      name: `slug`,
      value: slug
    });
  }
};

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `);
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`src/templates/tau-document.js`),
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.fields.slug
      }
    });
  });
};
</code>```

答:
There only two files missing from the Tutorials folder: step-by-step-guide-how-to-buy-agoras.md and step-by-step-guide-how-to-store-agoras.md.

I think that the issue is with the formatting of the frontmatter in these files, not with gatsby-source-git.

As you can see, hat sets them apart from the other files is that they both have colon inside a value:

title: Agoras: How to Store

description: Agoras: How to Buy

You need to add quotes around those:

title: "Agoras: How to Store"

description: "Agoras: How to Buy"

Your query probably failed at parsing these, hence the files didn't appear. Let me know if this fixes your issue!

Title: Gatsby always fetch cached data

Body:
I use gatsby-source-git to pull files from Github repository. It worked well, but I added some files into repository and I am not able to pull new files into my Gatsby project.

If I run this query in http://localhost:8000/___graphql:

query MyQuery {
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          title
        }
        fileAbsolutePath
      }
    }
  }
}

I get this result:

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "title": "Introduction"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/index.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Conceptual Guide"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/tau-conceptual-guide.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Tau & Agoras Overview"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/what-is-tauchain-tau.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "FAQs"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/tauchain-agoras-faqs.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Tutorials"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/index.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Analysis of TauBot.TML"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/analysis-of-taubot-tml.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "TML Bot Tutorial"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/tml-Bot-tutorial.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Understanding TML"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/Tutorials/understanding-tml-prolog-datalog-tau.md"
          }
        },
        {
          "node": {
            "frontmatter": {
              "title": "Quick Start"
            },
            "fileAbsolutePath": "dev/tau-guide-website/.cache/gatsby-source-git/tau-guide-documents/docs/quick-start.md"
          }
        }
      ]
    }
  }
}

Tutorials folder contains 6 files, which aren't included in query result. I don't know why.

gatsby-config.js

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`
});

module.exports = {
  siteMetadata: {
    title: "Fan Site"
  },
  plugins: [
    "gatsby-plugin-react-helmet",
    "svgo",
    "gatsby-plugin-sass",
    "gatsby-plugin-postcss",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "data",
        path: `${__dirname}/src/data/`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/pages`,
        name: "pages"
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [`gatsby-remark-autolink-headers`]
      }
    },
    "gatsby-transformer-json",
    "gatsby-plugin-dark-mode",
    {
      resolve: "gatsby-source-prismic-graphql",
      options: {
        repositoryName: "funsite",
        accessToken: `${process.env.API_KEY}`
      }
    },
    {
      resolve: `gatsby-source-git`,
      options: {
        name: `tau-guide-documents`,
        remote: `https://github.com/TauGuide/tau-guide-documents.git`,
        branch: `master`,
        // Only import the docs folder from a codebase.
        patterns: `docs/**`
      }
    }
  ]
};

I tried to add local: "/dev/tauguide/tau-guide-documents", as gatsby-source-git option, but it didn't help.

I tried to run gatsby clean which removed .cache folder and gatsby develop, but I got the same result. When .cache folder is generated, all files are there, only query result doesn't include them.

I tried to remove the project and pull it from git again, but it didn't help.

package.json

{
  "name": "fan-site",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "develop": "gatsby develop",
    "build": "gatsby build",
    "serve": "gatsby serve",
    "start": "node server.js",
    "gh-pages": "gatsby build --prefix-paths && gh-pages -d public",
    "lint": "eslint src --fix",
    "dev": "(shx --silent rm -rf public .cache || shx true) && gatsby develop",
    "server": "cross-env NODE_ENV=development DEBUG=api nodemon server.js",
    "postinstall": "npm rebuild node-sass"
  },
  "author": "Prototype Interactive",
  "license": "MIT",
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.25",
    "@fortawesome/free-brands-svg-icons": "^5.12.0",
    "@fortawesome/free-solid-svg-icons": "^5.11.2",
    "@fortawesome/react-fontawesome": "^0.1.7",
    "@kunukn/react-collapse": "1",
    "@material-ui/core": "^4.9.5",
    "@popperjs/core": "^2.3.3",
    "add": "^2.0.6",
    "axios": "^0.19.0",
    "basic-auth": "^2.0.1",
    "bootstrap": "4.2.1",
    "chart.js": "^2.9.3",
    "d3-node": "^2.2.1",
    "debug": "^4.1.1",
    "font-awesome": "4.7.0",
    "framer-motion": "^1.10.3",
    "gatsby": "^2.18.12",
    "gatsby-plugin-canonical-urls": "^2.3.0",
    "gatsby-plugin-dark-mode": "^1.1.0",
    "gatsby-remark-autolink-headers": "^2.3.3",
    "gatsby-source-git": "^1.0.2",
    "gatsby-source-prismic-graphql": "3.6.2",
    "gatsby-transformer-remark": "^2.6.53",
    "lodash.get": "^4.4.2",
    "lodash.groupby": "^4.6.0",
    "lodash.pickby": "^4.6.0",
    "lodash.set": "^4.3.2",
    "lodash.update": "^4.10.2",
    "marked": "^0.8.0",
    "moment": "^2.24.0",
    "prismic-reactjs": "^1.3.1",
    "prop-types": "^15.7.2",
    "react-chartjs-2": "^2.8.0",
    "react-collapsible": "^2.6.3",
    "react-d3-components": "^0.9.1",
    "react-d3-library": "^1.1.8",
    "react-headroom": "^3.0.0",
    "react-helmet": "^5.2.0",
    "react-lazyload": "^2.6.5",
    "react-moment": "^0.9.6",
    "react-onclickout": "^2.0.8",
    "react-popper": "^2.2.3",
    "react-popper-tooltip": "^2.11.1",
    "react-responsive": "^8.0.1",
    "react-scroll-to": "^3.0.0-beta.3",
    "react-select": "^3.1.0",
    "react-sidebar": "^3.0.2",
    "react-slick": "^0.25.2",
    "react-svg-donuts": "^1.0.0",
    "react-telegram-embed": "^0.0.10",
    "react-toastify": "^5.4.1",
    "react-twitter-embed": "^3.0.3",
    "react-window": "^1.8.5",
    "reactstrap": "^8.4.1",
    "slick-carousel": "^1.8.1",
    "underscore": "^1.9.1",
    "yarn": "^1.21.1"
  },
  "devDependencies": {
    "@prototype-interactive/eslint-config": "^0.1.1",
    "autoprefixer": "^9.4.4",
    "cross-env": "^5.2.0",
    "dotenv": "^8.2.0",
    "eslint": "^5.12.0",
    "gatsby-plugin-google-analytics": "^2.3.0",
    "gatsby-plugin-postcss": "^2.0.2",
    "gatsby-plugin-postcss-sass": "^1.0.22",
    "gatsby-plugin-react-helmet": "^3.0.5",
    "gatsby-plugin-sass": "^2.0.7",
    "gatsby-source-filesystem": "^2.2.2",
    "gatsby-transformer-json": "^2.1.7",
    "gh-pages": "^2.0.1",
    "husky": "^1.3.1",
    "prettier": "^1.15.3",
    "pretty-quick": "^1.8.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "shx": "^0.3.2",
    "svg-sprite-loader": "^4.1.3"
  },
  "resolutions": {
    "gatsby-source-graphql-universal": "3.3.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/PrototypeInteractive/gatsby-react-boilerplate.git"
  },
  "bugs": {
    "url": "https://github.com/PrototypeInteractive/gatsby-react-boilerplate/issues"
  },
  "homepage": "https://github.com/PrototypeInteractive/gatsby-react-boilerplate#readme"
}

gatsby-node.js

const path = require(`path`);
const { createFilePath } = require(`gatsby-source-git`);

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions;
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` });
    createNodeField({
      node,
      name: `slug`,
      value: slug
    });
  }
};

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `);
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`src/templates/tau-document.js`),
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.fields.slug
      }
    });
  });
};


问:
How can i trim spaces in object.values?
my object.values(article.data) returns

```<code>[' This is ']
['is ']
['a']
['sentence ']
</code>```

how can i trim and remove the spaces so it becomes

```<code>['Thisis']
['is']
['a']
['sentence']
</code>```

答:
considering your array is named ar

```<code>ar.map(s => s.trim());
</code>```

it should return the array trimmed

Title: How can i trim spaces in object.values?

Body:
my object.values(article.data) returns

[' This is ']
['is ']
['a']
['sentence ']

how can i trim and remove the spaces so it becomes

['Thisis']
['is']
['a']
['sentence']

Body:
considering your array is named ar

ar.map(s => s.trim());

it should return the array trimmed


问:
Unhandled Rejection: default.get is not a function
I'm trying to make a simple get request using axios in my react component using the following function:

```<code>import React from 'react';
import api from '../../assets/API';
import {useEffect, useState} from 'react';

export default function Chart() {
    const [apiData, setDataApi] = useState({ elements: [] });

    useEffect(() => {
    const fetchData = async () => {
        const result = await api.get('/countries');
        setDataApi(result.data);
    };
    fetchData();
    }, []);

    console.log(apiData);

    return(
        <h1>.</h1>
    )
}
</code>```

The api.js looks like this:

```<code>import axios from 'axios';

const api = axios.get({
    baseURL: 'https://api.covid19api.com',
})

export default api;
</code>```

I'm facing the following errors:

```<code>Uncaught (in promise) TypeError: _assets_API__WEBPACK_IMPORTED_MODULE_1__.default.get is not a function
    at fetchData (Chart.js:10)
    at Chart.js:13
    at commitHookEffectListMount (react-dom.development.js:19731)
    at commitPassiveHookEffects (react-dom.development.js:19769)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at flushPassiveEffectsImpl (react-dom.development.js:22853)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushPassiveEffects (react-dom.development.js:22820)
    at react-dom.development.js:22699
    at workLoop (scheduler.development.js:597)
    at flushWork (scheduler.development.js:552)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)
</code>```

I've tried to clear cache and used yarn install to make sure I had everything in the project, but didn't worked. I'm also receiving an empty array in the console.log(apiData), but I'm afraid it's related to the error, since I tried with other APIs and faced the same response.

答:
It is a simple mistake =)

api.js:

```<code>const api = axios.get({
    baseURL: 'https://api.covid19api.com',
})
</code>```

In the above code, where you define your API, you should use axios.create instead of axios.get.

At the moment, if you look carefully, in your React component you're basically calling axios.get().get() which doesn't make sense.

Body:
I'm trying to make a simple get request using axios in my react component using the following function:

import React from 'react';
import api from '../../assets/API';
import {useEffect, useState} from 'react';

export default function Chart() {
    const [apiData, setDataApi] = useState({ elements: [] });

    useEffect(() => {
    const fetchData = async () => {
        const result = await api.get('/countries');
        setDataApi(result.data);
    };
    fetchData();
    }, []);

    console.log(apiData);

    return(

.

    )
}

The api.js looks like this:

import axios from 'axios';

const api = axios.get({
    baseURL: 'https://api.covid19api.com',
})

export default api;

I'm facing the following errors:

Uncaught (in promise) TypeError: _assets_API__WEBPACK_IMPORTED_MODULE_1__.default.get is not a function
    at fetchData (Chart.js:10)
    at Chart.js:13
    at commitHookEffectListMount (react-dom.development.js:19731)
    at commitPassiveHookEffects (react-dom.development.js:19769)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at flushPassiveEffectsImpl (react-dom.development.js:22853)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushPassiveEffects (react-dom.development.js:22820)
    at react-dom.development.js:22699
    at workLoop (scheduler.development.js:597)
    at flushWork (scheduler.development.js:552)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)

I've tried to clear cache and used yarn install to make sure I had everything in the project, but didn't worked. I'm also receiving an empty array in the console.log(apiData), but I'm afraid it's related to the error, since I tried with other APIs and faced the same response.

Body:
It is a simple mistake =)

api.js:

const api = axios.get({
    baseURL: 'https://api.covid19api.com',
})

In the above code, where you define your API, you should use axios.create instead of axios.get.

At the moment, if you look carefully, in your React component you're basically calling axios.get().get() which doesn't make sense.


问:
MySQL query slow querying table on primary key
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

```<code>+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
</code>```

create table:

```<code>CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

答:
Could you post your CREATE TABLE statement as well as the output of EXPLAIN select data from table where id=XXX?  How is the io wait on the system?

My best guess is that you're IO bound and because the rows aren't all the same size, it's having to search through the data.  You have enough memory that it should be able to keep the data cached.  This link describes some low level profiling in MySQL that might be helpful.

http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html

Body:
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+

create table:

CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8