答:
try this instead :</p>

```<code>.sidebar .menu li a .icon i:hover {
     color:red;
}
</code>```

Body:
While I hover over an  tag area I want to switch the icon's color but for some reason it remains the same. I was able to get the wanted result only if I pinpointed the icon directly
.sidebar .menu li a .icon:hover{background: #ecedf2;color: #3d5654;} but I have to hover exactly over the icon. What I wanted to achieve is to change the icon's color while a hover over the  tag area. Let me know if I am doing something wrong.

HTML

      Dashboard

CSS

* {
  list-style: none;
  text-decoration: none;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Jost', sans-serif;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  height: 100vh;
  width: 100wh;
  padding: 0;
  margin: 0;
  font-size: 1rem;
  font-weight: 300;
  line-height: 1.6;
  display: grid;
  grid-template-columns: auto 8fr;
  grid-template-rows: 80px auto 50px;
  grid-template-areas:
    'header header'
    'sidebar main'
    'footer footer';
}

.sidebar {
  grid-area: sidebar;
  width: 260px;
  background: #2c343b;
  height: 100%;
}

.sidebar .menu {
  padding-right: 30px;
  padding-left: 20px;
  margin: 0;
  overflow: auto;
  transition: all 0.5s;
}

.sidebar .menu li a {
  color: #ecedf2;
  display: block;
  width: 100%;
  line-height: 60px;
  text-decoration: none;
  padding: 15px;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-bottom: 1px;
  transition: 0.5s;
}

.sidebar .menu li a .icon {
  color: #ecedf2;
  width: 25px;
  display: inline-block;
}

.sidebar .menu li a:hover,
.sidebar .menu li a.active {
  background: #ecedf2;
  color: #3d5654;
}

Body:
try this instead :

.sidebar .menu li a .icon i:hover {
     color:red;
}


来源: stackexchange

问:
How to change json encode to array string
I have a task to solve how to change JSON encode to array string,
look at my code below: I have

```<code>["11:00"]["09:00"]["01:00"]["12:00"]["11:00"]["10:00"]["01:00"]["00:00"]["23:00"]["22:00"]
</code>```

how to change it to become

```<code>["11:00","09:00","01:00","11:00","10:00","01:00","00:00","23:00","22:00"]
</code>```

My stats.php looks like this:

```<code>out .=  '         <div class="col-lg-5 col-md-5 col-sm-5 col-lg-offset-1 col-md-offset-1 col-sm-offset-1" style="height: 300px">';
        $out .=  '          <div class="chartjs-size-monitor">';
        $out .=  '              <div class="chartjs-size-monitor-expand">';
        $out .=  '                  <div class=""></div>';
        $out .=  '              </div>';
        $out .=  '              <div class="chartjs-size-monitor-shrink">';
        $out .=  '                  <div class=""></div>';
        $out .=  '              </div>';
        $out .=  '         </div>';
        $out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
        $out .=  '        </div>';

$graph_query = mssql_query("SELECT TOP 100 Convert(nvarchar,dtDate,108) AS Date, serial, nAverageUser, nMaxUser FROM tbl_ServerUser_Log ORDER BY serial DESC");

            $i = 1;
            while ($graph = mssql_fetch_array($graph_query)) {
                $graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
                $graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
                $serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
                $serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
                $date = date('H:i', strtotime($graph['Date']));
                $convert = json_encode(str_split($date, 5));
                // $convert = str_replace('][','',$convert);

                echo $convert;

            }
</code>```

I want to show a chart and send the value in HTML.
The HTML shall look like this:

```<code><script type="text/javascript">
    var ctx = document.getElementById('myChart2').getContext('2d');
    var myChart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'], //Jamnya
            datasets: [{
                backgroundColor: 'rgba(232,72,163,0.2)',
                borderColor: '#e848a3',
                label: '29 May 2020',
                data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
                fill: true,
                pointRadius: 5,
                pointHoverRadius: 10,
                showLine: true
            }]
        }, options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: true,
                text: 'Total Online Yesterday',
                position: 'top',
                fontSize: 15,
                fontStyle: 'bold'
            },
            legend: {
                display: false
            },
            elements: {
                point: {
                    pointStyle: 'circle'
                }
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TIME'
                    },
                    ticks: {
                        major: {
                            fontStyle: 'bold',
                            fontColor: '#FF0000'
                        }
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TOTAL ONLINE'
                    }
                }]
            },
            tooltips:{
                callbacks: {
                    title: function(tooltipItem, data) {
                      return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
                    },
                    label: function(tooltipItem, data) {
                      return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                    },
                },
                titleFontSize: 15,
                bodyFontSize: 15,
                displayColors: false
            }
        }
    });
</script>
</code>```

I just want to show my chart from manual value to query value that I catch from an SQL server.

Thanks in advance for answering my question.

答:
Don't echo JSON every time through the loop. Put the times in a single array, and echo the JSON at the end.</p>

```<code>$dates = [];
while ($graph = mssql_fetch_array($graph_query)) {
    $graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
    $graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
    $serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
    $serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
    $date = date('H:i', strtotime($graph['Date']));
    $dates[] = $date;
    echo $convert;
}
echo json_encode($dates);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a task to solve how to change JSON encode to array string,
look at my code below: I have

["11:00"]["09:00"]["01:00"]["12:00"]["11:00"]["10:00"]["01:00"]["00:00"]["23:00"]["22:00"]

how to change it to become

["11:00","09:00","01:00","11:00","10:00","01:00","00:00","23:00","22:00"]

My stats.php looks like this:

out .=  '
';
        $out .=  '
';
        $out .=  '
';
        $out .=  '

';
        $out .=  '
';
        $out .=  '
';
        $out .=  '

';
        $out .=  '
';
        $out .=  '
';
        $out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
        $out .=  '
';

$graph_query = mssql_query("SELECT TOP 100 Convert(nvarchar,dtDate,108) AS Date, serial, nAverageUser, nMaxUser FROM tbl_ServerUser_Log ORDER BY serial DESC");

            $i = 1;
            while ($graph = mssql_fetch_array($graph_query)) {
                $graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
                $graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
                $serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
                $serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
                $date = date('H:i', strtotime($graph['Date']));
                $convert = json_encode(str_split($date, 5));
                // $convert = str_replace('][','',$convert);

                echo $convert;

            }

I want to show a chart and send the value in HTML.
The HTML shall look like this:

I just want to show my chart from manual value to query value that I catch from an SQL server.

Thanks in advance for answering my question.

Body:
Don't echo JSON every time through the loop. Put the times in a single array, and echo the JSON at the end.

$dates = [];
while ($graph = mssql_fetch_array($graph_query)) {
    $graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
    $graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
    $serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
    $serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
    $date = date('H:i', strtotime($graph['Date']));
    $dates[] = $date;
    echo $convert;
}
echo json_encode($dates);


问:
scroll behaviour smooth not working at all
I am wondering why my scroll smooth isn't working at all. I am not too sure why? I thought adding  overflow-y: scroll; scroll-behavior: smooth; will help but its not working. Here is my code:

#container{
    overflow-y: scroll;
    scroll-behavior: smooth;
}
.topTab{
bottom: 0;
position: fixed;
font-size: 25px;
color: white;
}
.pg{
  font-size: 100px;
  height: 100vh;
  background-color: blue;
  text-align: center;
}

a{
 color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "topTab">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</div>

<div id = "container">
<div id = "1" class= "pg">1</div>
<div id = "2" class = "pg">2</div>
<div id = "3" class = "pg">3</div>
</div></code>```

答:
Try this one...

html {
  scroll-behavior: smooth;
}

#container{
    overflow-y: scroll;
}
.topTab{
bottom: 0;
position: fixed;
font-size: 25px;
color: white;
}
.pg{
  font-size: 100px;
  height: 100vh;
  background-color: blue;
  text-align: center;
}

