问:
Launching Jupyter Notebook on localhost results in '[Errno 49] Can't assign requested address', however ip=127.0.0.1 works
When attempting to launch a Jupyter Notebook I get the following error

```<code>$ Jupyter Notebook
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/bin/jupyter-notebook", line 11, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/jupyter_core/application.py", line 268, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/traitlets/config/application.py", line 663, in launch_instance
    app.initialize(argv)
  File "</Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/decorator.py:decorator-gen-7>", line 2, in initialize
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/traitlets/config/application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/notebook/notebookapp.py", line 1720, in initialize
    self.init_webapp()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/notebook/notebookapp.py", line 1482, in init_webapp
    self.http_server.listen(port, self.ip)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tornado/tcpserver.py", line 151, in listen
    sockets = bind_sockets(port, address=address)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tornado/netutil.py", line 174, in bind_sockets
    sock.bind(sockaddr)
OSError: [Errno 49] Can't assign requested address
</code>```

However, when I specify the ip address of 127.0.0.1 (i.e. not 'localhost'), Jupyter Notebook --ip=127.0.0.1 it works perfectly fine.

Also, when I ping localhost it returns that local host is in fact 127.0.0.1.

```<code>$ ping localhost
PING localhost.localdomain (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.034 ms
</code>```

I've checked both etc/hosts and private/etc/hosts, and neither specify a localhost (or anything for that matter).

I am trying to fix this issue as I run Jupyter Notebooks in PyCharm and you can't create a simple shortcut to just run on 127.0.0.1 vice 'localhost'. (No simple shortcut I'm aware of, correct me if I'm wrong)  I can launch on 127.0.0.1 in Pycharm, but it takes multiple steps and is burdensome.  I just want this to work via its intended configuration of 'localhost' as the default.

答:
Answer credited to @jackw11111

Generate a config file for your jupyter notebook

```<code>$ jupyter notebook --generate-config
</code>```

Jump into this new config file with your favorite editor

```<code>$ nano ~/.jupyter/jupyter_notebook_config.py
</code>```

Add the following line to the file to make this the default server to listen on

```<code>c.NotebookApp.ip = '127.0.0.1'
</code>```

Body:
When attempting to launch a Jupyter Notebook I get the following error

$ Jupyter Notebook
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/bin/jupyter-notebook", line 11, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/jupyter_core/application.py", line 268, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/traitlets/config/application.py", line 663, in launch_instance
    app.initialize(argv)
  File "</Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/decorator.py:decorator-gen-7>", line 2, in initialize
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/traitlets/config/application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/notebook/notebookapp.py", line 1720, in initialize
    self.init_webapp()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/notebook/notebookapp.py", line 1482, in init_webapp
    self.http_server.listen(port, self.ip)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tornado/tcpserver.py", line 151, in listen
    sockets = bind_sockets(port, address=address)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tornado/netutil.py", line 174, in bind_sockets
    sock.bind(sockaddr)
OSError: [Errno 49] Can't assign requested address

However, when I specify the ip address of 127.0.0.1 (i.e. not 'localhost'), Jupyter Notebook --ip=127.0.0.1 it works perfectly fine.

Also, when I ping localhost it returns that local host is in fact 127.0.0.1.

