问:
AKKA Typed SLF4J NOP warning
I am using AKKA Typed 2.6.5 with AKKA HTTP...

and getting below error

SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.

I have imported every possible sbt repository and tested but still logging is not working.
Any help would be appreciated.

答:
You need to add a dependency to an implementation of the SLF4J API. SLF4J is only an interface, and requires you to provide an implementation of your choice, as described in the documentation linked from the error message.

A popular implementation is Logback. You can include it in your project by adding it to your libraryDependencies:

```<code>libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"
</code>```

You can configure it by adding a file at src/main/resources/logback.xml with contents like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>myapp.log</file>
        <immediateFlush>false</immediateFlush>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>myapp_%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[%date{ISO8601}] [%level] [%logger] [%marker] [%thread] - %msg MDC: {%mdc}%n</pattern>
        </encoder>
    </appender>

    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <queueSize>8192</queueSize>
        <neverBlock>true</neverBlock>
        <appender-ref ref="FILE" />
    </appender>

    <root level="INFO">
        <appender-ref ref="ASYNC"/>
    </root>
</configuration>
</code>```

You can configure this to the needs of your application. See the Logback manual for details on configuration. Be sure to use an async appender as demonstrated above, so that logging doesn't result in blocking I/O on your Akka dispatcher threads.

There is more information in the Akka documentation at https://doc.akka.io/docs/akka/current/typed/logging.html#slf4j-backend

Title: AKKA Typed SLF4J NOP warning

Body:
You need to add a dependency to an implementation of the SLF4J API. SLF4J is only an interface, and requires you to provide an implementation of your choice, as described in the documentation linked from the error message.

A popular implementation is Logback. You can include it in your project by adding it to your libraryDependencies:

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"

You can configure it by adding a file at src/main/resources/logback.xml with contents like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>myapp.log</file>
        <immediateFlush>false</immediateFlush>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>myapp_%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[%date{ISO8601}] [%level] [%logger] [%marker] [%thread] - %msg MDC: {%mdc}%n</pattern>
        </encoder>
    </appender>

    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <queueSize>8192</queueSize>
        <neverBlock>true</neverBlock>
        <appender-ref ref="FILE" />
    </appender>

    <root level="INFO">
        <appender-ref ref="ASYNC"/>
    </root>
</configuration>

You can configure this to the needs of your application. See the Logback manual for details on configuration. Be sure to use an async appender as demonstrated above, so that logging doesn't result in blocking I/O on your Akka dispatcher threads.

There is more information in the Akka documentation at https://doc.akka.io/docs/akka/current/typed/logging.html#slf4j-backend


来源: stackexchange

问:
How does a file system like FastFile work?
I have 2 questions concerning the node array used by this file system which have i nodes to save the files.

Each i-node consists of

a user ID (2 bytes)

three timestamps (4 bytes each)

protection bits (2 bytes)

a reference count (2 bytes)

a file type (2 bytes)

size (4 bytes)

In addition, node-i contains

13 direct indexes

an index to a level 1 index table

an index to a level 2 index table

an index to a level 3 index table

The system also stores the first 436 bytes of each file on node-i.

So, the questions are:

Let's assume that a sector of the disk has 512 bytes, and that any auxiliary index table occupies an entire sector, what is the maximum size of a file in this system?

Is there any benefit to the first 436 bytes of the file being stored on node-i?

答:
Storing the first bytes of the file in the inode speeds up reads for files that can entirely fit in the inode itself. This is called inlining.

Because you mentioned 4 bytes (32 bits) are reserved for the file size, I'd expect 2^32 - 1 to be the max amount of sectors in a file.

From man newfs in OpenBSD:

The maximum size of an FFS file system is 2,147,483,647 (2^31 - 1) of 512-byte blocks, slightly less than 1 TB. FFS2 file systems can be as large as 64 PB.

ContentLicense: CC BY-SA 4.0


问:
"Error: line contains NULL byte" in Python DictReader
I am getting the following error "Error: line contains NULL byte" when trying to read and covert a CSV column into a dictionary list within Python.

I have followed list contains NULL byte, CSV DictReader but this doesn't seem to work with the code I have written.

import pandas as pd
import csv
from collections import defaultdict

columns = defaultdict(list)

with open('file.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k,v) in row.items():
            columns[k].append(v)

keywords = print(columns['Keyword'])```

Any help would be appreciated! Thanks.

答:
The problem as you see is the empty row/cell. The link you mentioned is replacing '\0' with a dummy string ''

Do you have any other content in the 'file.csv' which is causing this error? Can you check its content first? I believe the error you get would need replacing some other problematic string with dummy string ''

An easier way is to just print all the unique characters and check whether you have problematic strings like '\0', '\0\0', '\0,\0' etc

If you are only looking to convert a column to the list you can try this:

```<code>df = pd.read_csv("file.csv")
df["Keyord"].tolist()
</code>```

Body:
I am getting the following error "Error: line contains NULL byte" when trying to read and covert a CSV column into a dictionary list within Python.

I have followed list contains NULL byte, CSV DictReader but this doesn't seem to work with the code I have written.

import pandas as pd
import csv
from collections import defaultdict

columns = defaultdict(list)