a{
 color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "topTab">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</div>

<div id = "container">
<div id = "1" class= "pg">1</div>
<div id = "2" class = "pg">2</div>
<div id = "3" class = "pg">3</div>
</div></code>```

Body:
I am wondering why my scroll smooth isn't working at all. I am not too sure why? I thought adding  overflow-y: scroll; scroll-behavior: smooth; will help but its not working. Here is my code:

#container{
    overflow-y: scroll;
    scroll-behavior: smooth;
}
.topTab{
bottom: 0;
position: fixed;
font-size: 25px;
color: white;
}
.pg{
  font-size: 100px;
  height: 100vh;
  background-color: blue;
  text-align: center;
}

a{
 color: white;
}

1

2

3

1

2

3

Body:
Try this one...

html {
  scroll-behavior: smooth;
}

#container{
    overflow-y: scroll;
}
.topTab{
bottom: 0;
position: fixed;
font-size: 25px;
color: white;
}
.pg{
  font-size: 100px;
  height: 100vh;
  background-color: blue;
  text-align: center;
}

a{
 color: white;
}

<div class = "topTab">
  <li><a href="#1">1</a></li>
  <li><a href="#2">2</a></li>
  <li><a href="#3">3</a></li>
</div>

<div id = "container">
<div id = "1" class= "pg">1</div>
<div id = "2" class = "pg">2</div>
<div id = "3" class = "pg">3</div>
</div>


问:
Is there any way I can output the variable name instead of the value? [JAVA]
for example, I have a list of integer variables

```<code>int CLUTCH_CASE = 8;
int CS20 = 6;
int DANGER_ZONE_CASE = 6;
int TOTAL_CASE = 0;
</code>```

I have an array:

```<code>int CaseValue[] = {CS20, CLUTCH_CASE, DANGER_ZONE_CASE};
</code>```

and I output the value of total cases, which is going to be:

```<code>for (int counter=0;counter<CaseValue.length;counter++) {
    TOTAL_CASE += CaseValue[counter];
}
System.out.println("You have "+CaseValue.length+" CSGO Cases");
System.out.println("You have a total of "+TOTAL_CASE+" CSGO Cases:");
</code>```

Output:

```<code>You have 3 CSGO Cases
You have a total of 20 CSGO Cases:
</code>```

yet I also want to output the name.

Example:
(CASENAME are just placeholders for this example. I wanted to use CaseValue[].NAME even that does not exist since it's an example)

```<code>for (int counter2=0;counter2<CaseValue.length;counter2++) {
    System.out.println(CASENAME+": "+CaseValue[counter2]);
}
</code>```

My expected and wanted output to be:

```<code>CLUTCH_CASE: 8
CS20: 6
DANGER_ZONE_CASE: 6
</code>```

Is there any way to output the name of the integer variable?

答:
You could use a HashMap.

enum CaseType {
   CLUTCH_CASE,
   CS20,
   DANGER_ZONE_CASE;
}
Map<CaseType, Integer> map = new HashMap<>(3);
map.put(CaseType.CLUTCH_CASE, 8);
map.put(CaseType.CS20, 6);
map.put(CaseType.DANGER_ZONE_CASE, 6);
map.forEach((key, value) -> System.out.println(key.name() + ": " + value));
```

Body:
for example, I have a list of integer variables

int CLUTCH_CASE = 8;
int CS20 = 6;
int DANGER_ZONE_CASE = 6;
int TOTAL_CASE = 0;

I have an array:

int CaseValue[] = {CS20, CLUTCH_CASE, DANGER_ZONE_CASE};

and I output the value of total cases, which is going to be:

for (int counter=0;counter<CaseValue.length;counter++) {
    TOTAL_CASE += CaseValue[counter];
}
System.out.println("You have "+CaseValue.length+" CSGO Cases");
System.out.println("You have a total of "+TOTAL_CASE+" CSGO Cases:");

Output:

You have 3 CSGO Cases
You have a total of 20 CSGO Cases:

yet I also want to output the name.

Example:
(CASENAME are just placeholders for this example. I wanted to use CaseValue[].NAME even that does not exist since it's an example)

for (int counter2=0;counter2<CaseValue.length;counter2++) {
    System.out.println(CASENAME+": "+CaseValue[counter2]);
}

My expected and wanted output to be:

CLUTCH_CASE: 8
CS20: 6
DANGER_ZONE_CASE: 6

Is there any way to output the name of the integer variable?


问:
Wordpress & Zend Framework application working togheter?
I have in my site a Wordpress running in the root directory, ie: mysite.com/

And I need to create a ZF Application, and host it under a subdirectory of my hosting, ie: mysite.com/backend

I did under my root directory:

% zf create project backend

It created the "backend" directory under my root, with all the project inside.

Under my root directory I have this .htaccess file:

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

Under webroot/backend/public I have this .htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</code>```

I'm using ZF 1.11

What I can't figure how must I configure is the .htaccess files to get this zf app working under the subdirectory.

Regards!

答:
I had to put this .htacess inside mysite.com/backend

```<code>RewriteEngine On
RewriteRule !\.(csv|js|gif|jpg|png|css|txt)$ public/index.php [L]
</code>```

And then in my Bootstrap.php this:

```<code>public function run() {
        $front   = $this->getResource('FrontController');
        $front->setBaseUrl('/backend');
}
</code>```

So Zend can route the requests in the right way.

ContentLicense: CC BY-SA 3.0

Body:
I have in my site a Wordpress running in the root directory, ie: mysite.com/

And I need to create a ZF Application, and host it under a subdirectory of my hosting, ie: mysite.com/backend

I did under my root directory:

% zf create project backend

It created the "backend" directory under my root, with all the project inside.

Under my root directory I have this .htaccess file:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Under webroot/backend/public I have this .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

I'm using ZF 1.11

What I can't figure how must I configure is the .htaccess files to get this zf app working under the subdirectory.

Regards!

Body:
I had to put this .htacess inside mysite.com/backend

RewriteEngine On
RewriteRule !\.(csv|js|gif|jpg|png|css|txt)$ public/index.php [L]

And then in my Bootstrap.php this:

public function run() {
        $front   = $this->getResource('FrontController');
        $front->setBaseUrl('/backend');
}

So Zend can route the requests in the right way.


问:
How to inject services in a controller inside a reusable Razor Class Library
I am using a Razor Class Library for making a reusable complex View (which includes its controller and several View Components) that can be used across several ASP.NET Core MVC projects. The problem is that the controller use dependency injection (a custom service called "GatewayProxy" and string localization). What is the correct way to inject services into a controller inside a RCL?

Here is the structure of my RCL:

Here is the exception:

答:
You can inject from load assemblies.
my code

ISturtupInitializers.cs

```<code>public interface ISturtupInitializers {
    void Compose(IServiceCollection serviceCollection);
}
</code>```

TypeLoader.cs

```<code>public static readonly Lazy<HashSet<Assembly>> AllAssemblies = new Lazy<HashSet<Assembly>>(() => {
    var bin_folder = Assembly.GetExecutingAssembly().GetFileInfo().Directory.FullName;
    var bin_assembly_files = Directory.GetFiles(bin_folder, "*.dll", SearchOption.TopDirectoryOnly).Where(x => !SystemAssemblies.Any(xs => x.IndexOf(xs, StringComparison.CurrentCultureIgnoreCase) >= 0)).ToList();
    var assemblies = new HashSet<Assembly>();
    foreach (var a in bin_assembly_files)
    {
        try {
            var assName = AssemblyName.GetAssemblyName(a);
            var ass = Assembly.Load(assName);
            assemblies.Add(ass);
        } catch (SecurityException e) {
            //ignore
        } catch (FileNotFoundException e) {
            //ignore
        } catch (BadImageFormatException e) {
            //ignore
        }
        catch (Exception e) {
            throw;
        }
    }

    return assemblies;
});

public static string[] SystemAssemblies = new[] {
    "Microsoft.",
    "System.",
    "Newtonsoft."
};
public static FileInfo GetFileInfo(this Assembly assembly)
{
    var uri = new Uri(assembly.CodeBase);
    var path = uri.LocalPath;
    return new FileInfo(path);
}
</code>```

Composer.cs

```<code>public class Composer {
    private static readonly Lazy<HashSet<Type>> _sturtup_initializers = new Lazy<HashSet<Type>>(() => {
        var aseemblies = TypeLoader.AllAssemblies.Value.SelectMany(x=>GetAllTypesInAssembly(x, typeof(ISturtupInitializers)));
        var result = new HashSet<Type>();
        foreach (var item in aseemblies) {
            result.Add(item);
        }

        return result;
    });

    public static void Compose(IServiceCollection services) {
        var composers = _sturtup_initializers.Value;

        foreach (var compose in composers) {
            public static void Compose(IServiceCollection services, IConfiguration configuration) {
        var composers = _sturtup_initializers.Value;

        var provider = services.BuildServiceProvider();

        foreach (var compose in composers) {
            ((IStartupInitializers) ActivatorUtilities.CreateInstance(provider, compose)).Compose(services, configuration);
        }
    }
        }
    }

    private static IEnumerable<Type> GetAllTypesInAssembly(Assembly assembly, Type implementInterface) {
        var types = assembly.GetTypes();
        return types.Where(x => x.GetInterfaces().Any(i => i == implementInterface));
    }
}
</code>```

MyStartup.cs

```<code>public class ServiceCollectionExtensions : ISturtupInitializers
{
    public void Compose(IServiceCollection serviceCollection) {
        /** YOUR CODE **/
    }
}
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services) {
    /** YOUR CODE **/
    Composer.Compose(services);
}
</code>```

Body:
You can inject from load assemblies.
my code

ISturtupInitializers.cs

public interface ISturtupInitializers {
    void Compose(IServiceCollection serviceCollection);
}

TypeLoader.cs

public static readonly Lazy<HashSet<Assembly>> AllAssemblies = new Lazy<HashSet<Assembly>>(() => {
    var bin_folder = Assembly.GetExecutingAssembly().GetFileInfo().Directory.FullName;
    var bin_assembly_files = Directory.GetFiles(bin_folder, "*.dll", SearchOption.TopDirectoryOnly).Where(x => !SystemAssemblies.Any(xs => x.IndexOf(xs, StringComparison.CurrentCultureIgnoreCase) >= 0)).ToList();
    var assemblies = new HashSet<Assembly>();
    foreach (var a in bin_assembly_files)
    {
        try {
            var assName = AssemblyName.GetAssemblyName(a);
            var ass = Assembly.Load(assName);
            assemblies.Add(ass);
        } catch (SecurityException e) {
            //ignore
        } catch (FileNotFoundException e) {
            //ignore
        } catch (BadImageFormatException e) {
            //ignore
        }
        catch (Exception e) {
            throw;
        }
    }

    return assemblies;
});

public static string[] SystemAssemblies = new[] {
    "Microsoft.",
    "System.",
    "Newtonsoft."
};
public static FileInfo GetFileInfo(this Assembly assembly)
{
    var uri = new Uri(assembly.CodeBase);
    var path = uri.LocalPath;
    return new FileInfo(path);
}

Composer.cs

public class Composer {
    private static readonly Lazy<HashSet<Type>> _sturtup_initializers = new Lazy<HashSet<Type>>(() => {
        var aseemblies = TypeLoader.AllAssemblies.Value.SelectMany(x=>GetAllTypesInAssembly(x, typeof(ISturtupInitializers)));
        var result = new HashSet<Type>();
        foreach (var item in aseemblies) {
            result.Add(item);
        }

        return result;
    });

    public static void Compose(IServiceCollection services) {
        var composers = _sturtup_initializers.Value;

        foreach (var compose in composers) {
            public static void Compose(IServiceCollection services, IConfiguration configuration) {
        var composers = _sturtup_initializers.Value;

        var provider = services.BuildServiceProvider();

        foreach (var compose in composers) {
            ((IStartupInitializers) ActivatorUtilities.CreateInstance(provider, compose)).Compose(services, configuration);
        }
    }
        }
    }

    private static IEnumerable<Type> GetAllTypesInAssembly(Assembly assembly, Type implementInterface) {
        var types = assembly.GetTypes();
        return types.Where(x => x.GetInterfaces().Any(i => i == implementInterface));
    }
}

MyStartup.cs

public class ServiceCollectionExtensions : ISturtupInitializers
{
    public void Compose(IServiceCollection serviceCollection) {
        /** YOUR CODE **/
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services) {
    /** YOUR CODE **/
    Composer.Compose(services);
}


问:
How to send data from Jetson nano to Arduino?
I'm trying to connect NVIDIA Jetson Nano through serial communication with Arduino Uno via USB, so when my camera, connected to the jetson nano, detect an object the LED turn on, but it's not working. I think my arduino doesn't receive any data from the jetson.
If someone can help me with suggestions, or the answer that would be great. Here is my code for arduino and for jetson nano:

Arduino:

```<code>char data;
int LED=13;
void setup() {

Serial.begin(9600);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);

}