$ ping localhost
PING localhost.localdomain (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.034 ms

I've checked both etc/hosts and private/etc/hosts, and neither specify a localhost (or anything for that matter).

I am trying to fix this issue as I run Jupyter Notebooks in PyCharm and you can't create a simple shortcut to just run on 127.0.0.1 vice 'localhost'. (No simple shortcut I'm aware of, correct me if I'm wrong)  I can launch on 127.0.0.1 in Pycharm, but it takes multiple steps and is burdensome.  I just want this to work via its intended configuration of 'localhost' as the default.

Body:
Answer credited to @jackw11111

Generate a config file for your jupyter notebook

$ jupyter notebook --generate-config

Jump into this new config file with your favorite editor

$ nano ~/.jupyter/jupyter_notebook_config.py

Add the following line to the file to make this the default server to listen on

c.NotebookApp.ip = '127.0.0.1'


来源: stackexchange

问:
Using SignalR via reflection
I am developing an asp.net core 3.1 application that loads up an assembly using Application Parts and reflection. This plugin assembly is also an asp.net core 3.1 application which is all working fine except it also has SignalR functionality within it. In the host application I have the service registered in Startup.cs like this:-

```<code>services.AddSignalR();
</code>```

In the Configure method I would normally have something like this:-

```<code>endpoints.MapHub<MyHub>("/myHub");
</code>```

But MyHub is a class from the plugin assembly. How can I map the hub when it could be of any type? I don't want to have this MyHub class in the host application, it can only be in the plugin application.

答:
In your solution, you can create new .NET Core Library project which is referred to the main project.

In the library project, you can add this Nuget package:

```<code>Microsoft.AspNetCore.SignalR.Core
</code>```

Then, creating your Hub class from there and mapping it from the Startup class.

ContentLicense: CC BY-SA 4.0

Title: Using SignalR via reflection

Body:
I am developing an asp.net core 3.1 application that loads up an assembly using Application Parts and reflection. This plugin assembly is also an asp.net core 3.1 application which is all working fine except it also has SignalR functionality within it. In the host application I have the service registered in Startup.cs like this:-

services.AddSignalR();

In the Configure method I would normally have something like this:-

endpoints.MapHub<MyHub>("/myHub");

But MyHub is a class from the plugin assembly. How can I map the hub when it could be of any type? I don't want to have this MyHub class in the host application, it can only be in the plugin application.

Body:
In your solution, you can create new .NET Core Library project which is referred to the main project.

In the library project, you can add this Nuget package:

Microsoft.AspNetCore.SignalR.Core

Then, creating your Hub class from there and mapping it from the Startup class.


问:
Knitr cannot find img files in /static/ folder
I have a hugo-academic website (methods101.com) that has been working well for last year.

I just went to edit some pages and I've started getting a new error.

The code that seems to be creating the problems is the knitr::include_graphics() function.

This is an example of the text that produces an error:

```<code>{r, echo=FALSE, out.width=600,
fig.cap="Newspaper article in Word document, next to same article on internet.",
fig.align='center'}

knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png")
</code>```

This is the error message:

```<code>Rendering content/docs/SOC224_qual_analysis_eg.Rmd
Quitting from lines 80-81 (SOC224_qual_analysis_eg.Rmd)
Error in knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png") :
  Cannot find the file(s): "/img/soc224_qual_analysis_eg_figure_1.png"
Calls: local ... withCallingHandlers -> withVisible -> eval -> eval -> <Anonymous>
Execution halted
<simpleError in render_page(f): Failed to render 'content/docs/SOC224_qual_analysis_eg.Rmd'>
</code>```

I get the same problem on different computers, and after fresh re-installing/downloading the website contents.

The image file is definitely inside the folder:

/static/img/

答:
You may see the help page ?knitr::include_graphics. In your case, you need

knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png", error = FALSE)
```

Body:
I have a hugo-academic website (methods101.com) that has been working well for last year.

I just went to edit some pages and I've started getting a new error.

The code that seems to be creating the problems is the knitr::include_graphics() function.

This is an example of the text that produces an error:

{r, echo=FALSE, out.width=600,
fig.cap="Newspaper article in Word document, next to same article on internet.",
fig.align='center'}

knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png")

This is the error message:

Rendering content/docs/SOC224_qual_analysis_eg.Rmd
Quitting from lines 80-81 (SOC224_qual_analysis_eg.Rmd)
Error in knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png") :
  Cannot find the file(s): "/img/soc224_qual_analysis_eg_figure_1.png"
Calls: local ... withCallingHandlers -> withVisible -> eval -> eval -> <Anonymous>
Execution halted
<simpleError in render_page(f): Failed to render 'content/docs/SOC224_qual_analysis_eg.Rmd'>

I get the same problem on different computers, and after fresh re-installing/downloading the website contents.

The image file is definitely inside the folder:

/static/img/


问:
Integrating Flutter app facebook authentication with Keycloak service
I have a Flutter app that is using Keycloak as it's authentication service.
Currently I only allow email+password login, and i would like to add option for the users to login using Facebook.

My question is how do i link the facebook login with my Keycloak service so that my service would manage the access tokens.

I found this very nice library for flutter facebook login: https://pub.dev/packages/flutter_facebook_login

I'm using Java Spring web service proxy between the app and the Keycloak service.
I'm using org.keycloak:keycloak-admin-client:6.0.1 library for the Keycloak client.

I would like to understand the flow of control that should take place so the user can login to his facebook account , and then my Keycloak service would manage it's access token so i can authenticate the user in my other services, which are all relying on the fact that Keycloak validates the access token.

Any suggestion would help , thanks ahead !

答:
Keycloak has a built in Facebook Identity Provider and makes it very easy to do this. Here is a link to Keycloak's Documentation which has a step by step on setting it up:
https://www.keycloak.org/docs/6.0/server_admin/#facebook

Here are the steps that are listed in the docs (copied and lightly modified because i'm not posting any pictures here).

*** FROM KEYCLOAK DOCS **

There are a number of steps you have to complete to be able to enable login with Facebook. First, go to the Identity Providers left menu item and select Facebook from the Add provider drop down list. This will bring you to the Add identity provider page.

You can’t click save yet, as you’ll need to obtain a Client ID and Client Secret from Facebook. One piece of data you’ll need from this page is the Redirect URI. You’ll have to provide that to Facebook when you register Keycloak as a client there, so copy this URI to your clipboard.

To enable login with Facebook you first have to create a project and a client in the Facebook Developer Console.

Once you’ve logged into the console there is a pull down menu in the top right corner of the screen that says My Apps. Select the Add a New App menu item.

Select a platform. Click the Skip and Create App ID button.

The email address and app category are required fields. Once you’re done with that, you will be brought to the dashboard for the application. Click the Settings left menu item.

Click on the + Add Platform button at the end of this page and select the Website icon. Copy and paste the Redirect URI from the Keycloak Add identity provider page into the Site URL of the Facebook Website settings block.

After this it is necessary to make the Facebook app public. Click App Review left menu item and switch button to "Yes".

You will need also to obtain the App ID and App Secret from this page so you can enter them into the Keycloak Add identity provider page. To obtain this click on the Dashboard left menu item and click on Show under App Secret. Go back to Keycloak and specify those items and finally save your Facebook Identity Provider.

One config option to note on the Add identity provider page for Facebook is the Default Scopes field. This field allows you to manually specify the scopes that users must authorize when authenticating with this provider. For a complete list of scopes, please take a look at https://developers.facebook.com/docs/graph-api. By default, Keycloak uses the following scopes: email.


问:
Express ENOENT: no such file or directory, stat '/index.html'
I'm having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default.

import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';

// Create express server
const app = express();

// Add middleware
app.use(helmet());
app.use(morgan('combined'));

// Define API routes
app.get('/api/', home.get);

// Configure environment settings
if (ENVIRONMENT === 'development') {
    // ...
} else {
    // Configure Static Files (Production)
    app.use(express.static("./"));

    // Serve React Static Files (Production)
    app.get('*', (req: Request, res: Response) => {
        res.sendFile(path.resolve(__dirname, "/index.html"));
    });
}

// Start server
app.listen(PORT, () => {
    console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});

export default app;
module.exports = app;
```

<p>Basically I go to localhost:8080 and my app renders just fine. <strong>However</strong> when I go to localhost:8080/login I get the following response from the server:</p>

<pre class="lang-sh prettyprint-override"><code>Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
</code>```

Here are the morgan logs:

::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

```

<p>Why does it render my app on <code>localhost:8080</code> but not <code>localhost:8080/login</code></p>

<p>Dist Folder:</p>

```dist
  img
  app.bundle.js
  index.html
  server.bundle.js
```

答:
Create a folder build and copy the build files into this folder

Set the build folder to static

```<code>app.use(express.static(path.join(__dirname, 'build')));
</code>```

Then

```<code>app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
</code>```

Body:
I'm having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default.

import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';

// Create express server
const app = express();

// Add middleware
app.use(helmet());
app.use(morgan('combined'));

// Define API routes
app.get('/api/', home.get);

// Configure environment settings
if (ENVIRONMENT === 'development') {
    // ...
} else {
    // Configure Static Files (Production)
    app.use(express.static("./"));

    // Serve React Static Files (Production)
    app.get('*', (req: Request, res: Response) => {
        res.sendFile(path.resolve(__dirname, "/index.html"));
    });
}

// Start server
app.listen(PORT, () => {
    console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});

export default app;
module.exports = app;

Basically I go to localhost:8080 and my app renders just fine. However when I go to localhost:8080/login I get the following response from the server:

Error: ENOENT: no such file or directory, stat '/index.html'
/index.html

Here are the morgan logs:

::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

Why does it render my app on localhost:8080 but not localhost:8080/login

Dist Folder:

dist
  img
  app.bundle.js
  index.html
  server.bundle.js

Body:
Create a folder build and copy the build files into this folder

Set the build folder to static

app.use(express.static(path.join(__dirname, 'build')));

Then

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


问:
How do I refresh all connected clients using Scaledrone?
I own a website where it is a chatroom that most of my school uses to talk. There are some annoying spammers and just recently I made a way to ban them but they have to refresh. Is there any way I can make a way  to refresh everyones screen who is on my website and have the spammer banned? It would also be useful to use this and refresh everyone when I release an update.

Is there a way to do this using Scaledrone, which is the library that I am using?

答:
Yes, you can. If you are using Scaledrone, you can listen for a specific message and in the handler code call location.reload().

From the Scaledrone link above. You need to modify this to work with whatever setup you have. Did you write the code for the chat site?

```<code>// Subscribe after the 'open' or 'authenticate' event from the Scaledrone instance
const room = drone.subscribe('room_name');

room.on('message', message => {
  // Received message from room
    const {data, id, timestamp, clientId, member} = message;
   if (member.id === myId && message ==='expelliarmus') {
      location.reload()
  }
});
</code>```

Body:
Yes, you can. If you are using Scaledrone, you can listen for a specific message and in the handler code call location.reload().

From the Scaledrone link above. You need to modify this to work with whatever setup you have. Did you write the code for the chat site?

// Subscribe after the 'open' or 'authenticate' event from the Scaledrone instance
const room = drone.subscribe('room_name');

room.on('message', message => {
  // Received message from room
    const {data, id, timestamp, clientId, member} = message;
   if (member.id === myId && message ==='expelliarmus') {
      location.reload()
  }
});


问:
Jsp unscrollable and fix menu
In my JSP page There is a menu with 14 options in the left side and menu description at the right side. I have created hyperlink in the same page on the menu click. Menu description has lengthy stuff. And the size of the page is much more than the menu. My problem is when I click on any menu item at left excluding first menu item the page scrolls down and menu disappears. Is there can be any way to make the left side (menu) unscrollable, and fixed in the position. Only The right side of the page will scroll. Thanks.</p>

答:
There are several ways:

make left div position:fixed

make height of right div fix and give overflow:auto

ContentLicense: CC BY-SA 3.0

Title: Jsp unscrollable and fix menu


问:
Writing a class in javascript
I want to create a class based on this object structure:

```<code>var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2)
</code>```

Basically, I want to be able to access the object contents via this style since I will be working a lot on parameter modifications:

ourStorage[accessStr][drawerPart].folder2

So my questions are:

How do I convert this to class while maintaining this kind of structure? Is it possible?

If I want to insert another item/object (e.g. variableItem3) - how do I do that?

If I also want to insert another item/object on the deeper level (e.g. middle drawer), how do I also do that?

Thanks much!!

答:
There are a number of ways you can turn that into a class, but if you want to interact with it as if it's json (dot or bracket notation) then I'd say keep it as json and just make a class for interacting with the stored structure.

In the snippet, I made a storage class that let's you pass in json as a staring structure.

we then give this class 2 methods: get and update.

update will let you slap in any new node, wherever you want (you could add a new variableItem5 with drawers, folders, cabinets and wardrobes with as many nested nodes as you want)

then with the get method you can use the bracket notation like you're looking for:

```<code>console.log(os.get[accessStr][drawerPart]);
</code>```

var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'

class OurStorage{
    constructor(startingStorage = {}){
        this.storage = startingStorage;
    }
    get get(){
        return JSON.parse(JSON.stringify(this.storage));
    }
    update(store = {}){
        this.storage = $.extend(true, this.storage, store);
    }
}

var os = new OurStorage(ourStorage);
console.log(os.get[accessStr]);
console.log(os.get[accessStr][drawerPart]);
os.update({"variableItem2": {
    "secretBananaFolder":{"id":"bananas"}
}});

console.log(os.get[accessStr]);

os.update({"variableItem3": {
    "top drawer": {
      "folder1": "",
      "folder2": "Awesome!"
    },
    "bottom drawer": ""
}});

accessStr = "variableItem3";

console.log(os.get[accessStr][drawerPart]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Writing a class in javascript

Body:
I want to create a class based on this object structure:

var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2)

Basically, I want to be able to access the object contents via this style since I will be working a lot on parameter modifications:

ourStorage[accessStr][drawerPart].folder2

So my questions are:

How do I convert this to class while maintaining this kind of structure? Is it possible?

If I want to insert another item/object (e.g. variableItem3) - how do I do that?

If I also want to insert another item/object on the deeper level (e.g. middle drawer), how do I also do that?

Thanks much!!

Body:
There are a number of ways you can turn that into a class, but if you want to interact with it as if it's json (dot or bracket notation) then I'd say keep it as json and just make a class for interacting with the stored structure.

In the snippet, I made a storage class that let's you pass in json as a staring structure.

we then give this class 2 methods: get and update.

update will let you slap in any new node, wherever you want (you could add a new variableItem5 with drawers, folders, cabinets and wardrobes with as many nested nodes as you want)

then with the get method you can use the bracket notation like you're looking for:

console.log(os.get[accessStr][drawerPart]);

var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'

class OurStorage{
    constructor(startingStorage = {}){
        this.storage = startingStorage;
    }
    get get(){
        return JSON.parse(JSON.stringify(this.storage));
    }
    update(store = {}){
        this.storage = $.extend(true, this.storage, store);
    }
}

var os = new OurStorage(ourStorage);
console.log(os.get[accessStr]);
console.log(os.get[accessStr][drawerPart]);
os.update({"variableItem2": {
    "secretBananaFolder":{"id":"bananas"}
}});

console.log(os.get[accessStr]);

os.update({"variableItem3": {
    "top drawer": {
      "folder1": "",
      "folder2": "Awesome!"
    },
    "bottom drawer": ""
}});

accessStr = "variableItem3";

console.log(os.get[accessStr][drawerPart]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
How can I use GitLab pages to host webpages with a user input form, which updates a GitLab repo when saved?
I know that GitLab pages is made to host static pages rather than dynamic but I'm not too clear on the borderlines between static and dynamic and whether there are different levels of how dynamic a webpage actually is.

I'm wondering if GitLab pages can be used to host a webpage that:

A) shows content from yaml files in a gitlab repo (in which case I imagine the html file for the webpage would be inside or alongside that repo?)

B) has a form on the webpage with user input boxes such that when this form is saved/sent, the aforementioned GitLab repo is updated.