with open('file.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k,v) in row.items():
            columns[k].append(v)

keywords = print(columns['Keyword'])

Any help would be appreciated! Thanks.

Body:
The problem as you see is the empty row/cell. The link you mentioned is replacing '\0' with a dummy string ''

Do you have any other content in the 'file.csv' which is causing this error? Can you check its content first? I believe the error you get would need replacing some other problematic string with dummy string ''

An easier way is to just print all the unique characters and check whether you have problematic strings like '\0', '\0\0', '\0,\0' etc

If you are only looking to convert a column to the list you can try this:

df = pd.read_csv("file.csv")
df["Keyord"].tolist()


问:
How to prevent saving files with certain names in Vim?
I type really fast and sometimes accidentally save a file with the name consisting of a single ; or :. (A typo is sometimes introduced as I type the :wq command.)

Is there any way to write a macro that rejects files matching certain names from being saved?

答:
A simple yet effective solution would be to define an auto-command
matching potentially mistyped file names, that issues a warning and
terminates saving:

```<code>:autocmd BufWritePre [:;]* throw 'Forbidden file name: '..expand('<afile>')
</code>```

Note that the :throw command is necessary to make Vim stop writing
the contents of a buffer.

In order to avoid getting the E605 error because of an uncaught
exception, one can issue an error using the :echoerr command run
in the try block—:echoerr raises its error message as an exception
when called from inside a try construct (see :help :echoerr).

```<code>:autocmd BufWritePre [:;]*
\   try | echoerr 'Forbidden file name: '..expand('<afile>') | endtry
</code>```

If it is ever needed to save a file with a name matching the pattern
used in the above auto-command, one can prepend a writing command
with :noautocmd or set the eventignore option accordingly (see
:help :noautocmd and :help eventignore for details), e.g.:

```<code>:noa w :ok.txt
</code>```

Body:
A simple yet effective solution would be to define an auto-command
matching potentially mistyped file names, that issues a warning and
terminates saving:

:autocmd BufWritePre [:;]* throw 'Forbidden file name: '..expand('<afile>')

Note that the :throw command is necessary to make Vim stop writing
the contents of a buffer.

In order to avoid getting the E605 error because of an uncaught
exception, one can issue an error using the :echoerr command run
in the try block—:echoerr raises its error message as an exception
when called from inside a try construct (see :help :echoerr).

:autocmd BufWritePre [:;]*
\   try | echoerr 'Forbidden file name: '..expand('<afile>') | endtry

If it is ever needed to save a file with a name matching the pattern
used in the above auto-command, one can prepend a writing command
with :noautocmd or set the eventignore option accordingly (see
:help :noautocmd and :help eventignore for details), e.g.:

:noa w :ok.txt


问:
Download multiple files over FTP using one connection in .NET Core
I am trying to download multiple files to memory with only one open connection.

I know from this documentation: https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest.keepalive – that FtpWebRequest defaults KeepAlive to true.

if the connection to the server should not be destroyed; otherwise, false. The default value is true.

I have created this piece of code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApp23
{
    class Program
    {

        static void Main(string[] args)
        {
            String[] files = FTPListTree("ftp://server.com", "user", "password");

            for (int i = 0; i <= files.Count() - 1; i++)
            {
                string path = files[i].ToString();
                var request = (FtpWebRequest)WebRequest.Create(path);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential("user", "password");
                request.Timeout = 100000;
                request.KeepAlive = true;
                request.ConnectionGroupName = "DownloadFilesGroup";
                request.ServicePoint.ConnectionLimit = 8;

                using (var response = (FtpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var ms = new MemoryStream();
                        stream.CopyTo(ms);
                        var a = ms.ToArray();
                        string ss = Encoding.UTF8.GetString(a);
                        Console.WriteLine(ss);
                    }
                }
            }
        }

        public static String[] FTPListTree(String ftpUri, String user, String pass)
        {

            try
            {
                List<String> files = new List<String>();
                Queue<String> folders = new Queue<String>();
                folders.Enqueue(ftpUri);

                while (folders.Count > 0)
                {
                    String fld = folders.Dequeue();
                    List<String> newFiles = new List<String>();

                    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(fld);
                    ftp.Timeout = 20000;
                    ftp.Credentials = new NetworkCredential(user, pass);
                    ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                    using (StreamReader resp = new StreamReader(ftp.GetResponse().GetResponseStream()))
                    {
                        String line = resp.ReadLine();
                        while (line != null)
                        {
                            newFiles.Add(line.Trim());
                            line = resp.ReadLine();
                        }
                    }

                    ftp = (FtpWebRequest)FtpWebRequest.Create(fld);
                    ftp.Timeout = 20000;
                    ftp.Credentials = new NetworkCredential(user, pass);
                    ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                    using (StreamReader resp = new StreamReader(ftp.GetResponse().GetResponseStream()))
                    {
                        String line = resp.ReadLine();
                        while (line != null)
                        {
                            if (!Path.HasExtension(line))
                            {
                                String dir = newFiles.First(x => line.EndsWith(x));
                                newFiles.Remove(dir);
                                folders.Enqueue(fld + dir + "/");
                            }
                            line = resp.ReadLine();
                        }
                    }
                    files.AddRange(from f in newFiles select fld + f);
                }
                return files.ToArray();
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
</code>```

Is this a proper way of doing dispose? I can't seem to find any documentation on if disposing the response or the response stream, will close the control connection, that the keepalive will keep open.

Is there any way I can log this when running this, so I can see the FTP calls? I don't have access to the FTP server myself.

UPDATE

I have actually tested this with a test FTP and the above code, even though it has KeepAlive=true, it uses new connection on every request. I have created an PoC with Fluent API: https://github.com/robinrodricks/FluentFTP/blob/master/FluentFTP.CSharpExamples/DownloadManyFiles.cs, that does it correctly: connect once, and downloads files. I had a feeling that it was the case with FtpWebRequest. I don't understand the KeepAlive and what it does. Maybe it reuses the TCP connection, which is a good thing in itself, but it uses the TCP connection to login on each request.

Does anybody know if this is even possible with FtpWebRequest, not logging in on each new request, like the Fluent FTP API? Am I missing something?

An example of the FTP log can be seen here

FTP is FileZilla Server 0.9.60 beta.

答:
It seems that the FTP connection reuse was not implemented in .NET Core:
https://github.com/dotnet/runtime/issues/23256

And as *WebRequest API is actually obsolete, it probably never will.

With .NET framework, it works as expected:

FTP multiple files in C# without reestablishing connection

Body:
I am trying to download multiple files to memory with only one open connection.

I know from this documentation: https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest.keepalive – that FtpWebRequest defaults KeepAlive to true.

if the connection to the server should not be destroyed; otherwise, false. The default value is true.

I have created this piece of code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApp23
{
    class Program
    {

        static void Main(string[] args)
        {
            String[] files = FTPListTree("ftp://server.com", "user", "password");

            for (int i = 0; i <= files.Count() - 1; i++)
            {
                string path = files[i].ToString();
                var request = (FtpWebRequest)WebRequest.Create(path);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential("user", "password");
                request.Timeout = 100000;
                request.KeepAlive = true;
                request.ConnectionGroupName = "DownloadFilesGroup";
                request.ServicePoint.ConnectionLimit = 8;

                using (var response = (FtpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var ms = new MemoryStream();
                        stream.CopyTo(ms);
                        var a = ms.ToArray();
                        string ss = Encoding.UTF8.GetString(a);
                        Console.WriteLine(ss);
                    }
                }
            }
        }

        public static String[] FTPListTree(String ftpUri, String user, String pass)
        {

            try
            {
                List<String> files = new List<String>();
                Queue<String> folders = new Queue<String>();
                folders.Enqueue(ftpUri);

                while (folders.Count > 0)
                {
                    String fld = folders.Dequeue();
                    List<String> newFiles = new List<String>();

                    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(fld);
                    ftp.Timeout = 20000;
                    ftp.Credentials = new NetworkCredential(user, pass);
                    ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                    using (StreamReader resp = new StreamReader(ftp.GetResponse().GetResponseStream()))
                    {
                        String line = resp.ReadLine();
                        while (line != null)
                        {
                            newFiles.Add(line.Trim());
                            line = resp.ReadLine();
                        }
                    }

                    ftp = (FtpWebRequest)FtpWebRequest.Create(fld);
                    ftp.Timeout = 20000;
                    ftp.Credentials = new NetworkCredential(user, pass);
                    ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                    using (StreamReader resp = new StreamReader(ftp.GetResponse().GetResponseStream()))
                    {
                        String line = resp.ReadLine();
                        while (line != null)
                        {
                            if (!Path.HasExtension(line))
                            {
                                String dir = newFiles.First(x => line.EndsWith(x));
                                newFiles.Remove(dir);
                                folders.Enqueue(fld + dir + "/");
                            }
                            line = resp.ReadLine();
                        }
                    }
                    files.AddRange(from f in newFiles select fld + f);
                }
                return files.ToArray();
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}

Is this a proper way of doing dispose? I can't seem to find any documentation on if disposing the response or the response stream, will close the control connection, that the keepalive will keep open.

Is there any way I can log this when running this, so I can see the FTP calls? I don't have access to the FTP server myself.

UPDATE

I have actually tested this with a test FTP and the above code, even though it has KeepAlive=true, it uses new connection on every request. I have created an PoC with Fluent API: https://github.com/robinrodricks/FluentFTP/blob/master/FluentFTP.CSharpExamples/DownloadManyFiles.cs, that does it correctly: connect once, and downloads files. I had a feeling that it was the case with FtpWebRequest. I don't understand the KeepAlive and what it does. Maybe it reuses the TCP connection, which is a good thing in itself, but it uses the TCP connection to login on each request.

Does anybody know if this is even possible with FtpWebRequest, not logging in on each new request, like the Fluent FTP API? Am I missing something?

An example of the FTP log can be seen here

FTP is FileZilla Server 0.9.60 beta.


问:
When i install any flutter package, example projects are also including?
When i install any flutter package for eg: shared_preference, "example project" is also including along with that package for iOS, Android and Web. That increases my flutter project size. Initially my project size is in 1 mb or 2mb only. Including example projects also in package installation, my project size also increasing. Now my project size is 136mb.

How can i solve to reduce my project size?

Update :

I created new project.

1
Initial project size.

2 After install shared_preference package.

3 After install pod for iOS.

答:
Try this command in the terminal

flutter build apk

And navigate to the folder

Your_Flutter_Application/build/app/outputs/apk/app.apk

Try to install this apk in your device you can see the reduce in the size of the application

If you are talking about the space occupied by the project in you laptop/system it depends on the assets and the other dependences you use in the project we can't reduce it but the above procces will help you to reduce the final application size


问:
Best solution for "No Scheme" issue in Xcode 4 after defected merging git branches
Got the "No Scheme" issue after merging the conflict issue

Auto-merging SampleProject.xcodeproj/project.pbxproj
  CONFLICT (content): Merge conflict in SampleProject.xcodeproj/project.pbxproj
  Automatic merge failed; fix conflicts and then commit the result.

Definitely I took some defected operations when merging the conflicts.
The question is that does there has any best solution to fix the "No Scheme" issue in this kind of case.

答: Deleting my entire project and reinstalling pod files resolved the issue (None of the above worked).</p>

ContentLicense: CC BY-SA 3.0


问:
Angular passing data to variable and that variable usage
Declaring variable

```<code>export class TestComponent implements OnInit {
testVar:string;
</code>```

then initialising

```<code>ngOnInit() {

this.somefunction works.subscribe(
this.testVar='testData';
console.log('log1 '+this.testVar);
);
console.log('log2 '+this.testVar);
}
</code>```

now firing AfterViewInit:

```<code>ngAfterViewInit() {
console.log('log3 '+this.testVar);
</code>```

The results are

```<code>log1 testData
log2 undefined
log3 undefined
</code>```

question is why log2 and log 3 give undefined testVar and how can I fix that ?

答:
That is not how asynchronous data works. The variables are not assigned values as soon the call is made. All statements that directly depend on an async data (this.testVar here) should be inside the subscription.

ngOnInit() {
  this.service.someFunction().subscribe(
    value => {
      this.testVar='testData';
      console.log('log1 '+this.testVar);
      console.log('log2 '+this.testVar);
      ...
    }
  );
}
```

AfterViewInit lifecycle hook has nothing to do with how the variables are initialized in the controller. It will be called after Angular has fully initialized a component's view/template.

See here for more details on how to access async data: https://stackoverflow.com/a/14220323/6513921

Body:
Declaring variable

export class TestComponent implements OnInit {
testVar:string;

then initialising

ngOnInit() {

this.somefunction works.subscribe(
this.testVar='testData';
console.log('log1 '+this.testVar);
);
console.log('log2 '+this.testVar);
}

now firing AfterViewInit:

ngAfterViewInit() {
console.log('log3 '+this.testVar);

The results are

log1 testData
log2 undefined
log3 undefined

question is why log2 and log 3 give undefined testVar and how can I fix that ?

Body:
That is not how asynchronous data works. The variables are not assigned values as soon the call is made. All statements that directly depend on an async data (this.testVar here) should be inside the subscription.

ngOnInit() {
  this.service.someFunction().subscribe(
    value => {
      this.testVar='testData';
      console.log('log1 '+this.testVar);
      console.log('log2 '+this.testVar);
      ...
    }
  );
}

AfterViewInit lifecycle hook has nothing to do with how the variables are initialized in the controller. It will be called after Angular has fully initialized a component's view/template.

See here for more details on how to access async data: https://stackoverflow.com/a/14220323/6513921


问:
Visual Designer for JSF
I am using Netbeans for JSF development and...is there any Visual Web Designer plugin for JSF in Netbeans 6.9.1?

I am a sloppy guy, so without a visual aid for web development, I pretty much messed up my web UI.

答:
Visual aid is no more available since Netbeans 6.9 release.

You can find those in previous netbeans version. I have seen it in 6.7, where you install JSF pluggin and can find an option to create Visual JSF page

Check following links for more info

Link 1

Link 2

Title: Visual Designer for JSF


问:
Flutter: How to fit the web view size to screen?
I am new in flutter,

tried to use web view in flutter, but the the size of the web view is bigger than the screen.

I want to fit the web page size to the phone screen size.

How I can do that?

Here is what I get now:

I want to see:

Here is my code:

import 'package:flutter/material.dart';

import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

```<code>class CoursesInformation extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<CoursesInformation> {
  TextEditingController controller = TextEditingController();
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var urlString = "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx";

  launchUrl() {
    setState(() {
      urlString = controller.text;
     flutterWebviewPlugin.reloadUrl(urlString);
       flutterWebviewPlugin.launch(urlString,
              rect: new Rect.fromLTWH(
                  0.0,
                  0.0,
                  MediaQuery.of(context).size.width,
                  300.0));
    });
  }

  @override
  void initState() {
    super.initState();

    flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
      print(wvs.type);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
    textDirection: TextDirection.rtl,
    child: WebviewScaffold(
      appBar: AppBar(
        title: Text('מידע על קורסים'),
        centerTitle: true
      ),
      url: urlString,
      withZoom: true,
      scrollBar: true,
      withJavascript: true,
      useWideViewPort: true,

      withLocalStorage: true,
        ));
  }
}
</code>```

答:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

In your case, you can enable the DESKTOP mode (as it happens on normal browsers like Chrome, etc.) through the option preferredContentMode: UserPreferredContentMode.DESKTOP

Here is an example with your URL:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl:
                "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
                  preferredContentMode: UserPreferredContentMode.DESKTOP),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) async {

            },
          ))
        ])),
      ),
    );
  }
}
```

Here is the Screenshot:

Body:
I am new in flutter,

tried to use web view in flutter, but the the size of the web view is bigger than the screen.

I want to fit the web page size to the phone screen size.

How I can do that?

Here is what I get now:

I want to see:

Here is my code:

import 'package:flutter/material.dart';

import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class CoursesInformation extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<CoursesInformation> {
  TextEditingController controller = TextEditingController();
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var urlString = "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx";

  launchUrl() {
    setState(() {
      urlString = controller.text;
     flutterWebviewPlugin.reloadUrl(urlString);
       flutterWebviewPlugin.launch(urlString,
              rect: new Rect.fromLTWH(
                  0.0,
                  0.0,
                  MediaQuery.of(context).size.width,
                  300.0));
    });
  }

  @override
  void initState() {
    super.initState();

    flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
      print(wvs.type);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
    textDirection: TextDirection.rtl,
    child: WebviewScaffold(
      appBar: AppBar(
        title: Text('מידע על קורסים'),
        centerTitle: true
      ),
      url: urlString,
      withZoom: true,
      scrollBar: true,
      withJavascript: true,
      useWideViewPort: true,

      withLocalStorage: true,
        ));
  }
}

Body:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

In your case, you can enable the DESKTOP mode (as it happens on normal browsers like Chrome, etc.) through the option preferredContentMode: UserPreferredContentMode.DESKTOP

Here is an example with your URL:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl:
                "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
                  preferredContentMode: UserPreferredContentMode.DESKTOP),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) async {

            },
          ))
        ])),
      ),
    );
  }
}

Here is the Screenshot:


问:
Basic Global State with React Hooks in React Native
I've been jumping on the React Hooks bandwagon and decided to roll a React Native app together to try and give a full redux/global state implementation a shot. I've been following some articles on how to go about it, but I do have some questions.

I understand the concepts of useState and useReducer, but I'm getting hung up on the Context side of things.

First question: What is the best way to pass a state object down the tree without having to use props? Here's what I have so far. Normally, without Navigation, you would have a child component of DispatchContext that would receive props. But since I do have Navigation, I don't really want to pass the state down the tree. I feel that defeats the purpose of Context and hooks in general. I've seen some things where the value={dispatch} is value={{somePieceOfState}}. How can I pass both the state and the dispatch into the component tree?

```<code>import React, { useReducer } from 'react';
import Navigation from './Navigation';
import { DispatchContext } from './Context';
import { countReducer } from './reducers';