void loop() {

 if (Serial.available() ) {
  data= Serial.read();
 }
 if(data == 'Y' || data == 'y') {
  digitalWrite(LED, HIGH);
    delay(5000);
 }
}
</code>```

Jetson Nano:

```<code>#!/usr/bin/python
import jetson.inference
import jetson.utils
import time
import serial
import argparse
import sys

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(port='/dev/ttyUSB0',baudrate=9600)

# parse the command line
parser = argparse.ArgumentParser(description="Locate objects in a live camera stream using an object detection DNN.", formatter_class=argparse.RawTextHelpFormatter,epilog=jetson.inference.detectNet.Usage())
parser.add_argument("--network", type=str, default="ssd-mobilenet-v2", help="pre-trained model to load (see below for options)")
parser.add_argument("--overlay", type=str, default="box,labels,conf", help="detection overlay flags (e.g. --overlay=box,labels,conf)\nvalid combinations are:  'box', 'labels', 'conf', 'none'")
parser.add_argument("--threshold", type=float, default=0.5, help="minimum detection threshold to use")
parser.add_argument("--camera", type=str, default="0", help="index of the MIPI CSI camera to use (e.g. CSI camera 0)\nor for VL42 cameras, the /dev/video device to use.\nby default, MIPI CSI camera 0 will be used.")
parser.add_argument("--width", type=int, default=1280, help="desired width of camera stream (default is 1280 pixels)")
parser.add_argument("--height", type=int, default=720, help="desired height of camera stream (default is 720 pixels)")

try:
    opt = parser.parse_known_args()[0]
except:
    print("")
    parser.print_help()
    sys.exit(0)

 # load the object detection network
 net = jetson.inference.detectNet(opt.network, sys.argv, opt.threshold)

 # create the camera and display
 camera = jetson.utils.gstCamera(opt.width, opt.height, opt.camera)
 display = jetson.utils.glDisplay()

# process frames until user exits
while display.IsOpen():
# capture the image
img, width, height = camera.CaptureRGBA()

# detect objects in the image (with overlay)
detections = net.Detect(img, width, height, opt.overlay)

# print the detections
print("detected {:d} objects in image".format(len(detections)))

for detection in detections:
    print(detection)

# render the image
display.RenderOnce(img, width, height)

# update the title bar
display.SetTitle("{:s} | Network {:.0f} FPS".format(opt.network, net.GetNetworkFPS()))

# print out performance info
net.PrintProfilerTimes()

if (detections > 0):

    ser = serial.Serial(port='/dev/ttyUSB0',baudrate=9600)
    time.sleep(2)
    print(ser)
    ser.write('Y')
</code>```

答:
as alan.elkin mentioned before. You need to point out the problem. Nevertheless I would debug your problem as follows:

check only the  serial communication between both devices. I would advice to remove any other logic in your python script. ( Object detection with Camera)

review your connection setup. Common problems are : no common GND for both devices, different logic level( most of Arduinos operate at 5V and Jetson Nano at 3.3V)

review your serial communication configuration, Baudarte, parity bit.. etc

If you have an Oscilloscope, check the Pins sending data . You should see the signal toggling

hope this gives you a hint how to identfy your problem

Body:
I'm trying to connect NVIDIA Jetson Nano through serial communication with Arduino Uno via USB, so when my camera, connected to the jetson nano, detect an object the LED turn on, but it's not working. I think my arduino doesn't receive any data from the jetson.
If someone can help me with suggestions, or the answer that would be great. Here is my code for arduino and for jetson nano:

Arduino:

char data;
int LED=13;
void setup() {

Serial.begin(9600);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);

}

void loop() {

 if (Serial.available() ) {
  data= Serial.read();
 }
 if(data == 'Y' || data == 'y') {
  digitalWrite(LED, HIGH);
    delay(5000);
 }
}

Jetson Nano:

#!/usr/bin/python
import jetson.inference
import jetson.utils
import time
import serial
import argparse
import sys

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(port='/dev/ttyUSB0',baudrate=9600)

# parse the command line
parser = argparse.ArgumentParser(description="Locate objects in a live camera stream using an object detection DNN.", formatter_class=argparse.RawTextHelpFormatter,epilog=jetson.inference.detectNet.Usage())
parser.add_argument("--network", type=str, default="ssd-mobilenet-v2", help="pre-trained model to load (see below for options)")
parser.add_argument("--overlay", type=str, default="box,labels,conf", help="detection overlay flags (e.g. --overlay=box,labels,conf)\nvalid combinations are:  'box', 'labels', 'conf', 'none'")
parser.add_argument("--threshold", type=float, default=0.5, help="minimum detection threshold to use")
parser.add_argument("--camera", type=str, default="0", help="index of the MIPI CSI camera to use (e.g. CSI camera 0)\nor for VL42 cameras, the /dev/video device to use.\nby default, MIPI CSI camera 0 will be used.")
parser.add_argument("--width", type=int, default=1280, help="desired width of camera stream (default is 1280 pixels)")
parser.add_argument("--height", type=int, default=720, help="desired height of camera stream (default is 720 pixels)")

try:
    opt = parser.parse_known_args()[0]
except:
    print("")
    parser.print_help()
    sys.exit(0)

 # load the object detection network
 net = jetson.inference.detectNet(opt.network, sys.argv, opt.threshold)

 # create the camera and display
 camera = jetson.utils.gstCamera(opt.width, opt.height, opt.camera)
 display = jetson.utils.glDisplay()

# process frames until user exits
while display.IsOpen():
# capture the image
img, width, height = camera.CaptureRGBA()

# detect objects in the image (with overlay)
detections = net.Detect(img, width, height, opt.overlay)

# print the detections
print("detected {:d} objects in image".format(len(detections)))

for detection in detections:
    print(detection)

# render the image
display.RenderOnce(img, width, height)

# update the title bar
display.SetTitle("{:s} | Network {:.0f} FPS".format(opt.network, net.GetNetworkFPS()))

# print out performance info
net.PrintProfilerTimes()

if (detections > 0):

    ser = serial.Serial(port='/dev/ttyUSB0',baudrate=9600)
    time.sleep(2)
    print(ser)
    ser.write('Y')


问:
How do I join multiple texts together on selenium?
I got this below error. I know that i have to join the Strings together but i don't know how.

TypeError: sequence item 0: expected str instance, WebElement found

```<code>import random
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("user-data-dir=C:/Users/Guest/AppData/Local/Google/Chrome/User Data")
driver = webdriver.Chrome(executable_path="C:/Users/Guest/Desktop/chromedriver.exe", chrome_options=options)