If this is possible, how would I do this?
If this is not possible then do you have any recommendations about doing this?

Thanks for reading, Milan

答:
There is no secure way to do what you want from a static site.  In order to write to your repository, you have to have some sort of credentials.  With a static site, those credentials would have to be embedded in the page, so anyone who could download the page could make arbitrary modifications to your repository.  Static sites don't allow the submission of forms to a backend, because there is no backend, only the fixed HTML, CSS, and JavaScript that are downloaded by the user's browser.

In order to securely make this work, you need to have a web server of some sort hosting a backend service written in the language of your choice.  It can then hold credentials that can operate on a repository or database, and accept forms or API requests submitted by a user.  You could also use a Google Form or some other content and then extract the data and periodically embed it into your repo or elsewhere.


问:
Xcode force me to use contains(where:) instead of contains()
I wanna check if in an array have already contained an item or not so I use to like this:

```<code>let fItem = FilterItem(key: String(describing: key), value: valueStr)
if self.filter?.filters?.contains(fItem){
    //remove the item if contains, append if not
}
</code>```

For more information, the self.filter?.filters? is an array:

```<code>var filters: [FilterItem]? = []
</code>```

And the FilterItem is a struct:

```<code>struct FilterItem {
    var key: String;
    var value: String;
}
</code>```

But Xcode forced me to use contains(where:..) instead of contains() with error: Missing argument label 'where:' in call. Why?

答: You can't use contains(_) because the array of FilterItem objects doesn't conform to protocol Equatable. This question and its answers should help explain it. Basically, the array elements cannot directly be compared with one another using ==, so they don't conform to Equatable.

Body:
I wanna check if in an array have already contained an item or not so I use to like this:

let fItem = FilterItem(key: String(describing: key), value: valueStr)
if self.filter?.filters?.contains(fItem){
    //remove the item if contains, append if not
}

For more information, the self.filter?.filters? is an array:

var filters: [FilterItem]? = []

And the FilterItem is a struct:

struct FilterItem {
    var key: String;
    var value: String;
}

But Xcode forced me to use contains(where:..) instead of contains() with error: Missing argument label 'where:' in call. Why?


问:
'mvn' is not recognized as an internal or external command, operable program or batch file
May be question is asked before but i found very strange kind of error.
When I run mvn --version command from bin its gives the version and the other information. However when I run outside bin it gives exception. Both the result mention below

```<code>C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin>mvn --version
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:
28+0530)
Maven home: C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5>mvn --version
'mvn' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Also i set JAVA_HOME in user variable and M2_HOME, M2 in system environment variable. The output for these variables and %path% is:

```<code>C:\Users\SAHILBHALLA>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.7.0_25

C:\Users\SAHILBHALLA>echo %M2%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin

C:\Users\SAHILBHALLA>echo %M2_HOME%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5

C:\Users\SAHILBHALLA>echo %path%
C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPow erShell\v1.0\;C:\Program Files\Java\jdk1.7.0_25\bin;.;
</code>```

Tell me where i am wrong. What should i do recover from it?

答:
I did all of this in Windows 10 and still had a problem. In the end it turned out that
the path to the Maven home folder was not exactly what was expected in many of these answers as it turned out to be /apache-maven-3.6.3-bin/apache-maven-3.6.3. Once I corrected this for both the system variables and the PATH variable, it worked. In short, if you have set the environment variables up as directed and it still won't work, I would double check to make sure the variables really point to the exact path to the Maven home folder and the bin folder on your machine. </p>

Body:
May be question is asked before but i found very strange kind of error.
When I run mvn --version command from bin its gives the version and the other information. However when I run outside bin it gives exception. Both the result mention below

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin>mvn --version
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:
28+0530)
Maven home: C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5>mvn --version
'mvn' is not recognized as an internal or external command,
operable program or batch file.

Also i set JAVA_HOME in user variable and M2_HOME, M2 in system environment variable. The output for these variables and %path% is:

C:\Users\SAHILBHALLA>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.7.0_25

C:\Users\SAHILBHALLA>echo %M2%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin

C:\Users\SAHILBHALLA>echo %M2_HOME%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5

C:\Users\SAHILBHALLA>echo %path%
C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPow erShell\v1.0\;C:\Program Files\Java\jdk1.7.0_25\bin;.;

Tell me where i am wrong. What should i do recover from it?


问:
T4 Template File doesn't compile VS2019 V16.4.5
I have a T4 Template file in my project and I use it everyday but after upgrade into 16.4.5 version I'm getting this error when I Run Custom Code:

Severity  Code    Description Project File    Line    Suppression State
  Error     Running transformation:
  System.Runtime.InteropServices.COMException (0x80004005): Error
  HRESULT E_FAIL has been returned from a call to a COM component.    at
  System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
  errorCode, IntPtr errorInfo)    at
  Microsoft.VisualStudio.LanguageServices.Implementation.Utilities.Exceptions.ThrowEFail()
  at
  Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.FileCodeModel.GetDocument()
  at
  Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.FileCodeModel.GetSyntaxTree()
  at
  Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.FileCodeModel..ctor(CodeModelState
  state, Object parent, DocumentId documentId, ITextManagerAdapter
  textManagerAdapter)    at
  Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.CodeModelProjectCache.GetOrCreateFileCodeModel(String
  filePath, Object parent)    at
  Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ProjectCodeModel.Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.IProjectCodeModel.GetOrCreateFileCodeModel(String
  filePath, Object parent)    at
  Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.CSharpProjectShim.CreateFileCodeModel(String
  fileName, Object parent, FileCodeModel& ppFileCodeModel)    at
  EnvDTE.ProjectItem.get_FileCodeModel()    at
  Microsoft.VisualStudio.TextTemplatingA79231EE6EFCFD9A9F7580CC47D516BF0E336BDEE9E25B0EE85E3BDE9AA5F22021A94E93566B81968DF5D01D105C4011D1E60A396DC22B9D70AA7669950944CC.GeneratedTextTransformation.d__7.MoveNext()
  in XXX\SecurityKeys.tt:line 134    at
  Microsoft.VisualStudio.TextTemplatingA79231EE6EFCFD9A9F7580CC47D516BF0E336BDEE9E25B0EE85E3BDE9AA5F22021A94E93566B81968DF5D01D105C4011D1E60A396DC22B9D70AA7669950944CC.GeneratedTextTransformation.d__6.MoveNext()
  in XXX\SecurityKeys.tt:line 127    at
  Microsoft.VisualStudio.TextTemplatingA79231EE6EFCFD9A9F7580CC47D516BF0E336BDEE9E25B0EE85E3BDE9AA5F22021A94E93566B81968DF5D01D105C4011D1E60A396DC22B9D70AA7669950944CC.GeneratedTextTransformation.TransformText()
  in XXX\SecurityKeys.tt:line 48    MYPROJECT   XXX\SecurityKeys.tt 134

I tested the same file in my colleague's workstation with previous version of VS and it worked.

答: just exclude all project files and folders then include them again! it works</p>


问:
How to improve write performance in DolphinDB?
I am performing various computations on DolphinDB, the speed are pretty good enough. But I am having an roadblock with the write performance in DolphinDB because my data have thousands of columns, it takes a few seconds to write 100 records. How can I improve it?</p>

答:
Have you tried cache engine in DolphinDB? This should work for your case. To enable cache engine, please add one line setup in configuration file as follows</p>

```<code>//in unit of GB
chunkCacheEngineMemSize = 2
</code>```

Body:
Have you tried cache engine in DolphinDB? This should work for your case. To enable cache engine, please add one line setup in configuration file as follows

//in unit of GB
chunkCacheEngineMemSize = 2


问:
SwiftUI how to update newly selected images to cells
I'm making an iOS app and I want to display some sort of default image (or just blank) in a row view, and then update them to new selected images by users. How the app currently looks like
How can I update the images in the cells to be the new ones users select?

This is how I am creating the row views and cells

```<code>import SwiftUI