const App = () => {
  const [count, dispatchCount] = useReducer(countReducer, 0);

  const dispatch = action => [dispatchCount].forEach(fn => fn(action)); //provides one dispatch for the entire component tree

  const state = {
      count,
      //other pieces of state go here
  }

  return (
    <DispatchContext.Provider value={dispatch}>
      <Navigation />
      // <ChildComponent someStateProp={count} /> normal way to pass down props
    </DispatchContext.Provider>
  );
};

export default App;
</code>```

Second question: What's the best way to do actions and action creators? This is probably able to be answered in conjunction with the first question. Here is a component attached to my navigation.

```<code>import React, { useContext } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { DispatchContext } from './Context';
import { countUp, countDown } from './actions';

const Comp1 = () => {
  const dispatch = useContext(DispatchContext);
  return (
    <View>
      <TouchableOpacity
        onPress={() => dispatch(countUp)}
      >
        <Text>Up</Text>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() => dispatch(countDown)}
      >
        <Text>Down</Text>
      </TouchableOpacity>
    </View>
  );
};

export default Comp1;
</code>```

The actions associated with it:

```<code>import {
  COUNT_UP,
  COUNT_DOWN
} from './types';

export const countUp = () => {
  return {
    type: COUNT_UP
  };
};

export const countDown = () => {
  return {
    type: COUNT_DOWN
  };
};
</code>```

And the reducer:

```<code>import {
  COUNT_UP,
  COUNT_DOWN
} from '../actions/types';