copy = driver.find_elements_by_xpath("//p[contains(@class,'ui_qtext_para u-ltr u-text-align--start')]")
for text in copy:
    driver.find_element_by_xpath("//div[@placeholder='']/div").send_keys(copy)
</code>```

答:
Please update your code as shown below.</p>

```<code> for text in copy:
    driver.find_element_by_xpath("//div[@placeholder='Traducir la respuesta']/div").send_keys(text.text)
</code>```

Body:
I got this below error. I know that i have to join the Strings together but i don't know how.

TypeError: sequence item 0: expected str instance, WebElement found

import random
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("user-data-dir=C:/Users/Guest/AppData/Local/Google/Chrome/User Data")
driver = webdriver.Chrome(executable_path="C:/Users/Guest/Desktop/chromedriver.exe", chrome_options=options)

copy = driver.find_elements_by_xpath("//p[contains(@class,'ui_qtext_para u-ltr u-text-align--start')]")
for text in copy:
    driver.find_element_by_xpath("//div[@placeholder='']/div").send_keys(copy)

Body:
Please update your code as shown below.

 for text in copy:
    driver.find_element_by_xpath("//div[@placeholder='Traducir la respuesta']/div").send_keys(text.text)


问:
Get a line of space-separated integers from stdio without knowing how much they are (C++)
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

```<code>int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];
</code>```

In case I don't have 'n', how would I achieve the same thing?

答:
When you will be given the value of n. You can follow any of the following two steps:

Step: 1

```<code>#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n;
    cin >> n; // Input n
    vector<int>vv(n); // It will declare a vector(similar to an array) of size n
    for(int i = 0; i < n; i++)
    {
        cin >> vv[i];
    }
    return 0;
}
</code>```

Step: 2

```<code>#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n, number;
    cin >> n; // Input n
    vector<int>vv; // It will declare an empty vector
    for(int i = 0; i < n; i++)
    {
        cin >> number; // Take a number as input
        vv.push_back(number); // Put the input to the last of the vector
    }
    return 0;
}
</code>```

When you will not be given the value of n:

```<code>#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int number;
    vector<int>vv; // It will declare an empty vector.
    while(cin >> number)
    {
        vv.push_back(number); // Push(put) the input to the back(end/last) of the vector
    }

    /* In case of reading input from a file,
    the loop will continue until the end of the file.

    When you'll try it from console, you need to enter
    end-of-file command from keyboard.*/

    return 0;
}
</code>```

Body:
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];

In case I don't have 'n', how would I achieve the same thing?

Body:
When you will be given the value of n. You can follow any of the following two steps:

Step: 1

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n;
    cin >> n; // Input n
    vector<int>vv(n); // It will declare a vector(similar to an array) of size n
    for(int i = 0; i < n; i++)
    {
        cin >> vv[i];
    }
    return 0;
}

Step: 2

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n, number;
    cin >> n; // Input n
    vector<int>vv; // It will declare an empty vector
    for(int i = 0; i < n; i++)
    {
        cin >> number; // Take a number as input
        vv.push_back(number); // Put the input to the last of the vector
    }
    return 0;
}

When you will not be given the value of n:

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int number;
    vector<int>vv; // It will declare an empty vector.
    while(cin >> number)
    {
        vv.push_back(number); // Push(put) the input to the back(end/last) of the vector
    }

    /* In case of reading input from a file,
    the loop will continue until the end of the file.

    When you'll try it from console, you need to enter
    end-of-file command from keyboard.*/

    return 0;
}


问:
Igor Pro 8, functions for comparing strings
Hi I'm pretty new to using Igor Pro. I'm looking for some help on writing a procedure for a task.

I have 4 waves, two are text waves and two are numeric waves(one of which has no data yet). I need to write a function that will compare the two text waves and if they are equal, have igor pull data from one of the numeric waves and put it in the correct point to match the text wave it's coupled with.

To make it visually conceptually

```<code>twave1                           twave2

nwave1                           nwave2
</code>```

twave1 is a list of all isotopes up to neptunium but they're not in order, and nwave1 is their corresponding mass values. (both on table1)

twave2 is the same list of isotopes but ordered properly (i.e. 1H, 2H, 3H, 4H...3He, 4He...ect) and nwave2 is empty (both on table2)

so the goal is to create a function that will sort through twave1 and twave2, and if they match, pull the data from nwave1 into nwave2, so that the masses match with the correct isotopes on table2. So table2 will have the correctly ordered isotopes and now the mass data as well, in the correct places.

Any help would be greatly appreciated; this is where I've gotten so far

```<code>function assignMEf()
    wave ME, ME_FRIB
    wave isotope_FRIB, isotope
    variable len = numpnts(ME)
    variable i, j
    variable ME_current, iso_current

    for(i=0; i<len; i+=1)
     ME_current = ME[i]
     iso_current = isotope[i]
   for(j=0; j<4254; j+=1)
    if(iso_current == isotope_frib[j])
        ME_frib = ME[i]
    endif
   endfor
  endfor

end
</code>```

答:
If I understood correctly, the two waves you want at the end are isotope and ME. Your code was close to working, however you need to tell Igor when you declare a text wave that it is a text wave, by using the /t flag. I simplified the code a bit more:

```<code>function assignMEf()
    wave ME, ME_FRIB
    wave/t isotope, isotope_FRIB
    variable len = numpnts(ME)

    variable i, j

    for(i = 0; i < len; i += 1)
        for(j = 0; j < len; j += 1)
            if(stringmatch(isotope[i],isotope_frib[j]))
                ME[i] = ME_FRIB[j]
            endif
        endfor
    endfor
end
</code>```

This code is not very robust but works for what you'd like to do.

To test the code, here is my MWE:

```<code>•Make/O/N=(10) ME_FRIB = p
•Make/O/N=(10) ME = NaN
•Make/O/N=(10)/T isotope_FRIB = "iso" + num2str(10 - p)
•Duplicate/O isotope_FRIB,isotope
•Sort isotope,isotope
•Edit isotope_FRIB,ME_FRIB,isotope,ME
•assignmef()
</code>```

Body:
Hi I'm pretty new to using Igor Pro. I'm looking for some help on writing a procedure for a task.

I have 4 waves, two are text waves and two are numeric waves(one of which has no data yet). I need to write a function that will compare the two text waves and if they are equal, have igor pull data from one of the numeric waves and put it in the correct point to match the text wave it's coupled with.

To make it visually conceptually

twave1                           twave2

nwave1                           nwave2

twave1 is a list of all isotopes up to neptunium but they're not in order, and nwave1 is their corresponding mass values. (both on table1)

twave2 is the same list of isotopes but ordered properly (i.e. 1H, 2H, 3H, 4H...3He, 4He...ect) and nwave2 is empty (both on table2)

so the goal is to create a function that will sort through twave1 and twave2, and if they match, pull the data from nwave1 into nwave2, so that the masses match with the correct isotopes on table2. So table2 will have the correctly ordered isotopes and now the mass data as well, in the correct places.

Any help would be greatly appreciated; this is where I've gotten so far

function assignMEf()
    wave ME, ME_FRIB
    wave isotope_FRIB, isotope
    variable len = numpnts(ME)
    variable i, j
    variable ME_current, iso_current

    for(i=0; i<len; i+=1)
     ME_current = ME[i]
     iso_current = isotope[i]
   for(j=0; j<4254; j+=1)
    if(iso_current == isotope_frib[j])
        ME_frib = ME[i]
    endif
   endfor
  endfor

end

Body:
If I understood correctly, the two waves you want at the end are isotope and ME. Your code was close to working, however you need to tell Igor when you declare a text wave that it is a text wave, by using the /t flag. I simplified the code a bit more:

function assignMEf()
    wave ME, ME_FRIB
    wave/t isotope, isotope_FRIB
    variable len = numpnts(ME)

    variable i, j

    for(i = 0; i < len; i += 1)
        for(j = 0; j < len; j += 1)
            if(stringmatch(isotope[i],isotope_frib[j]))
                ME[i] = ME_FRIB[j]
            endif
        endfor
    endfor
end

This code is not very robust but works for what you'd like to do.

To test the code, here is my MWE:

•Make/O/N=(10) ME_FRIB = p
•Make/O/N=(10) ME = NaN
•Make/O/N=(10)/T isotope_FRIB = "iso" + num2str(10 - p)
•Duplicate/O isotope_FRIB,isotope
•Sort isotope,isotope
•Edit isotope_FRIB,ME_FRIB,isotope,ME
•assignmef()


问:
guflow error ACTIVITY_ID_ALREADY_IN_USE aws
Hi in my api I receive 2 patch that send the signal to schedule the same activity, this is because receive diferent content , but when I tried to made this I receive the exeption ACTIVITY_ID_ALREADY_IN_USE and the workflow in aws go to failed status, you know how I cna schedule both activities at the same tiem or if I can schedule on after the other when is one is active, I use guflow  to create workflow and schedule activities</p>

答: I believe error indicates not the activity type, but activity ID is in use. Make sure that you use a different ID when scheduling the second activity.</p>


问:
How to make it so that data doesn't get lost when refreshed in javascript?
I am making a to do list, and to do items are being lost (as expected) when page is refreshed. How do I stop it from clearing the items when the page is refreshed???????

Html:

```<code>        <div class="row">
                <input id="userInput" type="text" placeholder="New item..." maxlength="190"autofocus>
                <button id="enter">Add</button>
        </div>

        <div class="row" id="items">
            <div class="listItems col-12">
                <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
                </ul>
            </div>
        </div>
    </div>