struct Row: Identifiable {
    let id = UUID()
    let cells: [Cell]
}

extension Row {

}

extension Row {

    static func all() -> [Row] {
        var resultRow = [Row]()

        for _ in 1...10 {
            resultRow.append(Row(cells: [Cell(imageURL: "camera"), Cell(imageURL: "camera")]))
        }

        return resultRow
    }
}

struct Cell: Identifiable {
    let id = UUID()
    let imageURL: String
}

</code>```

And my UIView looks like this

```<code>import SwiftUI

struct PhotoUIView: View {
    @State private var showImagePicker: Bool = false
    @State private var image: Image? = nil

    let rows = Row.all()

    var body: some View {

        VStack{

            List {
                ForEach(rows) { row in
                    HStack(alignment: .center) {
                        ForEach(row.cells) { cell in
                            Image(cell.imageURL)
                                .resizable()
                                .scaledToFit()
                        }
                    }
                }
            }.padding(EdgeInsets.init(top: 0, leading: -20, bottom: 0, trailing: -20))

            image?.resizable()
                .scaledToFit()
            if (image == nil) {
                Text("Upload photo to begin quick design")
            }

            Button("Select photo to upload") {
                self.showImagePicker = true
            }.padding()
                .background(Color.blue)
                .foregroundColor(Color.white)
                .cornerRadius(10)

            Button("Begin Quick Design") {
                print("Here we upload photo and get result back")
            }.padding()
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(10)

        }.sheet(isPresented: self.$showImagePicker) {
            PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
        }
    }
}

struct PhotoUIView_Previews: PreviewProvider {
    static var previews: some View {
        PhotoUIView()
    }
}

</code>```

答: So you can do is, creaate an array of images and add those selected images with name like image_0, image_1, and so on. And then add the images in the cell using the array eg a[i]</p>

Body:
I'm making an iOS app and I want to display some sort of default image (or just blank) in a row view, and then update them to new selected images by users. How the app currently looks like
How can I update the images in the cells to be the new ones users select?

This is how I am creating the row views and cells

import SwiftUI

struct Row: Identifiable {
    let id = UUID()
    let cells: [Cell]
}

extension Row {

}

extension Row {

    static func all() -> [Row] {
        var resultRow = [Row]()

        for _ in 1...10 {
            resultRow.append(Row(cells: [Cell(imageURL: "camera"), Cell(imageURL: "camera")]))
        }

        return resultRow
    }
}

struct Cell: Identifiable {
    let id = UUID()
    let imageURL: String
}

And my UIView looks like this

import SwiftUI

struct PhotoUIView: View {
    @State private var showImagePicker: Bool = false
    @State private var image: Image? = nil

    let rows = Row.all()

    var body: some View {

        VStack{

            List {
                ForEach(rows) { row in
                    HStack(alignment: .center) {
                        ForEach(row.cells) { cell in
                            Image(cell.imageURL)
                                .resizable()
                                .scaledToFit()
                        }
                    }
                }
            }.padding(EdgeInsets.init(top: 0, leading: -20, bottom: 0, trailing: -20))

            image?.resizable()
                .scaledToFit()
            if (image == nil) {
                Text("Upload photo to begin quick design")
            }

            Button("Select photo to upload") {
                self.showImagePicker = true
            }.padding()
                .background(Color.blue)
                .foregroundColor(Color.white)
                .cornerRadius(10)

            Button("Begin Quick Design") {
                print("Here we upload photo and get result back")
            }.padding()
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(10)

        }.sheet(isPresented: self.$showImagePicker) {
            PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
        }
    }
}

struct PhotoUIView_Previews: PreviewProvider {
    static var previews: some View {
        PhotoUIView()
    }
}


问:
cannot get the relationship data in laravel
this is my function

```<code>public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }
</code>```

newproject model

```<code>public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }
</code>```

it always getting the error

```<code>message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
</code>```

please help my to solve my problem please.

答:
Check the relationship one-to-one reference
The foreign_key user_id is in newprojects table, you need to build the relationship like this:

User model:

public function newproject()
{
   return $this->hasOne(Newproject::class,'user_id');
}
```

<p>newproject model:</p>

<pre class="lang-php prettyprint-override"><code>public function user()
{
   return $this->belongsTo(User::class);
}
</code>```

Body:
this is my function

public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }

newproject model

public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }

it always getting the error

message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669

please help my to solve my problem please.

Body:
Check the relationship one-to-one reference
The foreign_key user_id is in newprojects table, you need to build the relationship like this:

User model:

public function newproject()
{
   return $this->hasOne(Newproject::class,'user_id');
}

newproject model:

public function user()
{
   return $this->belongsTo(User::class);
}


问:
Objective-C Frameworks and namespace clashes
We want to put 2 versions of our iOS app in the same bundle. This way our customers could revert to the legacy version after an update has been pushed. I had hoped to achieve this by building the current and previous versions into frameworks and calling the appropriate version after prompting the user.

As a test I've created two Frameworks, LibA & LibB, each containing class Thing.

The problem I'm encountering is this runtime warning...

objc[21117]: Class Thing is implemented in both /private/var/containers/Bundle/Application/0E6374C5-52FB-421F-90D6-ADC9A4C22B5D/DualBootTestApp.app/Frameworks/LibA.framework/LibA (0x102b144b0) and /private/var/containers/Bundle/Application/0E6374C5-52FB-421F-90D6-ADC9A4C22B5D/DualBootTestApp.app/Frameworks/LibB.framework/LibB (0x102ba4460). One of the two will be used. Which one is undefined.

In the real world, these Frameworks would be two versions of the same app, so 99% of the class names are going to be identical in each.

Each Framework does actually call its own version of Thing, but the runtime warning suggests to me I can't rely on that behaviour.

Update

I've just tried using a Cocoa Touch Static Library instead. With a static library I don't get the runtime warning, but the version of class Thing from LibB is always called, even when the call originates from LibA.

I'm starting to believe some kind of macro prefixing the objective c class names might be the only solution. Lots of shared code makes this a grim prospect.

Does anyone know a way I can hide the class names so only each Framework has visibility of its own classes?

Is there a better approach to adding two versions of an app into the same bundle? Is it even possible? Would there be issues with Appstore review?

答:
If you've already made your classes into frameworks, congrats, you've done the hard part already. Bear in mind, however, that if much of your application code is in a framework, some things might not behave as expected. For instance, any code that ultimately calls NSBundle.mainBundle (eg +[UIImage imageNamed:]) is probably wrong, assuming you've versioned your assets as well.

But let's assume that you've successfully framework-ized your app versions.

You can't link against either framework if you want to choose one of them at runtime. Instead, you need to use dlopen and NSClassFromString or dlsym to reach an entry point.

Here's an example:

```<code>#import <dlfcn.h>
#import "HeaderWithEntryPointMethod.h"

void pickedAppVersion(int version) {
    NSString *frameworkName = [NSString stringWithFormat:@"AppV%d", version];
    NSString *frameworkExecutable = [NSString stringWithFormat:@"%@.framework/%@", frameworkName, frameworkName]; // this should traverse the symlink
    NSString *frameworkPath = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:frameworkExecutable];
    void *frameworkHandle = dlopen(frameworkPath.UTF8String, RTLD_NOW);
    if (frameworkHandle != NULL) {
        Class EntryPointClass = NSClassFromString(@"EntryPoint");
        assert(EntryPointClass != Nil);
        [EntryPointClass entryMethod];
        // App framework should do everything from here
        if (dlclose(frameworkHandle) != 0) {
            NSLog(@"failed to close chosen app framework: %s", dlerror());
        }
    }
    else {
        NSLog(@"failed to open app framework: %@ because: %s", frameworkName, dlerror());
    }
}