export const countReducer = (state, action) => {
  console.log(action);
  switch (action) {
    case COUNT_UP:
      return state + 1;
    case COUNT_DOWN:
      return state - 1;
    default:
      return state;
  }
};
</code>```

I know the actions and dispatch and all that works because I console.log() in my reducer and I get a response. But when I console.log(action), it shows that it's the function, the action itself instead of the type. If I console.log(action.type), it's undefined. What am I doing wrong here?

Last question: Is this a reasonable approach for complex state management? I know about useEffect() and stuff like that, but from anyone that has had some experience with hooks, is it good for api calls and location tracking and stuff like that? Is it an extensible approach? Basically what I'm asking is I don't want to get knee deep into this and have to refactor everything into class-based components because I can't do something with hooks that I need to do with classes. But I really like this hooks thing and I want to stick with it. Is it good to move forward with it?

Sorry for the long post, but I feel these questions that have answers would be useful for others that are looking to get into hooks with react native.

答:
Many existing global hook libraries for React bundles React inside it, or modifies it.

In addition, I didn't like the way that they all seem to rely on "strings" as keys, and lack TypeScript strong-typing.

I just wanted something simple with no magical stuff that might break all the time, or leak memory.

So I wrote my own. Check the source - it's super simple:

https://www.npmjs.com/package/@fluffy-spoon/react-globalize

Usage

First, you need to globally create a key for your state, with an optional initial value.

//users.ts

import { createGlobal } from '@fluffy-spoon/react-globalize';

export const usersKey = createGlobal([{ firstName: "John", lastName: "Doe" }]);
```

<p>Then, you can simply use it in one of your components, just like you would use <code>useState</code>!</p>

<pre class="lang-js prettyprint-override"><code>//index.ts

import { usersKey } from './users';

export const GlobalUserListComponent = () => {

    //users and setUsers behaves like useState, except they are now shared between all components!
    const [users, setUsers] = useGlobal(usersKey);

    ...
}
</code>```

Body:
I've been jumping on the React Hooks bandwagon and decided to roll a React Native app together to try and give a full redux/global state implementation a shot. I've been following some articles on how to go about it, but I do have some questions.

I understand the concepts of useState and useReducer, but I'm getting hung up on the Context side of things.

First question: What is the best way to pass a state object down the tree without having to use props? Here's what I have so far. Normally, without Navigation, you would have a child component of DispatchContext that would receive props. But since I do have Navigation, I don't really want to pass the state down the tree. I feel that defeats the purpose of Context and hooks in general. I've seen some things where the value={dispatch} is value={{somePieceOfState}}. How can I pass both the state and the dispatch into the component tree?

import React, { useReducer } from 'react';
import Navigation from './Navigation';
import { DispatchContext } from './Context';
import { countReducer } from './reducers';

const App = () => {
  const [count, dispatchCount] = useReducer(countReducer, 0);

  const dispatch = action => [dispatchCount].forEach(fn => fn(action)); //provides one dispatch for the entire component tree

  const state = {
      count,
      //other pieces of state go here
  }

  return (
    <DispatchContext.Provider value={dispatch}>
      <Navigation />
      // <ChildComponent someStateProp={count} /> normal way to pass down props
    </DispatchContext.Provider>
  );
};

export default App;

Second question: What's the best way to do actions and action creators? This is probably able to be answered in conjunction with the first question. Here is a component attached to my navigation.

import React, { useContext } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { DispatchContext } from './Context';
import { countUp, countDown } from './actions';

const Comp1 = () => {
  const dispatch = useContext(DispatchContext);
  return (
    <View>
      <TouchableOpacity
        onPress={() => dispatch(countUp)}
      >
        <Text>Up</Text>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() => dispatch(countDown)}
      >
        <Text>Down</Text>
      </TouchableOpacity>
    </View>
  );
};

export default Comp1;

The actions associated with it:

import {
  COUNT_UP,
  COUNT_DOWN
} from './types';

export const countUp = () => {
  return {
    type: COUNT_UP
  };
};

export const countDown = () => {
  return {
    type: COUNT_DOWN
  };
};

And the reducer:

import {
  COUNT_UP,
  COUNT_DOWN
} from '../actions/types';

export const countReducer = (state, action) => {
  console.log(action);
  switch (action) {
    case COUNT_UP:
      return state + 1;
    case COUNT_DOWN:
      return state - 1;
    default:
      return state;
  }
};

I know the actions and dispatch and all that works because I console.log() in my reducer and I get a response. But when I console.log(action), it shows that it's the function, the action itself instead of the type. If I console.log(action.type), it's undefined. What am I doing wrong here?

Last question: Is this a reasonable approach for complex state management? I know about useEffect() and stuff like that, but from anyone that has had some experience with hooks, is it good for api calls and location tracking and stuff like that? Is it an extensible approach? Basically what I'm asking is I don't want to get knee deep into this and have to refactor everything into class-based components because I can't do something with hooks that I need to do with classes. But I really like this hooks thing and I want to stick with it. Is it good to move forward with it?

Sorry for the long post, but I feel these questions that have answers would be useful for others that are looking to get into hooks with react native.

Body:
Many existing global hook libraries for React bundles React inside it, or modifies it.

In addition, I didn't like the way that they all seem to rely on "strings" as keys, and lack TypeScript strong-typing.

I just wanted something simple with no magical stuff that might break all the time, or leak memory.

So I wrote my own. Check the source - it's super simple:

https://www.npmjs.com/package/@fluffy-spoon/react-globalize

Usage

First, you need to globally create a key for your state, with an optional initial value.

//users.ts

import { createGlobal } from '@fluffy-spoon/react-globalize';

export const usersKey = createGlobal([{ firstName: "John", lastName: "Doe" }]);

Then, you can simply use it in one of your components, just like you would use useState!

//index.ts

import { usersKey } from './users';

export const GlobalUserListComponent = () => {

    //users and setUsers behaves like useState, except they are now shared between all components!
    const [users, setUsers] = useGlobal(usersKey);

    ...
}


问:
Execution order between React's useEffect and DOM event handler
I wrote a custom context provider in the below which holds application settings as a Context as well as save it in localStorage (thanks to a post by Alex Krush).

I added initialized flag to avoid saving the value fetched from localStorage right after the component is mounted (useEffect will be run at the timing of componentDidMount and try to write the fetched value to the storage).

import React, { useCallback, useEffect, useReducer, useRef } from 'react';

const storageKey = 'name';
const defaultValue = 'John Doe';

const initializer = (initialValue) => localStorage.getItem(storageKey) || initialValue;
const reducer = (value, newValue) => newValue;

const CachedContext = React.createContext();

const CachedContextProvider = (props) => {
  const [value, setValue] = useReducer(reducer, defaultValue, initializer);
  const initialized = useRef(false);

  // save the updated value as a side-effect
  useEffect(() => {
    if (initialized.current) {
      localStorage.setItem(storageKey, value);
    } else {
      initialized.current = true; // skip saving for the first time
    }
  }, [value]);

  return (
    <CachedContext.Provider value={[value, setValue]}>
      {props.children}
    </CachedContext.Provider>
  );
};
```