</code>```

JS:

```<code>    function createListElement() {
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        function crossOut() {
            li.classList.toggle("done");
        }
        li.addEventListener("click",crossOut);

        var dBtn = document.createElement("button");
        dBtn.appendChild(document.createTextNode("X"));
        li.appendChild(dBtn);
        dBtn.addEventListener("click", deleteListItem);

        function deleteListItem(){
            li.classList.add("delete");
        }
}

    //enter works
    function addListAfterKeypress(event) {
        if (inputLength() > 0 && event.which ===13) {
            createListElement();
        }
    }

    input.addEventListener("keypress", addListAfterKeypress);
</code>```

答:
It depends on the use case, if it's something like managing date centrally you need to go with database. if it is some minor data user specific you can go with local storage.

To use localStorage in your web applications, there are five methods to choose from:

```<code>setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage
</code>```

setItem()

```<code>window.localStorage.setItem('name', 'Obaseki Nosa');

const person = {
    name: "Obaseki Nosa",
    location: "Lagos",
}
window.localStorage.setItem('user', JSON.stringify(person));
</code>```

getItem()

```<code>window.localStorage.getItem('user');

JSON.parse(window.localStorage.getItem('user'));
</code>```

removeItem()

```<code>window.localStorage.removeItem('name');
</code>```

clear()

```<code>window.localStorage.clear();
</code>```

Note: localStorage is synchronous, with no data protection and limited to 5MB across all major browsers

Body:
I am making a to do list, and to do items are being lost (as expected) when page is refreshed. How do I stop it from clearing the items when the page is refreshed???????

Html:

                <input id="userInput" type="text" placeholder="New item..." maxlength="190"autofocus>
                <button id="enter">Add</button>

JS:

    function createListElement() {
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        function crossOut() {
            li.classList.toggle("done");
        }
        li.addEventListener("click",crossOut);

        var dBtn = document.createElement("button");
        dBtn.appendChild(document.createTextNode("X"));
        li.appendChild(dBtn);
        dBtn.addEventListener("click", deleteListItem);

        function deleteListItem(){
            li.classList.add("delete");
        }
}

    //enter works
    function addListAfterKeypress(event) {
        if (inputLength() > 0 && event.which ===13) {
            createListElement();
        }
    }

    input.addEventListener("keypress", addListAfterKeypress);

Body:
It depends on the use case, if it's something like managing date centrally you need to go with database. if it is some minor data user specific you can go with local storage.

To use localStorage in your web applications, there are five methods to choose from:

setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage

setItem()

window.localStorage.setItem('name', 'Obaseki Nosa');

const person = {
    name: "Obaseki Nosa",
    location: "Lagos",
}
window.localStorage.setItem('user', JSON.stringify(person));

getItem()

window.localStorage.getItem('user');

JSON.parse(window.localStorage.getItem('user'));

removeItem()

window.localStorage.removeItem('name');

clear()

window.localStorage.clear();

Note: localStorage is synchronous, with no data protection and limited to 5MB across all major browsers


问:
Factory for IAsyncEnumerable or IAsyncEnumerator
I'm wondering if there is a way to create either IAsyncEnumerable<T> or IAsyncEnumerator<T> via a Source object, rather like TaskCompletionSource allows one to do for tasks. In particular, TaskCompletionSource can be passed around like any other parameter.

Maybe something like this:

```<code>public class AsyncEnumerables {

    public Task HandlerTask { get; set; }

    public async Task<string> ParentMethod() {
        var source = new AsyncEnumerableSource<int>();
        IAsyncEnumerable asyncEnumerable = source.GetAsyncEnumerable();
        HandlerTask = Task.Run(() => handleAsyncResultsAsTheyHappen(asyncEnumerable));
        int n = await someOtherTask();
        source.YieldReturn(n);
        var r = await ChildMethod(source);
        source.Complete();  // this call would cause the HandlerTask to complete.
        return r;
    }

    private async Task<string> ChildMethod(AsyncEnumerableSource<int> source) {
        source.YieldReturn(5);
        await SomeOtherCall();
        source.YieldReturn(10);
        return "hello";
    }
}
</code>```

With the above code, the handleAsyncResultsAsTheyHappen task would see whatever values got passed into YieldReturn. So it would see the n from the above code, as well as the 5 and the 10 from ChildMethod.

答:
Here is another implementation of the AsyncEnumerableSource class, that doesn't depend on the Rx library. This one depends instead on the Channel<T>, class, which is natively available in the .NET standard libraries. It has identical behavior to the Rx-based implementation.

The class AsyncEnumerableSource can propagate notifications to multiple subscribers. Each subscriber can enumerate these notifications at its own pace. This is possible because each subscription has its own dedicated Channel<T> as underlying storage. The lifetime of a subscription is practically tied to the lifetime of a single await foreach loop. Breaking early from a loop for any reason (including thrown exceptions), ends immediately the subscription.

In technical terms a new subscription is created the first time that the MoveNextAsync method of an IAsyncEnumerator<T> is invoked. Calling the method GetAsyncEnumerable alone doesn't create a subscription, nor calling the GetAsyncEnumerator method does. The subscription ends when the associated IAsyncEnumerator<T> is disposed.

```<code>public class AsyncEnumerableSource<T>
{
    private readonly List<Channel<T>> _channels = new();
    private bool _completed;
    private Exception _exception;

    public async IAsyncEnumerable<T> GetAsyncEnumerable(
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        Channel<T> channel;
        lock (_channels)
        {
            if (_exception != null) throw _exception;
            if (_completed) yield break;
            channel = Channel.CreateUnbounded<T>(
                new() { SingleWriter = true, SingleReader = true });
            _channels.Add(channel);
        }
        try
        {
            await foreach (var item in channel.Reader.ReadAllAsync()
                .WithCancellation(cancellationToken).ConfigureAwait(false))
            {
                yield return item;
                cancellationToken.ThrowIfCancellationRequested();
            }
        }
        finally { lock (_channels) _channels.Remove(channel); }
    }

    public void YieldReturn(T value)
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryWrite(value);
        }
    }

    public void Complete()
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryComplete();
            _completed = true;
        }
    }

    public void Fault(Exception error)
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryComplete(error);
            _completed = true;
            _exception = error;
        }
    }
}
</code>```

The reason for the cancellationToken.ThrowIfCancellationRequested(); is because of this issue: ChannelReader.ReadAllAsync(CancellationToken) not actually cancelled mid-iteration.

Caution: in case you start propagating values with YieldReturn before any consumer has subscribed to the AsyncEnumerableSource, these values are going to be lost. No subscriber is going to observe them. To prevent this scenario you should make sure that all consumers have subscribed before starting the producers. The easiest way to do it is for the consumers to be async methods, with the await foreach being the first await inside the async method:

```<code>// Correct, synchronous subscription
async Task Consume()
{
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
}
Task consumer = Consume();
</code>```

Avoid the temptation to use the Task.Run method, because in this case the subscription will occur asynchronously on a ThreadPool thread, and not synchronously with the creation of the consumer:

```<code>// Wrong, delayed subscription (possibility for unobserved values)
Task consumer = Task.Run(async () =>
{
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
});
</code>```

In case that you don't want to do the subscriptions synchronously, it is possible to offload them to the ThreadPool, and await them to be established before starting the producers:

```<code>// Correct, awaited subscription
Task consumer = await Task.Factory.StartNew(async () =>
{
    HeavySynchronousComputation();
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
}, default, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
</code>```

The Task.Factory.StartNew(async method creates a nested Task<Task>. The outer task represents the subscription, and the inner task represents the consuming loop.

Body:
I'm wondering if there is a way to create either IAsyncEnumerable<T> or IAsyncEnumerator<T> via a Source object, rather like TaskCompletionSource allows one to do for tasks. In particular, TaskCompletionSource can be passed around like any other parameter.

Maybe something like this:

public class AsyncEnumerables {

    public Task HandlerTask { get; set; }

    public async Task<string> ParentMethod() {
        var source = new AsyncEnumerableSource<int>();
        IAsyncEnumerable asyncEnumerable = source.GetAsyncEnumerable();
        HandlerTask = Task.Run(() => handleAsyncResultsAsTheyHappen(asyncEnumerable));
        int n = await someOtherTask();
        source.YieldReturn(n);
        var r = await ChildMethod(source);
        source.Complete();  // this call would cause the HandlerTask to complete.
        return r;
    }

    private async Task<string> ChildMethod(AsyncEnumerableSource<int> source) {
        source.YieldReturn(5);
        await SomeOtherCall();
        source.YieldReturn(10);
        return "hello";
    }
}

With the above code, the handleAsyncResultsAsTheyHappen task would see whatever values got passed into YieldReturn. So it would see the n from the above code, as well as the 5 and the 10 from ChildMethod.

Body:
Here is another implementation of the AsyncEnumerableSource class, that doesn't depend on the Rx library. This one depends instead on the Channel<T>, class, which is natively available in the .NET standard libraries. It has identical behavior to the Rx-based implementation.

The class AsyncEnumerableSource can propagate notifications to multiple subscribers. Each subscriber can enumerate these notifications at its own pace. This is possible because each subscription has its own dedicated Channel<T> as underlying storage. The lifetime of a subscription is practically tied to the lifetime of a single await foreach loop. Breaking early from a loop for any reason (including thrown exceptions), ends immediately the subscription.

In technical terms a new subscription is created the first time that the MoveNextAsync method of an IAsyncEnumerator<T> is invoked. Calling the method GetAsyncEnumerable alone doesn't create a subscription, nor calling the GetAsyncEnumerator method does. The subscription ends when the associated IAsyncEnumerator<T> is disposed.

public class AsyncEnumerableSource<T>
{
    private readonly List<Channel<T>> _channels = new();
    private bool _completed;
    private Exception _exception;

    public async IAsyncEnumerable<T> GetAsyncEnumerable(
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        Channel<T> channel;
        lock (_channels)
        {
            if (_exception != null) throw _exception;
            if (_completed) yield break;
            channel = Channel.CreateUnbounded<T>(
                new() { SingleWriter = true, SingleReader = true });
            _channels.Add(channel);
        }
        try
        {
            await foreach (var item in channel.Reader.ReadAllAsync()
                .WithCancellation(cancellationToken).ConfigureAwait(false))
            {
                yield return item;
                cancellationToken.ThrowIfCancellationRequested();
            }
        }
        finally { lock (_channels) _channels.Remove(channel); }
    }

    public void YieldReturn(T value)
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryWrite(value);
        }
    }

    public void Complete()
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryComplete();
            _completed = true;
        }
    }

    public void Fault(Exception error)
    {
        lock (_channels)
        {
            if (_completed) return;
            foreach (var channel in _channels) channel.Writer.TryComplete(error);
            _completed = true;
            _exception = error;
        }
    }
}

The reason for the cancellationToken.ThrowIfCancellationRequested(); is because of this issue: ChannelReader.ReadAllAsync(CancellationToken) not actually cancelled mid-iteration.

Caution: in case you start propagating values with YieldReturn before any consumer has subscribed to the AsyncEnumerableSource, these values are going to be lost. No subscriber is going to observe them. To prevent this scenario you should make sure that all consumers have subscribed before starting the producers. The easiest way to do it is for the consumers to be async methods, with the await foreach being the first await inside the async method:

// Correct, synchronous subscription
async Task Consume()
{
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
}
Task consumer = Consume();

Avoid the temptation to use the Task.Run method, because in this case the subscription will occur asynchronously on a ThreadPool thread, and not synchronously with the creation of the consumer:

// Wrong, delayed subscription (possibility for unobserved values)
Task consumer = Task.Run(async () =>
{
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
});

In case that you don't want to do the subscriptions synchronously, it is possible to offload them to the ThreadPool, and await them to be established before starting the producers:

// Correct, awaited subscription
Task consumer = await Task.Factory.StartNew(async () =>
{
    HeavySynchronousComputation();
    await foreach (var item in source.GetAsyncEnumerable())
    {
        //...
    }
}, default, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

The Task.Factory.StartNew(async method creates a nested Task<Task>. The outer task represents the subscription, and the inner task represents the consuming loop.


问:
SSIS Execute SQL Query error with DateTime Input Parameter
I have spent a few days trying to fix this problem.  I have a SSIS package with 2 execute SQL tasks within a sequence container, one is a simple delete from table and the next one an simple insert the delete precedes the insert. The delete works fine so the connection etc is ok.

The Insert is failing with the following vague and unhelpful message.

```<code>failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
</code>```

The insert has 1 input parameter which is a date which is bound to a datetime variable set to 01/01/2011.  When I replace the ? in the sql task query with a hard coded date the task works. I have also looked at the locals at a pre-execute event break point on the insert task and the variable is ok.

I also fired up a SQL Profiler session and I see the delete query hitting the DB but nothing for the insert (when it uses the input parameter).

I am using Visual Studio 2005 Pro SP1 (Not my choice) and SQL Server 2005 SP3.

Regards

Mark

答:
I know that you have found an answer to your question. However, I would like to clarify here that the following query you were executing using OleDb connection is valid and it does work within the Execute SQL Task in SSIS package.

```<code>INSERT INTO dbo.table1 (DateCol, OtherCol, OtherCol1)
SELECT ?, SourceCol1, SourceCol2 FROM dbo.SourceTable
</code>```

Following example shows a successful implementation of the above mentioned query using SSIS 2005 (Business Intelligence Development Studio (BIDS) 2005)

Step-by-step process:

Create two tables named dbo.Source and dbo.Destination using the scripts provided under the Scripts section. Populate the table dbo.Source with data as shown in screenshot #1. Table dbo.Destination will initially be empty and will be populated with source data using an Execute SQL Task.

On the SSIS package, create an OLE DB Connection named SQLServer in the Connections Managers pointing to a SQL Server instance of your preference. Refer screenshot #2.

On the SSIS package, create a variable named RecordDate as shown in screenshot #3.

On the SSIS package, place an Execute SQL Task as shown in screenshot #4. Configure the task as shown in screenshots #5 and #6.

Screenshot #7 shows sample package execution.

Screenshot #8 shows data in the tables dbo.Source and dbo.Destination after package execution.

Hope that helps.

Scripts:
.

```<code>CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [DateValue] [datetime] NOT NULL,
    [ItemNumber] [varchar](50) NOT NULL,
    [Qty] [int] NOT NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Source](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ItemNumber] [varchar](50) NOT NULL,
    [Qty] [int] NOT NULL,