</code>```

As to exactly what EntryPoint is and +entryMethod does, that's up to you. If you need a C function entry point, use dlsym instead of NSClassFromString.

Re: App Store review: I imagine it might raise an eyebrow or two, but as long as you're allowing the user, especially the reviewer, to choose, there shouldn't be a problem. dlopen is commonly used to selectively load frameworks at runtime in order to streamline app launch and load features an application uses on demand.

Body:
If you've already made your classes into frameworks, congrats, you've done the hard part already. Bear in mind, however, that if much of your application code is in a framework, some things might not behave as expected. For instance, any code that ultimately calls NSBundle.mainBundle (eg +[UIImage imageNamed:]) is probably wrong, assuming you've versioned your assets as well.

But let's assume that you've successfully framework-ized your app versions.

You can't link against either framework if you want to choose one of them at runtime. Instead, you need to use dlopen and NSClassFromString or dlsym to reach an entry point.

Here's an example:

#import <dlfcn.h>
#import "HeaderWithEntryPointMethod.h"

void pickedAppVersion(int version) {
    NSString *frameworkName = [NSString stringWithFormat:@"AppV%d", version];
    NSString *frameworkExecutable = [NSString stringWithFormat:@"%@.framework/%@", frameworkName, frameworkName]; // this should traverse the symlink
    NSString *frameworkPath = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:frameworkExecutable];
    void *frameworkHandle = dlopen(frameworkPath.UTF8String, RTLD_NOW);
    if (frameworkHandle != NULL) {
        Class EntryPointClass = NSClassFromString(@"EntryPoint");
        assert(EntryPointClass != Nil);
        [EntryPointClass entryMethod];
        // App framework should do everything from here
        if (dlclose(frameworkHandle) != 0) {
            NSLog(@"failed to close chosen app framework: %s", dlerror());
        }
    }
    else {
        NSLog(@"failed to open app framework: %@ because: %s", frameworkName, dlerror());
    }
}

As to exactly what EntryPoint is and +entryMethod does, that's up to you. If you need a C function entry point, use dlsym instead of NSClassFromString.

Re: App Store review: I imagine it might raise an eyebrow or two, but as long as you're allowing the user, especially the reviewer, to choose, there shouldn't be a problem. dlopen is commonly used to selectively load frameworks at runtime in order to streamline app launch and load features an application uses on demand.


问:
How to add data labels to a graph created by google apps script
Here is my code.

```<code>function createChart(){

  var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, "month")
    .addColumn(Charts.ColumnType.NUMBER, "A")
    .addColumn(Charts.ColumnType.NUMBER, "B")
    .addRow(["Feb", 10, 5])
    .addRow(["Mar", 12, 3])
    .addRow(["Apr", 20, 5])
    .build();
   var chart = Charts.newBarChart()
      .setDataTable(data)
      .setStacked()
      .setOption('series', {
          0: {dataLabel: 'value'},
          1: {dataLabel: 'value'},
        })
      .setTitle('Sales per Month')
      .build();
  saveGraph2Drive(chart)

  return

}

function saveGraph2Drive(chart) {
  var folderId = 'xxxxx'; // Google Drive Folder ID
  var today = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'YYYY-MM-dd');
  try {
    var graphImg = chart.getBlob();
    var folder = DriveApp.getFolderById(folderId);
    folder.createFile(graphImg).setName(today);
  } catch (e) {
    Browser.msgBox(e);
  }
}
</code>```

I run createChart() in google apps script, and the following graph was saved to Drive.

But, I need the following graph, which has data labes.

答:
You want to add the data labels to the chart.

How about this modification?

In order to achieve above, it uses Class DataViewDefinitionBuilder.

Modified script:

When your script is modified, please modify as follows.

```<code>function createChart(){
  var annotations = [0,  // Added
    1, {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"},
    2, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"},
  ];
  var dataViewDefinition = Charts.newDataViewDefinition().setColumns(annotations).build();  // Added

  var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, "month")
    .addColumn(Charts.ColumnType.NUMBER, "A")
    .addColumn(Charts.ColumnType.NUMBER, "B")
    .addRow(["Feb", 10, 5])
    .addRow(["Mar", 12, 3])
    .addRow(["Apr", 20, 5])
    .build();
   var chart = Charts.newBarChart()
      .setDataTable(data)
      .setStacked()
      .setOption('series', {
          0: {dataLabel: 'value'},
          1: {dataLabel: 'value'},
        })
      .setTitle('Sales per Month')
      .setDataViewDefinition(dataViewDefinition)  // Added
      .build();

  saveGraph2Drive(chart)

  return

}
</code>```

Result:

References:

Class DataViewDefinitionBuilder

setDataViewDefinition()

Labeling columns

I think that this document might be useful.

If I misunderstood your question and this was not the result you want, I apologize.

Body:
Here is my code.

function createChart(){

  var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, "month")
    .addColumn(Charts.ColumnType.NUMBER, "A")
    .addColumn(Charts.ColumnType.NUMBER, "B")
    .addRow(["Feb", 10, 5])
    .addRow(["Mar", 12, 3])
    .addRow(["Apr", 20, 5])
    .build();
   var chart = Charts.newBarChart()
      .setDataTable(data)
      .setStacked()
      .setOption('series', {
          0: {dataLabel: 'value'},
          1: {dataLabel: 'value'},
        })
      .setTitle('Sales per Month')
      .build();
  saveGraph2Drive(chart)

  return

}

function saveGraph2Drive(chart) {
  var folderId = 'xxxxx'; // Google Drive Folder ID
  var today = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'YYYY-MM-dd');
  try {
    var graphImg = chart.getBlob();
    var folder = DriveApp.getFolderById(folderId);
    folder.createFile(graphImg).setName(today);
  } catch (e) {
    Browser.msgBox(e);
  }
}

I run createChart() in google apps script, and the following graph was saved to Drive.

But, I need the following graph, which has data labes.

Body:
You want to add the data labels to the chart.

How about this modification?

In order to achieve above, it uses Class DataViewDefinitionBuilder.

Modified script:

When your script is modified, please modify as follows.

function createChart(){
  var annotations = [0,  // Added
    1, {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"},
    2, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"},
  ];
  var dataViewDefinition = Charts.newDataViewDefinition().setColumns(annotations).build();  // Added

  var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, "month")
    .addColumn(Charts.ColumnType.NUMBER, "A")
    .addColumn(Charts.ColumnType.NUMBER, "B")
    .addRow(["Feb", 10, 5])
    .addRow(["Mar", 12, 3])
    .addRow(["Apr", 20, 5])
    .build();
   var chart = Charts.newBarChart()
      .setDataTable(data)
      .setStacked()
      .setOption('series', {
          0: {dataLabel: 'value'},
          1: {dataLabel: 'value'},
        })
      .setTitle('Sales per Month')
      .setDataViewDefinition(dataViewDefinition)  // Added
      .build();

  saveGraph2Drive(chart)

  return

}

Result:

References:

Class DataViewDefinitionBuilder

setDataViewDefinition()

Labeling columns

I think that this document might be useful.

If I misunderstood your question and this was not the result you want, I apologize.


问:
multiply based on a condition on hardcoded values in pandas python
I have :

```<code>a = 2
b = 3
c = 4
</code>```

my table looks like :

```<code>ID   value
a    20
b    30
c    40
</code>```

Expected table :

```<code>ID   value   Expected_output
a    20      40
b    30      90
c    40      160
</code>```

I tried using np.where but getting the wrong output. How can I multiply hardcoded a,b,c with values

答:
if multiplier is a list you can simply do:</p>

```<code>data = pd.read_excel('test.xlsx')
multiplier = [2, 3, 4]
data['Expected_output'] = data.value * multiplier
print(data)

#   ID  value  Expected_output
# 0  a     20               40
# 1  b     30               90
# 2  c     40              160
</code>```

Body:
I have :

a = 2
b = 3
c = 4

my table looks like :

ID   value
a    20
b    30
c    40

Expected table :

ID   value   Expected_output
a    20      40
b    30      90
c    40      160

I tried using np.where but getting the wrong output. How can I multiply hardcoded a,b,c with values

Body:
if multiplier is a list you can simply do:

data = pd.read_excel('test.xlsx')
multiplier = [2, 3, 4]
data['Expected_output'] = data.value * multiplier
print(data)

#   ID  value  Expected_output
# 0  a     20               40
# 1  b     30               90
# 2  c     40              160


问:
How can I convert plaintext password to django passwords when importing users?
Im trying to setup a djangoproject to handle many users (20 k) .

Im importing the users from an excel file, where the users password is in plain-text (I know, this is bad!)

Im using https://github.com/bmihelac/django-import-export to do my importing, but the import function does not do any converting of the password.

What could I do to store the password correctly?

答:
You should hash your password before importing by overriding the method before_import_row

like this:

```<code>    from import_export import resources, fields
    from import_export.admin import ImportExportModelAdmin
    from django.contrib.auth.hashers import make_password

    class UserResource(resources.ModelResource):

       groups = fields.Field(
           column_name='group_name',
           attribute='groups',
           widget=ManyToManyWidget(Group, ',','name')
       )
       def before_import_row(self,row, **kwargs):
           value = row['password']
           row['password'] = make_password(value)
       class Meta:
           model = User

</code>```

Body:
You should hash your password before importing by overriding the method before_import_row

like this:

    from import_export import resources, fields
    from import_export.admin import ImportExportModelAdmin
    from django.contrib.auth.hashers import make_password

    class UserResource(resources.ModelResource):

       groups = fields.Field(
           column_name='group_name',
           attribute='groups',
           widget=ManyToManyWidget(Group, ',','name')
       )
       def before_import_row(self,row, **kwargs):
           value = row['password']
           row['password'] = make_password(value)
       class Meta:
           model = User


答:
There are 2 options by which you can do this.

Option1: initializing the class, by passing in the required object as param

```<code>class Storage
{
  constructor(init)
  {
    return init;
}
}

let ourStorage = new Storage({
    "variableItem1":   {
        "drawer": ""
      },
    "variableItem2": {
        "top drawer": {
          "folder1": "",
          "folder2": "harhar"
        },
        "bottom drawer": ""
      }
    });

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2);
</code>```

Option 2: Initializing the object inside the constructor of the class

```<code>class Storage
{
  constructor(init)
  {
    return {
    "variableItem1":   {
        "drawer": ""
      },
    "variableItem2": {
        "top drawer": {
          "folder1": "",
          "folder2": "harhar"
        },
        "bottom drawer": ""
      }
    };
}
}