<p>Usage:</p>

<pre class="lang-js prettyprint-override"><code>const App = (props) => {
  return <CachedContextProvider><Name name='Jane Doe' /></CachedContextProvider>;
}

const Name = (props) => {
  const [name, setName] = useContext(CachedContext);

  useEffect(() => {
    setName(props.name);
  }, [props.name]);
}
</code>```

Then, I'd like to make my custom context detect changes to the target storage made by another window. I added handleStorageEvent to CachedContextProvider for listening storage events:

  // re-initialize when the storage has been modified by another window
  const handleStorageEvent = useCallback((e) => {
    if (e.key === storageKey) {
      initialized.current = false; // <-- is it safe???
      setValue(initializer(defaultValue));
    }
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('storage', handleStorageEvent);
      return () => {
        window.removeEventListener('storage', handleStorageEvent);
      };
    }
  }, []);
```

My concern is whether I can reset initialized to false safely for avoid writing back the fetched value. I'm worried about the following case in the multi-process setting:

Window 1 runs setValue('Harry Potter')

Window 2 runs setValue('Harry Potter')

Window 2 runs localStorage.setItem in response to update on value

handleStorageEvent in Window 1 detects the change in storage and re-initialize its initialized and value as false and 'Harry Potter'

Window 1 try to run localStorage.setItem, but it does nothing because value is already set as 'Harry Potter' by Window 2 and React may judge there is no changes. As a result, initialized will be kept as false

Window 1 runs setValue('Ron Weasley'). It updates value but does not save it because initialized === false. It has a chance to lose the value set by the application

I think it is related to the execution order between React's useEffect and DOM event handler. Does anyone know how to do it right?

答:
I would probably add some sort of test to see what happens in every possible scenario.

However, this is my theory: In step 5, window 1 will not try to run localStorage.setItem (as you said), since initialized was just set to false. It will instead set initialized to true. Step 6 should therefore work as expected, and this shouldn't be an issue.

Body:
I wrote a custom context provider in the below which holds application settings as a Context as well as save it in localStorage (thanks to a post by Alex Krush).

I added initialized flag to avoid saving the value fetched from localStorage right after the component is mounted (useEffect will be run at the timing of componentDidMount and try to write the fetched value to the storage).

import React, { useCallback, useEffect, useReducer, useRef } from 'react';

const storageKey = 'name';
const defaultValue = 'John Doe';

const initializer = (initialValue) => localStorage.getItem(storageKey) || initialValue;
const reducer = (value, newValue) => newValue;

const CachedContext = React.createContext();

const CachedContextProvider = (props) => {
  const [value, setValue] = useReducer(reducer, defaultValue, initializer);
  const initialized = useRef(false);

  // save the updated value as a side-effect
  useEffect(() => {
    if (initialized.current) {
      localStorage.setItem(storageKey, value);
    } else {
      initialized.current = true; // skip saving for the first time
    }
  }, [value]);

  return (
    <CachedContext.Provider value={[value, setValue]}>
      {props.children}
    </CachedContext.Provider>
  );
};

Usage:

const App = (props) => {
  return <CachedContextProvider><Name name='Jane Doe' /></CachedContextProvider>;
}

const Name = (props) => {
  const [name, setName] = useContext(CachedContext);

  useEffect(() => {
    setName(props.name);
  }, [props.name]);
}

Then, I'd like to make my custom context detect changes to the target storage made by another window. I added handleStorageEvent to CachedContextProvider for listening storage events:

  // re-initialize when the storage has been modified by another window
  const handleStorageEvent = useCallback((e) => {
    if (e.key === storageKey) {
      initialized.current = false; // <-- is it safe???
      setValue(initializer(defaultValue));
    }
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('storage', handleStorageEvent);
      return () => {
        window.removeEventListener('storage', handleStorageEvent);
      };
    }
  }, []);

My concern is whether I can reset initialized to false safely for avoid writing back the fetched value. I'm worried about the following case in the multi-process setting:

Window 1 runs setValue('Harry Potter')

Window 2 runs setValue('Harry Potter')

Window 2 runs localStorage.setItem in response to update on value

handleStorageEvent in Window 1 detects the change in storage and re-initialize its initialized and value as false and 'Harry Potter'

Window 1 try to run localStorage.setItem, but it does nothing because value is already set as 'Harry Potter' by Window 2 and React may judge there is no changes. As a result, initialized will be kept as false

Window 1 runs setValue('Ron Weasley'). It updates value but does not save it because initialized === false. It has a chance to lose the value set by the application

I think it is related to the execution order between React's useEffect and DOM event handler. Does anyone know how to do it right?


问:
How to counter conflicting types error when dealing with pointers?
new to coding and I'm learning by doing questions.In this question were im stuck at im supposed to write code which takes input in array and prints it using pointers.Here is the code below please point out where i got it wrong.</p>

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

int* record_array (int *size_ptr);
void print_array (int *array_ptr , int *size_ptr);

int* record_array (int *size_ptr)
{
    int *array_ptr = (int*) malloc(*size_ptr * sizeof(int));
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("Enter element at index %d : ", index);
        scanf("%d", &array_ptr[index]);
    }
    return array_ptr;
}
void print_array (int *array_ptr, int *size_ptr)
{
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("%d ",array_ptr[index]);
    }

}

int main()
{
    int size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%d", &size);
    array = record_array(&size);
    print_array(array,&size);
    free(array);

    return 0;
}
</code>```

答:
When you test some ideas do not scanf values. scanf can be quite tricky for the beginners. Use also the correct types.

You do not need to pass the size of the array by the reference.

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

int* record_array (size_t size);
void print_array (const int *array_ptr, size_t size);

int* record_array (size_t size)
{
    int *array_ptr = malloc(size * sizeof(*array_ptr));
    for (size_t index = 0;index < size; ++index)
    {
        array_ptr[index] = index;
    }
    return array_ptr;
}
void print_array (const int *array_ptr, size_t size)
{
    for (int index = 0; index < size; ++index)
    {
        printf("%d\t%s", array_ptr[index], (index % 6) ? "" : "\n");
    }

}

int main()
{
    size_t size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%zu", &size);
    array = record_array(size);
    print_array(array,size);
    free(array);

    return 0;
}
</code>```