CONSTRAINT [PK_Source] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
</code>```

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:

ContentLicense: CC BY-SA 2.5

Body:
I have spent a few days trying to fix this problem.  I have a SSIS package with 2 execute SQL tasks within a sequence container, one is a simple delete from table and the next one an simple insert the delete precedes the insert. The delete works fine so the connection etc is ok.

The Insert is failing with the following vague and unhelpful message.

failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

The insert has 1 input parameter which is a date which is bound to a datetime variable set to 01/01/2011.  When I replace the ? in the sql task query with a hard coded date the task works. I have also looked at the locals at a pre-execute event break point on the insert task and the variable is ok.

I also fired up a SQL Profiler session and I see the delete query hitting the DB but nothing for the insert (when it uses the input parameter).

I am using Visual Studio 2005 Pro SP1 (Not my choice) and SQL Server 2005 SP3.

Regards

Mark

Body:
I know that you have found an answer to your question. However, I would like to clarify here that the following query you were executing using OleDb connection is valid and it does work within the Execute SQL Task in SSIS package.

INSERT INTO dbo.table1 (DateCol, OtherCol, OtherCol1)
SELECT ?, SourceCol1, SourceCol2 FROM dbo.SourceTable

Following example shows a successful implementation of the above mentioned query using SSIS 2005 (Business Intelligence Development Studio (BIDS) 2005)

Step-by-step process:

Create two tables named dbo.Source and dbo.Destination using the scripts provided under the Scripts section. Populate the table dbo.Source with data as shown in screenshot #1. Table dbo.Destination will initially be empty and will be populated with source data using an Execute SQL Task.

On the SSIS package, create an OLE DB Connection named SQLServer in the Connections Managers pointing to a SQL Server instance of your preference. Refer screenshot #2.

On the SSIS package, create a variable named RecordDate as shown in screenshot #3.

On the SSIS package, place an Execute SQL Task as shown in screenshot #4. Configure the task as shown in screenshots #5 and #6.

Screenshot #7 shows sample package execution.

Screenshot #8 shows data in the tables dbo.Source and dbo.Destination after package execution.

Hope that helps.

Scripts:
.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [DateValue] [datetime] NOT NULL,
    [ItemNumber] [varchar](50) NOT NULL,
    [Qty] [int] NOT NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Source](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ItemNumber] [varchar](50) NOT NULL,
    [Qty] [int] NOT NULL,
CONSTRAINT [PK_Source] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:


问:
Is there an issue with my useState? I feel the values are not truing up right in my Array ReactNative
Been so curious about my console.log output.

I have a button, when clicked it should basically add 1 to the use-State(1) I have created but it seems that I am doing something wrong; Please I need help with know if I am managing my State correctly {I am using React HOOKs}

```<code>const [procedureCounter, setProcedureCounter] = useState([1]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...ProcedureCounter,
  {
    id: procedureCounter.length,
    //value: procedureCounter + 1 // value is undefined for some reason so I removed it but still works
  },
]);
console.log(ProcedureCounter);