let ourStorage = new Storage();

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2);
</code>```

Title: Writing a class in javascript

Body:
There are 2 options by which you can do this.

Option1: initializing the class, by passing in the required object as param

class Storage
{
  constructor(init)
  {
    return init;
}
}

let ourStorage = new Storage({
    "variableItem1":   {
        "drawer": ""
      },
    "variableItem2": {
        "top drawer": {
          "folder1": "",
          "folder2": "harhar"
        },
        "bottom drawer": ""
      }
    });

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2);

Option 2: Initializing the object inside the constructor of the class

class Storage
{
  constructor(init)
  {
    return {
    "variableItem1":   {
        "drawer": ""
      },
    "variableItem2": {
        "top drawer": {
          "folder1": "",
          "folder2": "harhar"
        },
        "bottom drawer": ""
      }
    };
}
}

let ourStorage = new Storage();

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2);


问:
Deep filter objects in javascript array
From the following code below I need to return only the objects that have meta.menu in them while preserving the structure.

So in the case below, only the object with "panel.users.view" would get removed. I've tried making a recursive function to traverse it but I can't figure out how to infinitely traverse it because there could be more objects. I don't know how many levels deep a routes object can get.

I've also looked through lodash and collect.js to see if there were functions that could be used for this but I'm unable to find a solution on my own.

Would greatly appreciate the help, many thanks!

const routes = [
    {
        path: "/panel",
        name: "panel",
        redirect: { name: "panel.dashboard" },
        component: {},
        children: [
            {
                path: "/dashboard",
                name: "panel.dashboard",
                component: {},
                meta: {
                    menu: "main"
                },
            },
            {
                path: "/users",
                name: "panel.users",
                redirect: { name: "panel.dashboard" },
                component: {},
                children: [
                    {
                        path: "list",
                        name: "panel.users.list",
                        component: {},
                        meta: {
                            menu: "main"
                        },
                    },
                    {
                        path: "view/:user_id",
                        name: "panel.users.view",
                        component: {},
                    },
                ],
            }
        ],
    }
];
```

答:
You could imagine a recursive function which would look something like.

```<code>const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
                if(key === "children") findMeta(value);
                if(key === "meta") res.push(r);
      }
  })
  return res;
}
</code>```

const routes = [
    {
        path: "/panel",
        name: "panel",
        redirect: { name: "panel.dashboard" },
        component: {},
        children: [
            {
                path: "/dashboard",
                name: "panel.dashboard",
                component: {},
                meta: {
                    menu: "main"
                },
            },
            {
                path: "/users",
                name: "panel.users",
                redirect: { name: "panel.dashboard" },
                component: {},
                children: [
                    {
                        path: "list",
                        name: "panel.users.list",
                        component: {},
                        meta: {
                            menu: "main"
                        },
                    },
                    {
                        path: "view/:user_id",
                        name: "panel.users.view",
                        component: {},
                    },
                ],
            }
        ],
    }
];

const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
    if(key === "children") findMeta(value);
    if(key === "meta") res.push(r);
      }
  })
  return res;
}

console.log(findMeta(routes))```

Title: Deep filter objects in javascript array

Body:
You could imagine a recursive function which would look something like.

const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
                if(key === "children") findMeta(value);
                if(key === "meta") res.push(r);
      }
  })
  return res;
}

const routes = [
    {
        path: "/panel",
        name: "panel",
        redirect: { name: "panel.dashboard" },
        component: {},
        children: [
            {
                path: "/dashboard",
                name: "panel.dashboard",
                component: {},
                meta: {
                    menu: "main"
                },
            },
            {
                path: "/users",
                name: "panel.users",
                redirect: { name: "panel.dashboard" },
                component: {},
                children: [
                    {
                        path: "list",
                        name: "panel.users.list",
                        component: {},
                        meta: {
                            menu: "main"
                        },
                    },
                    {
                        path: "view/:user_id",
                        name: "panel.users.view",
                        component: {},
                    },
                ],
            }
        ],
    }
];

const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
    if(key === "children") findMeta(value);
    if(key === "meta") res.push(r);
      }
  })
  return res;
}

console.log(findMeta(routes))


问:
Sampling from a normal distribution using a for loop
So I am trying to sample from a uniform distribution 1000 times each time computing the mean of 20 random samples from said uniform distribution.

```<code>Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans.
{r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean = runif(n_samples, unif_sample_size))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] = summarize(uniformSampleMeans = mean(unif_sample_size))
}
</code>```

I successfully generate a tibble, however the values are "NaN". Additionally when I get to my for loop I get an error.

```<code>Error in summarise_(.data, .dots = compat_as_lazy_dots(...)) : argument ".data" is missing, with no default
</code>```

Any insight would be much appreciated!

Body:
So I am trying to sample from a uniform distribution 1000 times each time computing the mean of 20 random samples from said uniform distribution.

Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans.
{r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean = runif(n_samples, unif_sample_size))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] = summarize(uniformSampleMeans = mean(unif_sample_size))
}

I successfully generate a tibble, however the values are "NaN". Additionally when I get to my for loop I get an error.

Error in summarise_(.data, .dots = compat_as_lazy_dots(...)) : argument ".data" is missing, with no default

Any insight would be much appreciated!

Body:
Building a data.frame row-by-row is horrible in performance (it makes a complete copy of all rows each time you add one ... so that row 900, adding a row you have the original 900 rows twice ... this scales poorly).

Also, realize that taking many small random samples is a lot more expensive than taking just one larger sample.

set.seed(42)
m <- matrix(rnorm(1000*20), ncol = 20)
head(m)
#        [,1]   [,2]   [,3]   [,4]   [,5]    [,6]   [,7]    [,8]    [,9]   [,10]  [,11]   [,12]
# [1,]  1.371  2.325  0.251 -0.686 -0.142  0.0712  0.173  1.4163 -0.0575 -0.9221  1.163 -0.2945
# [2,] -0.565  0.524 -0.278 -0.793 -0.814  0.9703 -1.273  0.5572 -0.2490 -0.4958 -0.190  0.4641
# [3,]  0.363  0.971 -1.725 -0.407 -0.326  0.3100 -0.868  0.9812 -1.5242 -3.1105 -0.289 -1.5371
# [4,]  0.633  0.377 -2.007 -1.149  0.378 -0.1395  0.626 -0.5862  0.4636 -0.6928 -0.399  0.9862
# [5,]  0.404 -0.996 -1.292  1.116 -1.994 -0.3263 -0.106  0.9392 -1.1876  0.2989  0.709  0.6302
# [6,] -0.106 -0.597  0.366 -0.879 -0.999 -0.1188 -0.256 -0.0647  0.4941 -0.0687 -1.623  0.0573
#        [,13]    [,14]    [,15]  [,16]  [,17]  [,18]   [,19]  [,20]
# [1,]  0.0538 -1.80043 -2.29607 -1.020  0.496  0.110  1.0251  1.790
# [2,]  0.7534 -0.10643  0.00465 -0.754  0.519 -0.741 -1.4492 -0.262
# [3,]  0.2499  1.83347 -1.61634 -1.226 -0.422 -0.511  1.4175 -1.297
# [4,] -0.4441  1.02390  1.73313 -1.017  0.863 -0.912 -1.0353  0.618
# [5,] -0.0503 -0.00429 -0.67368  1.722 -0.778 -1.293  0.0853 -0.292
# [6,] -0.4678  2.27991 -0.09442  3.000  0.148  0.905  0.2451 -0.301
m2 <- apply(m, 1, mean)
length(m2)
# [1] 1000
head(m2)
# [1]  0.1513 -0.2089 -0.4366 -0.0339 -0.1544  0.0959
mean(m[1,])
# [1] 0.151
tibble(i = seq_along(m2), mu = m2)
# # A tibble: 1,000 x 2
#        i      mu
#    <int>   <dbl>
#  1     1  0.151
#  2     2 -0.209
#  3     3 -0.437
#  4     4 -0.0339
#  5     5 -0.154
#  6     6  0.0959
#  7     7  0.105
#  8     8 -0.503
#  9     9  0.0384
# 10    10 -0.175
# # ... with 990 more rows


问:
how to prevent ctrl-v in custom ajax toolkit editor?
Hi
I have succesfully made a custom ajax toolkit with a few buttoms in the footer toolbar as I wish. Now I also want to avoid crtl-v and right-click paste, but have searched, searched and tried everything with no result ... Maybe someone can lead me on the right track, I hope :)

Here below is my code (used with c# on asp.net web pages) which makes a editor control. The first part works, but the last part with the keydown is not working and maybe completely wrong?

Best regards,
Lars, Denmark

My Code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Windows.Forms;
using AjaxControlToolkit.HTMLEditor;

/// <summary>
/// Særlig editor tilrettet behovet hos Boost Company
/// </summary>

namespace AjaxControlToolkit.HTMLEditor.BoostToolbarButton
{
    public class Bold : AjaxControlToolkit.HTMLEditor.ToolbarButton.Bold
    {
        public override string ToolTip
        {
            get { return "Fed"; }
        }
    }
    public class Italic : AjaxControlToolkit.HTMLEditor.ToolbarButton.Italic
    {
    public override string ToolTip
        {
            get { return "Kursiv"; }
        }
    }
    public class Cut : AjaxControlToolkit.HTMLEditor.ToolbarButton.Cut
    {
        public override string ToolTip
        {
            get { return "Klip"; }
        }
    }
    public class Copy : AjaxControlToolkit.HTMLEditor.ToolbarButton.Copy
    {
        public override string ToolTip
        {
            get { return "Kopier"; }
        }
    }
    public class PasteText : AjaxControlToolkit.HTMLEditor.ToolbarButton.PasteText
    {
        public override string ToolTip
        {
            get { return "Indsæt"; }
        }
    }
    public class InsertLink : AjaxControlToolkit.HTMLEditor.ToolbarButton.InsertLink
    {
        public override string ToolTip
        {
            get { return "Indsæt/ret link"; }
        }
    }
}

namespace BoostKontroller
{

public class BoostEditor : Editor
{
    protected override void FillTopToolbar()
    {
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Bold());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Italic());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Cut());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Copy());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.PasteText());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.InsertLink());
    }

    protected override void FillBottomToolbar()
    {

    }

    void OnKeyDown(KeyEventArgs e)
    {

        if (e.Control && e.KeyCode == Keys.V)
        {
             Clipboard.SetText(string .Empty); ;
        }

    }

}
}
</code>```