https://godbolt.org/z/J9SEne

If you want to use pointers to pass the size (and you do not change it in the functions)

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

int* record_array (const size_t *size);
void print_array (const int *array_ptr, const size_t *size);

int* record_array (const size_t *size)
{
    int *array_ptr = malloc(*size * sizeof(*array_ptr));
    for (size_t index = 0;index < *size; ++index)
    {
        array_ptr[index] = index;
    }
    return array_ptr;
}
void print_array (const int *array_ptr, const size_t *size)
{
    for (int index = 0; index < *size; ++index)
    {
        printf("%d\t%s", array_ptr[index], (index % 6) ? "" : "\n");
    }

}

int main()
{
    size_t size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%zu", &size);
    array = record_array(&size);
    print_array(array,&size);
    free(array);

    return 0;
}
</code>```

https://godbolt.org/z/Vwt9oS

Remember that you always check the passed pointers if they are not NULL and check the result of the malloc

Body:
new to coding and I'm learning by doing questions.In this question were im stuck at im supposed to write code which takes input in array and prints it using pointers.Here is the code below please point out where i got it wrong.

#include <stdio.h>
#include <stdlib.h>

int* record_array (int *size_ptr);
void print_array (int *array_ptr , int *size_ptr);

int* record_array (int *size_ptr)
{
    int *array_ptr = (int*) malloc(*size_ptr * sizeof(int));
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("Enter element at index %d : ", index);
        scanf("%d", &array_ptr[index]);
    }
    return array_ptr;
}
void print_array (int *array_ptr, int *size_ptr)
{
    for (int index = 0;index < *size_ptr;++index)
    {
        printf("%d ",array_ptr[index]);
    }

}

int main()
{
    int size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%d", &size);
    array = record_array(&size);
    print_array(array,&size);
    free(array);

    return 0;
}

Body:
When you test some ideas do not scanf values. scanf can be quite tricky for the beginners. Use also the correct types.

You do not need to pass the size of the array by the reference.

#include <stdio.h>
#include <stdlib.h>

int* record_array (size_t size);
void print_array (const int *array_ptr, size_t size);

int* record_array (size_t size)
{
    int *array_ptr = malloc(size * sizeof(*array_ptr));
    for (size_t index = 0;index < size; ++index)
    {
        array_ptr[index] = index;
    }
    return array_ptr;
}
void print_array (const int *array_ptr, size_t size)
{
    for (int index = 0; index < size; ++index)
    {
        printf("%d\t%s", array_ptr[index], (index % 6) ? "" : "\n");
    }

}

int main()
{
    size_t size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%zu", &size);
    array = record_array(size);
    print_array(array,size);
    free(array);

    return 0;
}

https://godbolt.org/z/J9SEne

If you want to use pointers to pass the size (and you do not change it in the functions)

#include <stdio.h>
#include <stdlib.h>

int* record_array (const size_t *size);
void print_array (const int *array_ptr, const size_t *size);

int* record_array (const size_t *size)
{
    int *array_ptr = malloc(*size * sizeof(*array_ptr));
    for (size_t index = 0;index < *size; ++index)
    {
        array_ptr[index] = index;
    }
    return array_ptr;
}
void print_array (const int *array_ptr, const size_t *size)
{
    for (int index = 0; index < *size; ++index)
    {
        printf("%d\t%s", array_ptr[index], (index % 6) ? "" : "\n");
    }

}

int main()
{
    size_t size = 0;
    int *array = NULL;

    printf("How many elements do you want?");
    scanf("%zu", &size);
    array = record_array(&size);
    print_array(array,&size);
    free(array);

    return 0;
}

https://godbolt.org/z/Vwt9oS

Remember that you always check the passed pointers if they are not NULL and check the result of the malloc


问:
Lit-Element and Redux: Update Object in Array
I am trying to update the roll property in an object which is nested in the players array.
My state looks like this:

```<code>players: [
  {
    "id": "44ufazeep0o",
    "name": "test-player-1",
    "roll": 0,
    "totalWins": 0
  },
  {
    "id": "eu8hutex7z9",
    "name": "test-player-2",
    "roll": 0,
    "totalWins": 0
  }
]
</code>```

This is my action:

```<code>export const addRoll = (roll, id) => {
  return {
    type: ADD_ROLL,
    roll,
    id,
  }
}
</code>```

This is my reducer:

```<code>case ADD_ROLL:
  return state.players.map((player) => {
    if (player.id === action.id) {
      return {
        ...player,
        roll: action.roll,
      }
    }
    return player;
  });
  ...
</code>```

I am watching state.players in an components like so:

```<code>import { connect } from 'pwa-helpers'; // connects a Custom Element base class to the Redux store
...

stateChanged(state) {
   this.players = state.players;
}

render() {
  return html`${this.players.map((player)=> html`<h1>${player.name}</h1>`)}`
}
</code>```

Now, whenever I call store.dispatch(addRoll(this.roll, this.id)), this.players.map() returns undefined in the component where I am watching state.players.
Any input on why this might happen is much appreciated!

答:
You have return an array instead of an object with players key in it from state after ADD_ROLL action is dispatched. Correct way to update it would be</p>

```<code>case ADD_ROLL:
  return {
    ...state,
    players: state.players.map((player) => {
      if (player.id === action.id) {
        return {
          ...player,
          roll: action.roll,
        }
      }
      return player;
    });
  }
  ...