{       procedureCounter.map((item, value) => (
        <View style={{ marginVertical: 15 }} key={item.id + 1}>
          <ProcedureSteps step={value + 1} /> //This is a TexteInput Form
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
    </TouchableOpacity>
</code>```

Once 'ADD Button' is pressed it does not start from 2 as I have 1 set as initialState.
Below is my Terminal Output after clicking or Pressing 'Add Button' 3 Times

Thank you for taking the time to look into this. I really hoped I explained this as best as I can. Thank you again!

答:
First, have a consistent data type in your state so that is will easy mapping over values to create components.

const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);
```

<p>The reason you are getting undefined is you are not accessing the array properly. Check the below snippet to see how to use it. I have also updated the map iteration for component creation.</p>

<pre class="lang-js prettyprint-override"><code>
const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...procedureCounter,
  {
    id: procedureCounter[procedureCounter.length -1].id + 1,
    value: procedureCounter[procedureCounter.length -1].value + 1
  },
]);
console.log(procedureCounter);

{       procedureCounter.map((item) => (
        <View style={{ marginVertical: 15 }} key={item.id}>
          <ProcedureSteps step={item.value} /> //This is a TexteInput Form
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
</TouchableOpacity>
</code>```

Body:
Been so curious about my console.log output.

I have a button, when clicked it should basically add 1 to the use-State(1) I have created but it seems that I am doing something wrong; Please I need help with know if I am managing my State correctly {I am using React HOOKs}

const [procedureCounter, setProcedureCounter] = useState([1]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...ProcedureCounter,
  {
    id: procedureCounter.length,
    //value: procedureCounter + 1 // value is undefined for some reason so I removed it but still works
  },
]);
console.log(ProcedureCounter);

{       procedureCounter.map((item, value) => (
        <View style={{ marginVertical: 15 }} key={item.id + 1}>
          <ProcedureSteps step={value + 1} /> //This is a TexteInput Form
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
    </TouchableOpacity>

Once 'ADD Button' is pressed it does not start from 2 as I have 1 set as initialState.
Below is my Terminal Output after clicking or Pressing 'Add Button' 3 Times

Thank you for taking the time to look into this. I really hoped I explained this as best as I can. Thank you again!

Body:
First, have a consistent data type in your state so that is will easy mapping over values to create components.

const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);

The reason you are getting undefined is you are not accessing the array properly. Check the below snippet to see how to use it. I have also updated the map iteration for component creation.

const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...procedureCounter,
  {
    id: procedureCounter[procedureCounter.length -1].id + 1,
    value: procedureCounter[procedureCounter.length -1].value + 1
  },
]);
console.log(procedureCounter);

{       procedureCounter.map((item) => (
        <View style={{ marginVertical: 15 }} key={item.id}>
          <ProcedureSteps step={item.value} /> //This is a TexteInput Form
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
</TouchableOpacity>


问:
Uncaught ReferenceError: messageRef is not defined
I am using The Code Given Below To store my html contact form data in firebase

```<code>var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

saveMessage(email, packageFields, name, phone, date);
}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {

  messageRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

}
</code>```

It Gives the error

Uncaught ReferenceError: messageRef is not defined
      at saveMessage (bookingSubmit.js:47)

how can I solve it? Please help...

How To Define messageRef...??

Thanks In Advance.

答:
Try Now</p>

```<code>
var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

saveMessage(email, packageFields, name, phone, date);
}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {
// problem was here
  messagesRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

}
</code>```

Body:
I am using The Code Given Below To store my html contact form data in firebase

var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

saveMessage(email, packageFields, name, phone, date);
}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {

  messageRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

}

It Gives the error

Uncaught ReferenceError: messageRef is not defined
      at saveMessage (bookingSubmit.js:47)

how can I solve it? Please help...

How To Define messageRef...??

Thanks In Advance.

Body:
Try Now

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

saveMessage(email, packageFields, name, phone, date);
}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {
// problem was here
  messagesRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

}


问:
Can I use asyncio to read from and write to a multiprocessing.Pipe?
I need to communicate between processes in Python and am using asyncio in each of the processes for concurrent network IO.

Currently I'm using multiprocessing.Pipe to send and recv significantly large amounts of data between the processes, however I do so outside of asyncio and I believe I'm spending a lot of cpu time in IO_WAIT because of it.

It seems like asyncio can and should be used to handle the Pipe IO between processes, however I can't find an example for anything but piping STDIN/STDOUT.

From what I read it seems like I should register the pipe with loop.connect_read_pipe(PROTOCOL_FACTORY, PIPE) and likewise for write. However I don't understand the purpose of protocol_factory as it would relate to a multiprocessing.Pipe. It's not even clear if I should be creating a multiprocessing.Pipe or whether I can create a pipe within asyncio.

答:
multiprocessing.Pipe uses the high level multiprocessing.Connection module that pickles and unpickles Python objects and transmits additional bytes under the hood. If you wanted to read data from one of these pipes using loop.connect_read_pipe(), you would have to re-implement all of this yourself.

The easiest way to read from a multiprocessing.Pipe without blocking the event loop would be to use loop.add_reader(). Consider the following example:

```<code>import asyncio
import multiprocessing

def main():
    read, write = multiprocessing.Pipe(duplex=False)
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    data_available = asyncio.Event()
    asyncio.get_event_loop().add_reader(read.fileno(), data_available.set)

    if not read.poll():
        await data_available.wait()

    print(read.recv())
    data_available.clear()

def writer(write):
    write.send('Hello World')

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

Pipes created using the lower-level os.pipe don't add anything extra the way that pipes from multiprocessing.Pipe do. As a result, we can use os.pipe with loop.connect_read_pipe(), without re-implementing any sort of inner-workings. Here is an example:

```<code>import asyncio
import multiprocessing
import os

def main():
    read, write = os.pipe()
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    pipe = os.fdopen(read, mode='r')

    loop = asyncio.get_event_loop()
    stream_reader = asyncio.StreamReader()
    def protocol_factory():
        return asyncio.StreamReaderProtocol(stream_reader)

    transport, _ = await loop.connect_read_pipe(protocol_factory, pipe)
    print(await stream_reader.readline())
    transport.close()

def writer(write):
    os.write(write, b'Hello World\n')

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

This code helped me figure out how to use loop.connect_read_pipe.

Body:
multiprocessing.Pipe uses the high level multiprocessing.Connection module that pickles and unpickles Python objects and transmits additional bytes under the hood. If you wanted to read data from one of these pipes using loop.connect_read_pipe(), you would have to re-implement all of this yourself.

The easiest way to read from a multiprocessing.Pipe without blocking the event loop would be to use loop.add_reader(). Consider the following example:

import asyncio
import multiprocessing

def main():
    read, write = multiprocessing.Pipe(duplex=False)
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    data_available = asyncio.Event()
    asyncio.get_event_loop().add_reader(read.fileno(), data_available.set)

    if not read.poll():
        await data_available.wait()

    print(read.recv())
    data_available.clear()

def writer(write):
    write.send('Hello World')

if __name__ == '__main__':
    main()

Pipes created using the lower-level os.pipe don't add anything extra the way that pipes from multiprocessing.Pipe do. As a result, we can use os.pipe with loop.connect_read_pipe(), without re-implementing any sort of inner-workings. Here is an example:

import asyncio
import multiprocessing
import os

def main():
    read, write = os.pipe()
    writer_process = multiprocessing.Process(target=writer, args=(write,))
    writer_process.start()
    asyncio.get_event_loop().run_until_complete(reader(read))

async def reader(read):
    pipe = os.fdopen(read, mode='r')

    loop = asyncio.get_event_loop()
    stream_reader = asyncio.StreamReader()
    def protocol_factory():
        return asyncio.StreamReaderProtocol(stream_reader)

    transport, _ = await loop.connect_read_pipe(protocol_factory, pipe)
    print(await stream_reader.readline())
    transport.close()

def writer(write):
    os.write(write, b'Hello World\n')

if __name__ == '__main__':
    main()

This code helped me figure out how to use loop.connect_read_pipe.


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
I think this is what u need.
    #include
    int f(int x);

```<code>int main(void){
    int result = f(x);
    printf("10! is %d", result);
    return 0;
}

int f(int x) {
    if (x <= 0) return 0;
    return x*f(x-1)+2; // No more error here. This is where recursion begins
}
</code>```

By the way, that's not a factorial function.

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}

Body:
I think this is what u need.
    #include
    int f(int x);

int main(void){
    int result = f(x);
    printf("10! is %d", result);
    return 0;
}

int f(int x) {
    if (x <= 0) return 0;
    return x*f(x-1)+2; // No more error here. This is where recursion begins
}

By the way, that's not a factorial function.


问:
How to skip or remove password field in simplejwt token authentication in django rest framework?
My requirement is, I don't wanted to enter password in simplejwt token authentication. I have added one extra field in the authentication by inheriting the init() method of TokenObtainPairSerializer
as per my requrements.

Currently, I am passing None as in password field but still its showing to user (djnago admin portal). What I want is, I don't wanted to show the password field to user while authentication using simplejwt.

below is my code,

```<code>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomSerializer(TokenObtainPairSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields[self.username_field] = serializers.CharField()
        self.fields['password'] = PasswordField(default=None)
        self.fields['extra'] = serializers.CharField()

    def validate(self, attrs):
        pass

</code>```

Is there any ways to set PasswordField as unusable so it wont show to user?

答:
I have followed the below mentioned process to solve the problem,

Override the TokenObtainPairSerializer class __init__ method like below,

Use del self.fields['password'], so It wont ask you the password and add whatever fields you want.

class CustomSerializer(TokenObtainPairSerializer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields[self.username_field] = serializers.CharField()
        del self.fields['password']

This works really well. There is a almost same question I have answered, You can check it here for more knowledge.

Let me know if anyone have better solution of this problem.

Body:
My requirement is, I don't wanted to enter password in simplejwt token authentication. I have added one extra field in the authentication by inheriting the init() method of TokenObtainPairSerializer
as per my requrements.

Currently, I am passing None as in password field but still its showing to user (djnago admin portal). What I want is, I don't wanted to show the password field to user while authentication using simplejwt.

below is my code,

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomSerializer(TokenObtainPairSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields[self.username_field] = serializers.CharField()
        self.fields['password'] = PasswordField(default=None)
        self.fields['extra'] = serializers.CharField()

    def validate(self, attrs):
        pass

Is there any ways to set PasswordField as unusable so it wont show to user?


问:
How to scrape link within site using scrapy
I'm trying to use scrapy to scrape from a site, and a link within the content of the site. However, when I do this I get an error on the line above the yield statemant in parse:

TypeError: 'NoneType' object does not support item assignment

Here is my code:

```<code>class PostsSpider(scrapy.Spider):
    name = "posts"
    start_urls = ['https://www.nba.com/teams/bucks']
    allowed_domains = ['nba.com']

    def parse(self, response):
        for post in response.css('.nba-player-index section section'):
            playerPage = response.urljoin(post.css('a').attrib['href'])
            item = yield scrapy.Request(playerPage, callback=self.helper)
            item['number'] = post.css('span.nba-player-trending-item__number::text').get(),
            yield item

    def helper(self, response):
       print("--->"+response.css("title").get())
       item = Item()
       item['title'] = response.css("title::text").get()
       yield item

class Item(scrapy.Item):
    # define the fields for your item here like:
    number = scrapy.Field()
    title = scrapy.Field()
    ppg = scrapy.Field()
</code>```

答:
What you can do is pass number data to helper instead of doing this way.
Something like this:

```<code>def parse(self, response):
    for post in response.css('.nba-player-index section section'):
        playerPage = response.urljoin(post.css('a').attrib['href'])
        meta = response.meta.copy()
        meta['number'] = post.css('span.nba-player-trending-item__number::text').get()
        yield scrapy.Request(playerPage, callback=self.helper, meta=meta)

def helper(self, response):
       # here you will get `number` in response.meta['number'] that you can yield further.
       item = Item()
       item['number'] = response.meta.get('number)
       yield item
</code>```

Body:
I'm trying to use scrapy to scrape from a site, and a link within the content of the site. However, when I do this I get an error on the line above the yield statemant in parse:

TypeError: 'NoneType' object does not support item assignment

Here is my code:

class PostsSpider(scrapy.Spider):
    name = "posts"
    start_urls = ['https://www.nba.com/teams/bucks']
    allowed_domains = ['nba.com']

    def parse(self, response):
        for post in response.css('.nba-player-index section section'):
            playerPage = response.urljoin(post.css('a').attrib['href'])
            item = yield scrapy.Request(playerPage, callback=self.helper)
            item['number'] = post.css('span.nba-player-trending-item__number::text').get(),
            yield item

    def helper(self, response):
       print("--->"+response.css("title").get())
       item = Item()
       item['title'] = response.css("title::text").get()
       yield item

class Item(scrapy.Item):
    # define the fields for your item here like:
    number = scrapy.Field()
    title = scrapy.Field()
    ppg = scrapy.Field()

Body:
What you can do is pass number data to helper instead of doing this way.
Something like this:

def parse(self, response):
    for post in response.css('.nba-player-index section section'):
        playerPage = response.urljoin(post.css('a').attrib['href'])
        meta = response.meta.copy()
        meta['number'] = post.css('span.nba-player-trending-item__number::text').get()
        yield scrapy.Request(playerPage, callback=self.helper, meta=meta)

def helper(self, response):
       # here you will get `number` in response.meta['number'] that you can yield further.
       item = Item()
       item['number'] = response.meta.get('number)
       yield item


答:
That code should not compile as is. You can't define one function inside another in C, so you'll need to create another function outside main(), and call that.

I suggest you remove the factorial() function entirely, since it does not appear to be relevant to this assignment.

The basic structure of your program should be:

```<code>#include <stdio.h>

int f(int x)
{
    //definition of recursive function
}

int main(void)
{
    //call to recursive function
    return 0;
}
</code>```

The assignment gives you the definition of the recursive function; you just have to translate it into C.

Title: Homework-C Programming- Recursive Program

Body:
That code should not compile as is. You can't define one function inside another in C, so you'll need to create another function outside main(), and call that.

I suggest you remove the factorial() function entirely, since it does not appear to be relevant to this assignment.

The basic structure of your program should be:

#include <stdio.h>

int f(int x)
{
    //definition of recursive function
}

int main(void)
{
    //call to recursive function
    return 0;
}

The assignment gives you the definition of the recursive function; you just have to translate it into C.


问:
Guess the number game Python
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.

```<code>import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 100)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
    break

print("Thank you for playing")
</code>```

I wanna know how to make this to not stop until one of us is right?

答:
You can do something like this to make the computer smarter.</p>

```<code>import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
minPossible = 0
maxPossible = 100

while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player, guess lower...\n")
        if guess < maxPossible:
            maxPossible = guess - 1
    elif guess < the_number:
        print("Player, guess higher...\n")
        if guess > minPossible:
            minPossible = guess + 1
    else:
        print("Game Over! The number was", the_number, "The Player wins!")
        break

    guess = random.randint(minPossible, maxPossible)

    if guess > the_number:
        print("Computer, guess lower...\n")
        maxPossible = guess - 1
    elif guess < the_number:
        print("Computer, guess higher...\n")
        minPossible = guess + 1
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")

print("Thank you for playing")
</code>```

Title: Guess the number game Python

Body:
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.

import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 100)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
    break

print("Thank you for playing")

I wanna know how to make this to not stop until one of us is right?

Body:
You can do something like this to make the computer smarter.

import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
minPossible = 0
maxPossible = 100

while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player, guess lower...\n")
        if guess < maxPossible:
            maxPossible = guess - 1
    elif guess < the_number:
        print("Player, guess higher...\n")
        if guess > minPossible:
            minPossible = guess + 1
    else:
        print("Game Over! The number was", the_number, "The Player wins!")
        break

    guess = random.randint(minPossible, maxPossible)

    if guess > the_number:
        print("Computer, guess lower...\n")
        maxPossible = guess - 1
    elif guess < the_number:
        print("Computer, guess higher...\n")
        minPossible = guess + 1
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")

print("Thank you for playing")


问:
Why does a Transform stream stop writing after frist write?
In the example below it writes "foo" to process.stdout once.  Why doesn't it write "foo" 10 times?</p>

```<code>const { Transform } = require('stream');

class Stream extends Transform {

    constructor(){
        super({autoDestroy : false, emitClose :false});
    }

    _transform(chunk, encoding, callback){
        this.push(chunk);
    }
}

let stream = new Stream();

stream.pipe(process.stdout, {end:false});

for (let i = 0; i < 10; i++) {
    stream.write('foo');
}
</code>```

答:
The reason it doesn't print "foo" 10 times is because I didn't carefully read the documentation:

The callback function must be called only when the current chunk is completely consumed. The first argument passed to the callback must be an Error object if an error occurred while processing the input or null otherwise. If a second argument is passed to the callback, it will be forwarded on to the readable.push()...

```<code>_transform(chunk, encoding, callback){
    this.push(chunk);
    callback();
}
</code>```

fixes it.

Body:
In the example below it writes "foo" to process.stdout once.  Why doesn't it write "foo" 10 times?

const { Transform } = require('stream');

class Stream extends Transform {

    constructor(){
        super({autoDestroy : false, emitClose :false});
    }

    _transform(chunk, encoding, callback){
        this.push(chunk);
    }
}

let stream = new Stream();

stream.pipe(process.stdout, {end:false});

for (let i = 0; i < 10; i++) {
    stream.write('foo');
}

Body:
The reason it doesn't print "foo" 10 times is because I didn't carefully read the documentation:

The callback function must be called only when the current chunk is completely consumed. The first argument passed to the callback must be an Error object if an error occurred while processing the input or null otherwise. If a second argument is passed to the callback, it will be forwarded on to the readable.push()...

_transform(chunk, encoding, callback){
    this.push(chunk);
    callback();
}

fixes it.


答: Your problem is the break statement at the end of the while loop. The code is iterating through the loop one time, then the break is ending the loop.

Title: Guess the number game Python