答:
You can do that:

```<code>$find(sControlId).get_editPanel().get_activePanel()._doc.body.onpaste =
  function onPasteFunction()
  {
    $find(sControlId).get_editPanel().get_activePanel()._paste(false, false);
    return false;
  }
</code>```

_paste(false, false); is to paste with plain text if you want the word paste the function is _paste(true, true);

sControlId is the client id of the editor.

ContentLicense: CC BY-SA 2.5

Body:
Hi
I have succesfully made a custom ajax toolkit with a few buttoms in the footer toolbar as I wish. Now I also want to avoid crtl-v and right-click paste, but have searched, searched and tried everything with no result ... Maybe someone can lead me on the right track, I hope :)

Here below is my code (used with c# on asp.net web pages) which makes a editor control. The first part works, but the last part with the keydown is not working and maybe completely wrong?

Best regards,
Lars, Denmark

My Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Windows.Forms;
using AjaxControlToolkit.HTMLEditor;

///
/// Særlig editor tilrettet behovet hos Boost Company
///

namespace AjaxControlToolkit.HTMLEditor.BoostToolbarButton
{
    public class Bold : AjaxControlToolkit.HTMLEditor.ToolbarButton.Bold
    {
        public override string ToolTip
        {
            get { return "Fed"; }
        }
    }
    public class Italic : AjaxControlToolkit.HTMLEditor.ToolbarButton.Italic
    {
    public override string ToolTip
        {
            get { return "Kursiv"; }
        }
    }
    public class Cut : AjaxControlToolkit.HTMLEditor.ToolbarButton.Cut
    {
        public override string ToolTip
        {
            get { return "Klip"; }
        }
    }
    public class Copy : AjaxControlToolkit.HTMLEditor.ToolbarButton.Copy
    {
        public override string ToolTip
        {
            get { return "Kopier"; }
        }
    }
    public class PasteText : AjaxControlToolkit.HTMLEditor.ToolbarButton.PasteText
    {
        public override string ToolTip
        {
            get { return "Indsæt"; }
        }
    }
    public class InsertLink : AjaxControlToolkit.HTMLEditor.ToolbarButton.InsertLink
    {
        public override string ToolTip
        {
            get { return "Indsæt/ret link"; }
        }
    }
}

namespace BoostKontroller
{

public class BoostEditor : Editor
{
    protected override void FillTopToolbar()
    {
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Bold());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Italic());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Cut());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.Copy());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.PasteText());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.BoostToolbarButton.InsertLink());
    }

    protected override void FillBottomToolbar()
    {

    }

    void OnKeyDown(KeyEventArgs e)
    {

        if (e.Control && e.KeyCode == Keys.V)
        {
             Clipboard.SetText(string .Empty); ;
        }

    }

}
}

Body:
You can do that:

$find(sControlId).get_editPanel().get_activePanel()._doc.body.onpaste =
  function onPasteFunction()
  {
    $find(sControlId).get_editPanel().get_activePanel()._paste(false, false);
    return false;
  }

_paste(false, false); is to paste with plain text if you want the word paste the function is _paste(true, true);

sControlId is the client id of the editor.


答:
Given that you've tagged this as a dplyr question, you can use summarise_all:

```<code>library(dplyr)

n_obs = 20
n_samples = 1000

samples <- data.frame(matrix(runif(n_obs * n_samples), nrow = 20))

summarise_all(samples, mean)
</code>```

As others have noted, it's possible to do this in base R, too.

Update Per OP comment

Yes, possible to use a for loop, although not advisable.  Here's one approach:

```<code>unif_sample_size = 20
n_samples = 1000
total_draws <- unif_sample_size * n_samples

uniformSampleMeans <-
  tibble(draw_from_uniform = runif(n_samples * unif_sample_size))

sample_means <- vector(length = n_samples)

i <- 1
for (ix in seq(1, total_draws, by = unif_sample_size)) {
  start <- ix
  end <- ix + unif_sample_size - 1
  sample_means[i] <- mean(uniformSampleMeans$draw_from_uniform[start:end])
  i <- i + 1
}
</code>```

Title: Sampling from a normal distribution using a for loop

Body:
Given that you've tagged this as a dplyr question, you can use summarise_all:

library(dplyr)

n_obs = 20
n_samples = 1000

samples <- data.frame(matrix(runif(n_obs * n_samples), nrow = 20))

summarise_all(samples, mean)

As others have noted, it's possible to do this in base R, too.

Update Per OP comment

Yes, possible to use a for loop, although not advisable.  Here's one approach:

unif_sample_size = 20
n_samples = 1000
total_draws <- unif_sample_size * n_samples

uniformSampleMeans <-
  tibble(draw_from_uniform = runif(n_samples * unif_sample_size))

sample_means <- vector(length = n_samples)

i <- 1
for (ix in seq(1, total_draws, by = unif_sample_size)) {
  start <- ix
  end <- ix + unif_sample_size - 1
  sample_means[i] <- mean(uniformSampleMeans$draw_from_uniform[start:end])
  i <- i + 1
}


问:
How to solve flutter inappwebview stopped working?
I have created an app to display html file with flutter_inappwebview plugin but i got errors as below:

pubspec.yaml

```<code>flutter_inappwebview: ^2.1.0
</code>```

here is  my main.dart

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
  runApp(new MyApp());
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String url = "";
  double progress = 0;
  @override
  void initState() {
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: InAppWebView(
        initialUrl: 'https://www.google.com',
      ),
    );
  }
}
</code>```

when I run the code the app unfortunately stop.

This is an error in Emulator.

This is an error in Android Studio 3.5.3

Any solutions thanks?

答:
After looking at issue in github issue link, here is the solution:

From

```<code>dependencies:
  flutter_inappwebview: ^2.1.0+1
</code>```

To

```<code>dependencies:
  flutter_inappwebview:
      git:
        url: https://github.com/pichillilorenzo/flutter_inappwebview.git