</code>```

Body:
I am trying to update the roll property in an object which is nested in the players array.
My state looks like this:

players: [
  {
    "id": "44ufazeep0o",
    "name": "test-player-1",
    "roll": 0,
    "totalWins": 0
  },
  {
    "id": "eu8hutex7z9",
    "name": "test-player-2",
    "roll": 0,
    "totalWins": 0
  }
]

This is my action:

export const addRoll = (roll, id) => {
  return {
    type: ADD_ROLL,
    roll,
    id,
  }
}

This is my reducer:

case ADD_ROLL:
  return state.players.map((player) => {
    if (player.id === action.id) {
      return {
        ...player,
        roll: action.roll,
      }
    }
    return player;
  });
  ...

I am watching state.players in an components like so:

import { connect } from 'pwa-helpers'; // connects a Custom Element base class to the Redux store
...

stateChanged(state) {
   this.players = state.players;
}

render() {
  return html`${this.players.map((player)=> html`
${player.name}
`)}`
}

Now, whenever I call store.dispatch(addRoll(this.roll, this.id)), this.players.map() returns undefined in the component where I am watching state.players.
Any input on why this might happen is much appreciated!

Body:
You have return an array instead of an object with players key in it from state after ADD_ROLL action is dispatched. Correct way to update it would be

case ADD_ROLL:
  return {
    ...state,
    players: state.players.map((player) => {
      if (player.id === action.id) {
        return {
          ...player,
          roll: action.roll,
        }
      }
      return player;
    });
  }
  ...


问:
Should I make my REST client API library Async (Java 8)
I am creating client libraries for our REST server. For the C# library I use HttpClient.PostAsync() which works great, it returns an object that the caller can just wait on (making it synchronous), they can complete some other actions and then wait, or they can use the C# await mechanism. Great solution.

For Java I have to write the library for Java 8, because that's the version in the largest use. With Java 8 we cover 98% of the programmers out there. (If we get enough demand, I'll do a Java 11 one also and then we have native async calls.)

So here's my question, There are ways to get async behavior, either using DeferredResult or some 3rd party classes. But is there any advantage to my building my API around this and forcing it? Because if I create a synchronous API, the caller can still call it in their own DeferredResult code. Which is the same end result.

So it seems to me the way to provide a simple straightforward API is to deliver a synchronous one. And those that want async wrap it up in whatever mechanism they prefer to make it async. An important advantage here is I don't force a mechanism or 3rd party library they don't use on them.

Is there any downside to this approach?

Update: Here it is in more detail.

If all I have is a synchronous API, then the caller can wrap my synchronous API in many different ways. The easiest using vanilla Java 8 is:

```<code>// API is: public Metrics postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = CompletableFuture.supplyAsync(() -> { return client.postMetrics(template); });
</code>```

If instead I create an async API, then I am choosing which of these approaches (I would use CompletableFuture) and so the API becomes:

```<code>// API is: public CompletableFuture<Metrics> postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = client.postMetricsAsync(template);
</code>```

Granted, it's a bit easier with that async API. But very little difference. And the downside is I've now forced the async approach on them. Am I missing some larger advantage of providing  an async API?

答:
Perhaps you should think in these terms, what if tomorrow there is another competing library that provides async behavior out of the box and sync as well ?

If I was a developer, I would perhaps choose the one that allows me the async behavior out of the box and also gives me the options to configure it.

What I have said only makes sense if you are thinking in terms of easy developer adoption and inbuilt ease of making async API calls.

I hope this helps.

Body:
I am creating client libraries for our REST server. For the C# library I use HttpClient.PostAsync() which works great, it returns an object that the caller can just wait on (making it synchronous), they can complete some other actions and then wait, or they can use the C# await mechanism. Great solution.

For Java I have to write the library for Java 8, because that's the version in the largest use. With Java 8 we cover 98% of the programmers out there. (If we get enough demand, I'll do a Java 11 one also and then we have native async calls.)

So here's my question, There are ways to get async behavior, either using DeferredResult or some 3rd party classes. But is there any advantage to my building my API around this and forcing it? Because if I create a synchronous API, the caller can still call it in their own DeferredResult code. Which is the same end result.

So it seems to me the way to provide a simple straightforward API is to deliver a synchronous one. And those that want async wrap it up in whatever mechanism they prefer to make it async. An important advantage here is I don't force a mechanism or 3rd party library they don't use on them.

Is there any downside to this approach?

Update: Here it is in more detail.

If all I have is a synchronous API, then the caller can wrap my synchronous API in many different ways. The easiest using vanilla Java 8 is:

// API is: public Metrics postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = CompletableFuture.supplyAsync(() -> { return client.postMetrics(template); });

If instead I create an async API, then I am choosing which of these approaches (I would use CompletableFuture) and so the API becomes:

// API is: public CompletableFuture<Metrics> postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = client.postMetricsAsync(template);

Granted, it's a bit easier with that async API. But very little difference. And the downside is I've now forced the async approach on them. Am I missing some larger advantage of providing  an async API?


问:
Dialogflow response with parameters
I'm trying to set up Dialogflow interaction with my Go service. Is there any way to use 'formatting' in response?
The perfect solution for me is if I could get some data from my service, let's say the manager's name, and then substitute it as if it was an input parameter.
And use it like this
I know there is a way to process it and compile the answer on my own at webhook but it's not possible with multiple responses where I can substitute the calculated answer.
Is there any way to do it?
Thanks</p>

答:
Yes, but the way you "get some data" from your service is via a webhook.

The webhook, however, can then save values into a Context parameter which can be used with a Response from the UI using the format

```<code>#contextName.parameterName
</code>```

However, once you are using webhooks, it is usually better to do the response formatting there, since it can be much more powerful. You can still randomly pick a response from a list, do other filtering and conditionals, and even adjust the response to correctly handle plurals.

Title: Dialogflow response with parameters

Body:
Yes, but the way you "get some data" from your service is via a webhook.

The webhook, however, can then save values into a Context parameter which can be used with a Response from the UI using the format

#contextName.parameterName

However, once you are using webhooks, it is usually better to do the response formatting there, since it can be much more powerful. You can still randomly pick a response from a list, do other filtering and conditionals, and even adjust the response to correctly handle plurals.


问:
Why does node.js append '0' to my POST request?
Consider the following very simple node.js script:

```<code>http = require('http')

  options =
{
  host:'localhost',
  port:8000,
  method:'POST'
}

req = http.request(options)
req.end()
</code>```

When I tell netcat to listen on port 8000 then execute the script, netcat produces the following:

```<code>POST / HTTP/1.1
Host: localhost:8000
Connection: close
Transfer-Encoding: chunked

0
</code>```

What's with the trailing zero?  Note that this is not an artifact introduced by netcat.

答:
It's using chunked encoding as you can see by the header.
Basically it sends the length of a block of bytes as text followed by that block.
In your case it's sending a zero length block.

This is part of standard http/1.1 see http://en.wikipedia.org/wiki/Chunked_transfer_encoding

Body:
Consider the following very simple node.js script:

http = require('http')

  options =
{
  host:'localhost',
  port:8000,
  method:'POST'
}

req = http.request(options)
req.end()

When I tell netcat to listen on port 8000 then execute the script, netcat produces the following:

POST / HTTP/1.1
Host: localhost:8000
Connection: close
Transfer-Encoding: chunked

0

What's with the trailing zero?  Note that this is not an artifact introduced by netcat.


问:
Firebase Web creating user and write data in Real time database not working correct
Im assuming a strange behaviour while creating an account. I don't have an error to show, but sometimes firebase is not creating the user, sometimes firebase creates the user, but it not writes any data in realtime database. Pls someone help me out..

```<code>function signUp() {

  var userArtistName = document.getElementById("userArtistName").value;
  var userEmail = document.getElementById("userEmail").value;
  var userPassword = document.getElementById("userPassword").value;

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
    var user = firebase.auth().currentUser;
    var uid;
    if (user != null) {
      uid = user.uid;
    }
    var firebaseRef = firebase.database().ref();
    var userData = {
      userArtistName: userArtistName,
      userEmail: userEmail,
      userIsArtist: true,
      userId: uid,
    }
    firebaseRef.child('users/' + uid).set(userData);
    console.log('User successfully created!');
    // code for replace user
  }).catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
}
</code>```

my html form:

```<code><form action="#">
    <h1>Hello Form</h1>
    <span>Register now</span>
    <input type="text" placeholder="Name" id="userArtistName"/>
    <input type="email" placeholder="Email" id="userEmail" />
    <input type="password" placeholder="Password" id="userPassword" />
    <button onclick="signUp()">Registrieren</button>
</form>
</code>```

fb rules:

My firebase.js file:

```<code>// Your web app's Firebase configuration
  var firebaseConfig = {
    //fb config here
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

// Get a reference to firebase authenthification
const auth = firebase.auth();

function signUp() {

  var userArtistName = document.getElementById("userArtistName").value;
  var userEmail = document.getElementById("userEmail").value;
  var userPassword = document.getElementById("userPassword").value;

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
    var user = firebase.auth().currentUser;
    var uid;
    if (user != null) {
      uid = user.uid;
    }
    var firebaseRef = firebase.database().ref();
    var userData = {
      userArtistName: userArtistName,
      userEmail: userEmail,
      userIsArtist: true,
      userId: uid,
    }
    firebaseRef.child('users/' + uid).set(userData);
    console.log('User successfully created!');
    // code for replace user
  }).catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
}