</code>```

Then run flutter clean and then run the app. It should solve the problem.

Body:
I have created an app to display html file with flutter_inappwebview plugin but i got errors as below:

pubspec.yaml

flutter_inappwebview: ^2.1.0

here is  my main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
  runApp(new MyApp());
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String url = "";
  double progress = 0;
  @override
  void initState() {
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: InAppWebView(
        initialUrl: 'https://www.google.com',
      ),
    );
  }
}

when I run the code the app unfortunately stop.

This is an error in Emulator.

This is an error in Android Studio 3.5.3

Any solutions thanks?

Body:
After looking at issue in github issue link, here is the solution:

From

dependencies:
  flutter_inappwebview: ^2.1.0+1

To

dependencies:
  flutter_inappwebview:
      git:
        url: https://github.com/pichillilorenzo/flutter_inappwebview.git

Then run flutter clean and then run the app. It should solve the problem.


问:
Bazel remote cache analysis data
I am running bazel (via bazelisk) inside a docker container on jenkins. Furthermore I use a remote cache. On subsequent runs with no changes I get 100% cache hits, but the analysis phase (~60seconds) runs everytime a new container is created.

Is there a way to cache the analysis data remotely aswell or am I forced to run bazel directly on the jenkins agent so it doesn't shut itself off after build completion?

Thanks in advance

答:
https://docs.bazel.build/versions/master/remote-caching.html#known-issues

this link describes that the state is stored in-memory and therefore can not be cached easily

Title: Bazel remote cache analysis data


问:
python itertools product with steps
Currently, I have a NumPy array:

```<code>a = np.array([[1,2],[3,4],[5,6]])
</code>```

And I am doing the product operation in itertools, but I want to add a step function.
For example:

```<code>[ x for x in itertools.product(*a) ]
</code>```

Result in:

```<code>[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
</code>```

For the target output with step (1,1,2):

```<code>[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]
</code>```

I can't figure it out, here is the problem.

答:
This should do:</p>

```<code>step = (1,1,2)
[ x for x in itertools.product(*[a[i,::s] for i,s in enumerate(step)])]
</code>```

Title: python itertools product with steps

Body:
Currently, I have a NumPy array:

a = np.array([[1,2],[3,4],[5,6]])

And I am doing the product operation in itertools, but I want to add a step function.
For example:

[ x for x in itertools.product(*a) ]

Result in:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]

For the target output with step (1,1,2):

[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]

I can't figure it out, here is the problem.

Body:
This should do:

step = (1,1,2)
[ x for x in itertools.product(*[a[i,::s] for i,s in enumerate(step)])]


问:
Translating a VBA function into R
I am attempting to translate the function DISCRINV() which is an excel function available in the simtools excel add-in that was created by Roger Myerson into an R function. I believe i am close, but am having difficulty understanding the looping syntax of VBA.

The VBA code for this function is as follows:

```<code>Function DISCRINV(ByVal randprob As Double, values As Object, probabilities As Object)
On Error GoTo 63
Dim i As Integer, cumv As Double, cel As Object
If values.Count <> probabilities.Count Then GoTo 63
For Each cel In probabilities
 i = i + 1
 cumv = cumv + cel.Value
 If randprob < cumv Then
 DISCRINV = values.Cells(i).Value
 Exit Function
 End If
Next cel
If randprob < cumv + 0.001 Then
 DISCRINV = values.Cells(i).Value
 Exit Function
End If
63 DISCRINV = CVErr(xlErrValue)
End Function
</code>```

Attempting to translate this directly from the VBA code i have come up with this (Not Correct):

```<code>DISCRINV <- function(R,V,P){
 if(length(V) != length(P)){
   print("ERROR NUMBER OF VALUES DOES NOT EQUAL NUMBER OF PROBABILITIES")
 } else{
   for (i in 1:length(P)){
     cumv=cumv+P[i]
     if (R < cumv){
       DISCY1 = V[i]
       return(DISCY1)
       }

   print(cumv)

 if (R < cumv +0.001){

   DISCY2 = V[i]

   return(DISCY2)
 }
   }
 }
}
</code>```

Attempting to translate this through my understanding of what it is doing i have come up with this:

```<code>DISCRINV <- function(x,values,probabilities){
  require(FSA)
  precumsum <- pcumsum(probabilities)
  middle <- c()
  for (i in 1:(length(values)-2)){
    if (precumsum[i+1] <= x & x < precumsum[i+2]){
      middle[i] <- values[i+1]}
    else{
      middle[i] <- 0
    }
  }

  firstrow <- ifelse(x < precumsum[2], values[1], 0)
  lastrow <- ifelse(precumsum[length(precumsum)] <= x , values[length(precumsum)] , 0)
  Gvector <- c(firstrow,middle,lastrow)
  print(firstrow)
  print(middle)
  print(lastrow)
  print(Gvector)
  simulatedvalue <-  sum(Gvector)

  return(simulatedvalue)
}
</code>```

The latter option works 99% of the time, but not when the first function parameter is over 0.5, the second parameter is a vector of values c(1000,2000) and the third parameter is a vector (0.5,0.5). The case of the latter option not working 100% of the time is what has led me to try to translate the function directly. Could someone please give some insight into where my translation is going wrong?

Additionally a description of the function is as follows:

DISCRINV(randprob, values, probabilities) returns inverse cumulative values for a discrete random variable. When the first parameter is a RAND, DISCRINV returns a discrete random variable with possible values and corresponding probabilities in the given ranges.

Thank you in advance for the insight!

答:
For anyone that is interested, i was able to successfully translate this VBA script using this code</p>

```<code>    DISCRINV <- function(x,values,probabilities){
    require(FSA)
    precumsum <- pcumsum(probabilities)
    middle <- c()
    if(length(values <3 )){

    if(x<0.5){
    middle1 <- values[1]
    return(middle1)
    } else{
    middle2 <- values[2]
    return(middle2)
    }
    }
    else{
    for (i in 1:(length(values)-2)){
    if (precumsum[i+1] <= x & x < precumsum[i+2]){
    middle[i] <- values[i+1]}
    else{
    middle[i] <- 0
    }
    }
    firstrow <- ifelse(x < precumsum[2], values[1], 0)
    lastrow <- ifelse(precumsum[length(precumsum)] <= x , values[length(precumsum)] , 0)
    Gvector <- c(firstrow,middle,lastrow)
    print(firstrow)
    print(middle)
    print(lastrow)
    print(Gvector)
    simulatedvalue <-  sum(Gvector)

    return(simulatedvalue)
    }
    }

</code>```

Title: Translating a VBA function into R

Body:
I am attempting to translate the function DISCRINV() which is an excel function available in the simtools excel add-in that was created by Roger Myerson into an R function. I believe i am close, but am having difficulty understanding the looping syntax of VBA.

The VBA code for this function is as follows:

Function DISCRINV(ByVal randprob As Double, values As Object, probabilities As Object)
On Error GoTo 63
Dim i As Integer, cumv As Double, cel As Object
If values.Count <> probabilities.Count Then GoTo 63
For Each cel In probabilities
 i = i + 1
 cumv = cumv + cel.Value
 If randprob < cumv Then
 DISCRINV = values.Cells(i).Value
 Exit Function
 End If
Next cel
If randprob < cumv + 0.001 Then
 DISCRINV = values.Cells(i).Value
 Exit Function
End If
63 DISCRINV = CVErr(xlErrValue)
End Function

Attempting to translate this directly from the VBA code i have come up with this (Not Correct):

DISCRINV <- function(R,V,P){
 if(length(V) != length(P)){
   print("ERROR NUMBER OF VALUES DOES NOT EQUAL NUMBER OF PROBABILITIES")
 } else{
   for (i in 1:length(P)){
     cumv=cumv+P[i]
     if (R < cumv){
       DISCY1 = V[i]
       return(DISCY1)
       }

   print(cumv)

 if (R < cumv +0.001){

   DISCY2 = V[i]

   return(DISCY2)
 }
   }
 }
}

Attempting to translate this through my understanding of what it is doing i have come up with this:

DISCRINV <- function(x,values,probabilities){
  require(FSA)
  precumsum <- pcumsum(probabilities)
  middle <- c()
  for (i in 1:(length(values)-2)){
    if (precumsum[i+1] <= x & x < precumsum[i+2]){
      middle[i] <- values[i+1]}
    else{
      middle[i] <- 0
    }
  }

  firstrow <- ifelse(x < precumsum[2], values[1], 0)
  lastrow <- ifelse(precumsum[length(precumsum)] <= x , values[length(precumsum)] , 0)
  Gvector <- c(firstrow,middle,lastrow)
  print(firstrow)
  print(middle)
  print(lastrow)
  print(Gvector)
  simulatedvalue <-  sum(Gvector)

  return(simulatedvalue)
}

The latter option works 99% of the time, but not when the first function parameter is over 0.5, the second parameter is a vector of values c(1000,2000) and the third parameter is a vector (0.5,0.5). The case of the latter option not working 100% of the time is what has led me to try to translate the function directly. Could someone please give some insight into where my translation is going wrong?

Additionally a description of the function is as follows:

DISCRINV(randprob, values, probabilities) returns inverse cumulative values for a discrete random variable. When the first parameter is a RAND, DISCRINV returns a discrete random variable with possible values and corresponding probabilities in the given ranges.

Thank you in advance for the insight!

Body:
For anyone that is interested, i was able to successfully translate this VBA script using this code

    DISCRINV <- function(x,values,probabilities){
    require(FSA)
    precumsum <- pcumsum(probabilities)
    middle <- c()
    if(length(values <3 )){

    if(x<0.5){
    middle1 <- values[1]
    return(middle1)
    } else{
    middle2 <- values[2]
    return(middle2)
    }
    }
    else{
    for (i in 1:(length(values)-2)){
    if (precumsum[i+1] <= x & x < precumsum[i+2]){
    middle[i] <- values[i+1]}
    else{
    middle[i] <- 0
    }
    }
    firstrow <- ifelse(x < precumsum[2], values[1], 0)
    lastrow <- ifelse(precumsum[length(precumsum)] <= x , values[length(precumsum)] , 0)
    Gvector <- c(firstrow,middle,lastrow)
    print(firstrow)
    print(middle)
    print(lastrow)
    print(Gvector)
    simulatedvalue <-  sum(Gvector)

    return(simulatedvalue)
    }
    }


问:
How can I pad an integer with zeros on the left?
How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

答:
Here is how you can format your string without using DecimalFormat.

String.format("%02d", 9)

09

String.format("%03d", 19)

019

String.format("%04d", 119)

0119

OwnerDisplayName: Omar Kooheji