function signIn() {

  var email = document.getElementById("txtEmail");
  var password = document.getElementById("txtPassword");

  auth.signInWithEmailAndPassword(email.value, password.value)
    .then(userCredential => {
      const userId = userCredential.user.uid;
      return firebase.database().ref('/users/' + userId).once('value')
    })
    .then(snapshot => {
      var userIsArtist = snapshot.val().userIsArtist;
      if (!userIsArtist) {
        //Redirect to login or other action or message
        //signOut();
        console.log(userIsArtist);

      } else {
        window.location.replace("main.html");
      }});
    // }).catch((error) => {
    //   // Handle Errors here.
    //   // .catch function to hide error in console. error tells UID actually. We don't want that
    //   var errorCode = error.code;
    //   var errorMessage = error.message;
    // });
}

function signOut() {
  auth.signOut()
  console.log('Successfully signed out!');
  window.location.replace('login.html');
}

auth.onAuthStateChanged(function (user) {
  if (user) {

    let user = firebase.auth().currentUser;
    if(user != null){
      // deactivating loading spinner for people, who are not logged in
      document.getElementById("login-cover").style.display = "none";
    }

    var email = user.email;

    document.getElementById('fb-email').innerHTML = "Welcome User : " + email;
    console.log('Successfully logged in! ---- Active User: ' + email);

  } else if (
    // Not signed in, redirecting to login page
    user == null &&
    window.location.href == 'http://localhost/www.muego.com/main.html' ||
    window.location.href == 'http://localhost/www.muego.com/songs.html') {
    // Redirect user because session is not valid anymore

    window.location.replace('login.html');
  }

});

function resetPassword() {

  var auth = firebase.auth();
  var emailAddress = "admin@trash-mail.com";

  auth.sendPasswordResetEmail(emailAddress).then(function () {
    // Email sent.
  }).catch(function (error) {
    // An error happened.
  });
}
</code>```

答:
after several hours of try and error and with much love and help of @Dharmaraj the final code looks like this:

```<code>  function createAccount(){

    var userEmail = document.getElementById("userEmail").value;
    var userPass = document.getElementById("userPassword").value;
    var userArtistName = document.getElementById("userArtist").value;

    firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).then(function() {
      var user = firebase.auth().currentUser;
      console.log(user);
      var uid;
      if (user != null) {
        uid = user.uid;
        console.log(uid)
        var firebaseRef = firebase.database().ref();
        var userData = {
          userArtistName: userArtistName,
          userEmail: userEmail,
          userIsArtist: true,
          userId: uid,
        }
        firebaseRef.child('users/' + uid).set(userData).then(() => {
          window.location.replace('main.html');
        }).catch();
        console.log('User successfully created!' + 'logged in as:' + userEmail);
    }})
    .catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // ...
    });

  }
</code>```

There where alot of issues  with the redirect actually, so now I placed the replace itself in the promise of the firebaseRef.child and not the createUserWithEmailAndPassword . This made it work!

Body:
Im assuming a strange behaviour while creating an account. I don't have an error to show, but sometimes firebase is not creating the user, sometimes firebase creates the user, but it not writes any data in realtime database. Pls someone help me out..

function signUp() {

  var userArtistName = document.getElementById("userArtistName").value;
  var userEmail = document.getElementById("userEmail").value;
  var userPassword = document.getElementById("userPassword").value;

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
    var user = firebase.auth().currentUser;
    var uid;
    if (user != null) {
      uid = user.uid;
    }
    var firebaseRef = firebase.database().ref();
    var userData = {
      userArtistName: userArtistName,
      userEmail: userEmail,
      userIsArtist: true,
      userId: uid,
    }
    firebaseRef.child('users/' + uid).set(userData);
    console.log('User successfully created!');
    // code for replace user
  }).catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
}

my html form:

<form action="#">

Hello Form

    Register now
    <input type="text" placeholder="Name" id="userArtistName"/>
    <input type="email" placeholder="Email" id="userEmail" />
    <input type="password" placeholder="Password" id="userPassword" />
    <button onclick="signUp()">Registrieren</button>
</form>

fb rules:

My firebase.js file:

// Your web app's Firebase configuration
  var firebaseConfig = {
    //fb config here
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

// Get a reference to firebase authenthification
const auth = firebase.auth();

function signUp() {

  var userArtistName = document.getElementById("userArtistName").value;
  var userEmail = document.getElementById("userEmail").value;
  var userPassword = document.getElementById("userPassword").value;

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
    var user = firebase.auth().currentUser;
    var uid;
    if (user != null) {
      uid = user.uid;
    }
    var firebaseRef = firebase.database().ref();
    var userData = {
      userArtistName: userArtistName,
      userEmail: userEmail,
      userIsArtist: true,
      userId: uid,
    }
    firebaseRef.child('users/' + uid).set(userData);
    console.log('User successfully created!');
    // code for replace user
  }).catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
}

function signIn() {

  var email = document.getElementById("txtEmail");
  var password = document.getElementById("txtPassword");

  auth.signInWithEmailAndPassword(email.value, password.value)
    .then(userCredential => {
      const userId = userCredential.user.uid;
      return firebase.database().ref('/users/' + userId).once('value')
    })
    .then(snapshot => {
      var userIsArtist = snapshot.val().userIsArtist;
      if (!userIsArtist) {
        //Redirect to login or other action or message
        //signOut();
        console.log(userIsArtist);

      } else {
        window.location.replace("main.html");
      }});
    // }).catch((error) => {
    //   // Handle Errors here.
    //   // .catch function to hide error in console. error tells UID actually. We don't want that
    //   var errorCode = error.code;
    //   var errorMessage = error.message;
    // });
}

function signOut() {
  auth.signOut()
  console.log('Successfully signed out!');
  window.location.replace('login.html');
}

auth.onAuthStateChanged(function (user) {
  if (user) {

    let user = firebase.auth().currentUser;
    if(user != null){
      // deactivating loading spinner for people, who are not logged in
      document.getElementById("login-cover").style.display = "none";
    }

    var email = user.email;

    document.getElementById('fb-email').innerHTML = "Welcome User : " + email;
    console.log('Successfully logged in! ---- Active User: ' + email);

  } else if (
    // Not signed in, redirecting to login page
    user == null &&
    window.location.href == 'http://localhost/www.muego.com/main.html' ||
    window.location.href == 'http://localhost/www.muego.com/songs.html') {
    // Redirect user because session is not valid anymore

    window.location.replace('login.html');
  }

});

function resetPassword() {

  var auth = firebase.auth();
  var emailAddress = "admin@trash-mail.com";

  auth.sendPasswordResetEmail(emailAddress).then(function () {
    // Email sent.
  }).catch(function (error) {
    // An error happened.
  });
}

Body:
after several hours of try and error and with much love and help of @Dharmaraj the final code looks like this:

  function createAccount(){

    var userEmail = document.getElementById("userEmail").value;
    var userPass = document.getElementById("userPassword").value;
    var userArtistName = document.getElementById("userArtist").value;

    firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).then(function() {
      var user = firebase.auth().currentUser;
      console.log(user);
      var uid;
      if (user != null) {
        uid = user.uid;
        console.log(uid)
        var firebaseRef = firebase.database().ref();
        var userData = {
          userArtistName: userArtistName,
          userEmail: userEmail,
          userIsArtist: true,
          userId: uid,
        }
        firebaseRef.child('users/' + uid).set(userData).then(() => {
          window.location.replace('main.html');
        }).catch();
        console.log('User successfully created!' + 'logged in as:' + userEmail);
    }})
    .catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // ...
    });

  }

There where alot of issues  with the redirect actually, so now I placed the replace itself in the promise of the firebaseRef.child and not the createUserWithEmailAndPassword . This made it work!