问:
Unable to connect Android phone to my project with Expo
I created my project in react native by CLI:

```<code>_npm install -g create-react-native-app
_create-react-native-app AwesomeProject
_cd AwesomeProject
_npm start
</code>```

Then I installed expo in my Android phone, and scanned a QR code on my computer screen.

However, my phone can't connect to project, and I don't know why. It just loads and fails. This is error message:

Could not load exp:// 192.168.56.1:19000. Network response timed out.

This is view error:

"Uncaught Error: java,not.SocketTimeoutException: faild to connect to/192.168.56.1 (port 19000) after 10000 ms.

I'm trying to fix it, but still can't get it working. My phone and my laptop are on the same network. What can I do now?

答:
for local testing e.g comnputer , simulator

expo start

for Real mobile device

expo start --tunnel

Body:
I created my project in react native by CLI:

_npm install -g create-react-native-app
_create-react-native-app AwesomeProject
_cd AwesomeProject
_npm start

Then I installed expo in my Android phone, and scanned a QR code on my computer screen.

However, my phone can't connect to project, and I don't know why. It just loads and fails. This is error message:

Could not load exp:// 192.168.56.1:19000. Network response timed out.

This is view error:

"Uncaught Error: java,not.SocketTimeoutException: faild to connect to/192.168.56.1 (port 19000) after 10000 ms.

I'm trying to fix it, but still can't get it working. My phone and my laptop are on the same network. What can I do now?


来源: stackexchange

问:
How to change results Youtube Data API v3
I want to use nextPageToken to get new result when scrolling down.

https://developers.google.com/youtube/v3/docs/playlistItems/list?hl=ko

For example, if you do a search initially and 6 items are displayed,
Scroll down to see other videos related to those 6 search terms.

The same videos keep coming out.
How do I change the result??

onModalShow.js

```<code>import {$} from "../utils/querySelector.js";
import {renderRecentKeyword, renderSearchResult} from "../view/Modalview.js";
import {getURLQueryStringApplied, request} from "../utils/fetch.js";
import {MAX_RESULT_COUNT, PART_TYPE, REGION_CODE, SEARCH_TYPE_VIDEO} from "../constant.js";

const NEXT_PAGE_TOKEN ="";

const processJSON = (rawData) => {

    return rawData.items.map((item)=>({
        videoId : item.id.videoId,
        videoTitle : item.snippet.title,
        channelId : item.snippet.channelId,
        channelTitle : item.snippet.channelTitle,
        publishedAt : item.snippet.publishedAt,
    }));
};

export const requestSearch =(url)=>{
    request(url)
        .then((response)=>{

            return processJSON(response);
        })
        .then((articleInfo)=>renderSearchResult(articleInfo))
        .then((error)=>console.log(error));
};

export const renderSearchGroup=()=>{

    const $keywordInput = $('#search-input').value;
    const url = getURLQueryStringApplied({

        part: PART_TYPE,

        q: $keywordInput,

        type: SEARCH_TYPE_VIDEO,

        maxResults: MAX_RESULT_COUNT,

        regionCode: REGION_CODE,
        pageToken :  NEXT_PAGE_TOKEN,

    });

    requestSearch(url);
}

export const onSearchKeywordClick=()=>{
    const $keywordInput = $('#search-input').value;
    renderSearchGroup();
    renderRecentKeyword($keywordInput);
}

export const onSearchKeywordEnter = (e) => {
    const $keywordInput = $('#search-input').value;
    e.preventDefault();
    renderSearchGroup();
    renderRecentKeyword($keywordInput);

};

</code>```

fetch.js

```<code>import {API_KEY} from "./api.js";

export const request = async (url) => {
    try {
        const response = await fetch(url, {
            method: 'GET',
        });

        if (!response.ok) {
            throw Error(response.statusText);
        }

        return response.json();
    } catch (e) {
        console.error(e);
    }
};

export const getURLQueryStringApplied = (queryStrings) => {

    const queryString = Object.keys(queryStrings)
        .map((key)=>`&${key}=${queryStrings[key]}`)
        .join('');
    return `https://www.googleapis.com/youtube/v3/search?key=${API_KEY}`.concat(queryString);
};

</code>```

index.js

```<code>
import {$} from "./utils/querySelector.js";
import {onModalClose, onModalShowOpen} from "./view/Modalview.js";
import {onSearchKeywordClick} from "./handle/onModalShow.js";
import {onSearchKeywordEnter} from "./handle/onModalShow.js";
import {onMoreScroll} from "./handle/onMoreScroll.js";

const $searchKeyWordForm = $('#search-keyword-form');
const $searchBtn =$('#search-submit');

const $modalInner = $('.modal-inner');
export const YoutubeClassRoom =()=>{

    $('#search-button').addEventListener("click",onModalShowOpen);
    $('.modal-close').addEventListener("click",onModalClose);

    $searchKeyWordForm.addEventListener("submit",onSearchKeywordEnter);

    $searchBtn.addEventListener("click",onSearchKeywordClick);

    $modalInner.addEventListener("scroll",onMoreScroll);

};

YoutubeClassRoom();
</code>```

答:
it was very simple
add a value to the lookup field and
nextPageToken
Add it as the pageToken property value and you get the result.</p>
```<code>let nextPageToken ='';
const processJSON = (rawData) => {

    nextPageToken=rawData.nextPageToken;

    return rawData.items.map((item)=>({
        videoId : item.id.videoId,
        videoTitle : item.snippet.title,
        channelId : item.snippet.channelId,
        channelTitle : item.snippet.channelTitle,
        publishedAt : item.snippet.publishedAt,

    }));
};

export const nextPage =()=>{

    const $keywordInput = $('#search-input').value;

    const url =getURLQueryStringApplied({

        part : PART_TYPE,
        q:  $keywordInput,
        type : SEARCH_TYPE_VIDEO,
        maxResults : 2,
        regionCode: REGION_CODE,
        pageToken: nextPageToken,
    });

    requestSearch(url);
    nextPageToken='';
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use nextPageToken to get new result when scrolling down.

https://developers.google.com/youtube/v3/docs/playlistItems/list?hl=ko

For example, if you do a search initially and 6 items are displayed,
Scroll down to see other videos related to those 6 search terms.

The same videos keep coming out.
How do I change the result??

onModalShow.js

import {$} from "../utils/querySelector.js";
import {renderRecentKeyword, renderSearchResult} from "../view/Modalview.js";
import {getURLQueryStringApplied, request} from "../utils/fetch.js";
import {MAX_RESULT_COUNT, PART_TYPE, REGION_CODE, SEARCH_TYPE_VIDEO} from "../constant.js";

const NEXT_PAGE_TOKEN ="";

const processJSON = (rawData) => {

    return rawData.items.map((item)=>({
        videoId : item.id.videoId,
        videoTitle : item.snippet.title,
        channelId : item.snippet.channelId,
        channelTitle : item.snippet.channelTitle,
        publishedAt : item.snippet.publishedAt,
    }));
};

export const requestSearch =(url)=>{
    request(url)
        .then((response)=>{

            return processJSON(response);
        })
        .then((articleInfo)=>renderSearchResult(articleInfo))
        .then((error)=>console.log(error));
};

export const renderSearchGroup=()=>{

    const $keywordInput = $('#search-input').value;
    const url = getURLQueryStringApplied({

        part: PART_TYPE,

        q: $keywordInput,

        type: SEARCH_TYPE_VIDEO,

        maxResults: MAX_RESULT_COUNT,

        regionCode: REGION_CODE,
        pageToken :  NEXT_PAGE_TOKEN,

    });

    requestSearch(url);
}

export const onSearchKeywordClick=()=>{
    const $keywordInput = $('#search-input').value;
    renderSearchGroup();
    renderRecentKeyword($keywordInput);
}

export const onSearchKeywordEnter = (e) => {
    const $keywordInput = $('#search-input').value;
    e.preventDefault();
    renderSearchGroup();
    renderRecentKeyword($keywordInput);

};

fetch.js

import {API_KEY} from "./api.js";

export const request = async (url) => {
    try {
        const response = await fetch(url, {
            method: 'GET',
        });

        if (!response.ok) {
            throw Error(response.statusText);
        }

        return response.json();
    } catch (e) {
        console.error(e);
    }
};

export const getURLQueryStringApplied = (queryStrings) => {

    const queryString = Object.keys(queryStrings)
        .map((key)=>`&${key}=${queryStrings[key]}`)
        .join('');
    return `https://www.googleapis.com/youtube/v3/search?key=${API_KEY}`.concat(queryString);
};

index.js

import {$} from "./utils/querySelector.js";
import {onModalClose, onModalShowOpen} from "./view/Modalview.js";
import {onSearchKeywordClick} from "./handle/onModalShow.js";
import {onSearchKeywordEnter} from "./handle/onModalShow.js";
import {onMoreScroll} from "./handle/onMoreScroll.js";

const $searchKeyWordForm = $('#search-keyword-form');
const $searchBtn =$('#search-submit');

const $modalInner = $('.modal-inner');
export const YoutubeClassRoom =()=>{

    $('#search-button').addEventListener("click",onModalShowOpen);
    $('.modal-close').addEventListener("click",onModalClose);

    $searchKeyWordForm.addEventListener("submit",onSearchKeywordEnter);

    $searchBtn.addEventListener("click",onSearchKeywordClick);

    $modalInner.addEventListener("scroll",onMoreScroll);

};

YoutubeClassRoom();

Body:
it was very simple
add a value to the lookup field and
nextPageToken
Add it as the pageToken property value and you get the result.

let nextPageToken ='';
const processJSON = (rawData) => {

    nextPageToken=rawData.nextPageToken;

    return rawData.items.map((item)=>({
        videoId : item.id.videoId,
        videoTitle : item.snippet.title,
        channelId : item.snippet.channelId,
        channelTitle : item.snippet.channelTitle,
        publishedAt : item.snippet.publishedAt,

    }));
};

export const nextPage =()=>{

    const $keywordInput = $('#search-input').value;

    const url =getURLQueryStringApplied({

        part : PART_TYPE,
        q:  $keywordInput,
        type : SEARCH_TYPE_VIDEO,
        maxResults : 2,
        regionCode: REGION_CODE,
        pageToken: nextPageToken,
    });

    requestSearch(url);
    nextPageToken='';
}


问:
Ngrx effects not waiting for required data after refactoring
I had a working app using the original reducers, actions and effects of ngrx 7. Some of my effects read a value from the store using withLatestFrom, which is populated by another action/effect. They then use the id to load child data from an api. This has always worked as expected, the child effects wait for the parent data to be populated before executing.

```<code>createEffect(() =>
  this.action$.pipe(
    ofType(accountActions.loadAccountAlerts),
    withLatestFrom(this.store.pipe(fromAccount.getAccountId)),
    mergeMap(([action, id]) => //Downloads Data from Api ands dispatches a success action)
)
</code>```

Today I refactored the reducer referenced by fromAccount to use createReducer using the new ngrx 8 syntax. Now suddenly my effects are no longer waiting for a value in withLatestFrom, they get the value of getAccountId as null.

Instead of loading data once the accountId is populated, all of the effects now run before the action that populates accountId is completed. I assume the way the reducer is initialized has changed, but what should I do to return to the original functionality.

Should I have ever been assuming that withLatestFrom against the store would work like that?

答:
If you have a default value in your store (BTW strongly suggest using selectors and not piping the whole store), it will be emitted, even if it is null. To ensure you have a value, use:

withLatestFrom(this.store.pipe(fromAccount.getAccountId).pipe(
  filter(id => !!id)
))
```

EDIT: NgRx calls the reducer first, then the effect. It sounds like you might have some other magic going on in the reducer, or perhaps this effect is reacting to the wrong action. Do you have a loadAccountAlertsSuccss action?

Body:
I had a working app using the original reducers, actions and effects of ngrx 7. Some of my effects read a value from the store using withLatestFrom, which is populated by another action/effect. They then use the id to load child data from an api. This has always worked as expected, the child effects wait for the parent data to be populated before executing.

createEffect(() =>
  this.action$.pipe(
    ofType(accountActions.loadAccountAlerts),
    withLatestFrom(this.store.pipe(fromAccount.getAccountId)),
    mergeMap(([action, id]) => //Downloads Data from Api ands dispatches a success action)
)

Today I refactored the reducer referenced by fromAccount to use createReducer using the new ngrx 8 syntax. Now suddenly my effects are no longer waiting for a value in withLatestFrom, they get the value of getAccountId as null.

Instead of loading data once the accountId is populated, all of the effects now run before the action that populates accountId is completed. I assume the way the reducer is initialized has changed, but what should I do to return to the original functionality.

Should I have ever been assuming that withLatestFrom against the store would work like that?

Body:
If you have a default value in your store (BTW strongly suggest using selectors and not piping the whole store), it will be emitted, even if it is null. To ensure you have a value, use:

withLatestFrom(this.store.pipe(fromAccount.getAccountId).pipe(
  filter(id => !!id)
))

EDIT: NgRx calls the reducer first, then the effect. It sounds like you might have some other magic going on in the reducer, or perhaps this effect is reacting to the wrong action. Do you have a loadAccountAlertsSuccss action?


问:
FFProbe.Analyse getting the error 'The system cannot find the file specified' when given a string
I want to compress every video within every drive and its sub-directories so the code I have used so far finds each drive and looks for .mp4 locations. Then it uses that list of strings to compress each file but it comes up with this error at:

var mediaInfo = FFProbe.Analyse(filePath: d)

and

.FromFileInput(d, verifyExists: true)

System.ComponentModel.Win32Exception: 'The system cannot find the file specified'

I checked what the .Analyse needs and it is a string and d is a string which has the right path location C:\\Users\\Helix\\Desktop\\apartment\\5 Little Monkeys Swinging In The Tree.mp4" which I thought would work but it does not seem to like it. What am I doing wrong?

I am also curious as to if GetDrives() works on network drives? And if it does would two servers running this code conflict when grabbing the same file at the same time?

```<code>using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MediaToolkit;
using MediaToolkit.Model;
using FFMpegCore;
using FFMpegCore.Enums;

namespace Video_Compressor_for_Servers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void CompAll_Click(object sender, EventArgs e)
        {

            //An empty list for later to collect strings
            List<string> file = new List<string>();

            //extract primary drives strings into a list since there could be more than just C:\
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                //The d.Name output has "Drive C:\" as the output. remove the "Drive " part first
                var replacement = d.Name.Replace("Drive ", "");

                /*Grab each files location with the Directory tool from the earlier IO libary.
                GetFiles is a subcommand of directory with options in the brackets. These
                options can be found in more detail by seaching for GetFiles C#*/
                string[] files = Directory.GetFiles(@"C:\Users\Helix\Desktop\apartment\","*.mp4", SearchOption.AllDirectories);// replacement//AllDirectories

                //Convert the array to a list
                List<string> templist = files.ToList();

                //Add them to the earlier empty list we made
                file.AddRange(templist);

            }

            //Now that we have paths to all the files we need we can now compress them
            foreach (string d in file)
            {
                var mediaInfo = FFProbe.Analyse(filePath: d);
                //Open the video file with MediaToolkit
                FFMpegArguments
                .FromFileInput(d, verifyExists: true)
                .OutputToFile(d, false, options => options
                    .WithVideoCodec(VideoCodec.LibX264)
                    .WithConstantRateFactor(21)
                    .WithAudioCodec(AudioCodec.Aac)
                    .WithVariableBitrate(4)
                    .WithVideoFilters(filterOptions => filterOptions
                        .Scale(VideoSize.Ed))
                    .WithFastStart())
                .ProcessSynchronously();
            }

        }
    }
}
</code>```

答:
You need to download both ffprobe.exe and ffmpeg.exe.
The executable is missing not the media one.</p>

Body:
I want to compress every video within every drive and its sub-directories so the code I have used so far finds each drive and looks for .mp4 locations. Then it uses that list of strings to compress each file but it comes up with this error at:

var mediaInfo = FFProbe.Analyse(filePath: d)

and

.FromFileInput(d, verifyExists: true)

System.ComponentModel.Win32Exception: 'The system cannot find the file specified'

I checked what the .Analyse needs and it is a string and d is a string which has the right path location C:\\Users\\Helix\\Desktop\\apartment\\5 Little Monkeys Swinging In The Tree.mp4" which I thought would work but it does not seem to like it. What am I doing wrong?

I am also curious as to if GetDrives() works on network drives? And if it does would two servers running this code conflict when grabbing the same file at the same time?

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MediaToolkit;
using MediaToolkit.Model;
using FFMpegCore;
using FFMpegCore.Enums;

namespace Video_Compressor_for_Servers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void CompAll_Click(object sender, EventArgs e)
        {

            //An empty list for later to collect strings
            List<string> file = new List<string>();

            //extract primary drives strings into a list since there could be more than just C:\
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                //The d.Name output has "Drive C:\" as the output. remove the "Drive " part first
                var replacement = d.Name.Replace("Drive ", "");

                /*Grab each files location with the Directory tool from the earlier IO libary.
                GetFiles is a subcommand of directory with options in the brackets. These
                options can be found in more detail by seaching for GetFiles C#*/
                string[] files = Directory.GetFiles(@"C:\Users\Helix\Desktop\apartment\","*.mp4", SearchOption.AllDirectories);// replacement//AllDirectories

                //Convert the array to a list
                List<string> templist = files.ToList();

                //Add them to the earlier empty list we made
                file.AddRange(templist);

            }

            //Now that we have paths to all the files we need we can now compress them
            foreach (string d in file)
            {
                var mediaInfo = FFProbe.Analyse(filePath: d);
                //Open the video file with MediaToolkit
                FFMpegArguments
                .FromFileInput(d, verifyExists: true)
                .OutputToFile(d, false, options => options
                    .WithVideoCodec(VideoCodec.LibX264)
                    .WithConstantRateFactor(21)
                    .WithAudioCodec(AudioCodec.Aac)
                    .WithVariableBitrate(4)
                    .WithVideoFilters(filterOptions => filterOptions
                        .Scale(VideoSize.Ed))
                    .WithFastStart())
                .ProcessSynchronously();
            }

        }
    }
}


问:
H2 Database result set is readonly
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

```<code>public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

答:
You have to put update query for update data in database but you are going with select query that is the problem.

Select query is used if you have to fetch data from database.

Update query is used for update data in database where data already stored in database but you just overwrite data.

Here down is modified code:

```<code>public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        PreparedStatement stmt = conn.prepareStatement("UPDATE BCSTASKS_SERVICE SET wasShown = ? WHERE status = ? AND wasShown = ?");
        stmt.setBoolean(1, true);
        stmt.setString(2, "Neu");
        stmt.setBoolean(3, false);
        stmt.executeUpdate();
        stmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

Title: H2 Database result set is readonly

Body:
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

Body:
You have to put update query for update data in database but you are going with select query that is the problem.

Select query is used if you have to fetch data from database.

Update query is used for update data in database where data already stored in database but you just overwrite data.

Here down is modified code:

public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        PreparedStatement stmt = conn.prepareStatement("UPDATE BCSTASKS_SERVICE SET wasShown = ? WHERE status = ? AND wasShown = ?");
        stmt.setBoolean(1, true);
        stmt.setString(2, "Neu");
        stmt.setBoolean(3, false);
        stmt.executeUpdate();
        stmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}


问:
Need help with getting friends of Twitter user; using PHP and Epiphany RESTful PHP Framework
I am trying to get friends of the username I am passing in. Will not work, have tried everything I can think of. Please look over and give me some suggestions:

Although it gives no errors, a blank page is displayed. No usernames are echoed.

```<code>include 'lib/EpiCurl.php';
include 'lib/EpiOAuth.php';
include 'lib/EpiTwitter.php';
include 'lib/secret.php';

$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$oauth_token = 'xxxx'; //Yes I filled these out in the actual code
$oauth_token_secret = 'xxxx'; //Yes I filled these out in the actual code

$twitterObj->setToken($oauth_token, $oauth_token_secret);
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
$twitterUsername = $twitterInfo->screen_name;

getFriends('csti');

function getFriends ($username){

global $twitterObj, $oauth_token, $oauth_token_secret, $twitterUsername;

$twitterFriends = $twitterObj->get('/statuses/friends.json');
$twitterFriends->response; //not sure if this is necessary but doesnt work either way.

    try{
      foreach($twitterFriends as $friend) {
        echo $friend->screen_name;
      }
    }catch(EpiTwitterException $e){
      echo $e->getMessage();
    }
}
</code>```

答:
You've got a bit of weirdness in your code.

Your passing the parameter $username and the string 'csti' but you don't seem to be using it anywhere in the function.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get friends of the username I am passing in. Will not work, have tried everything I can think of. Please look over and give me some suggestions:

Although it gives no errors, a blank page is displayed. No usernames are echoed.

include 'lib/EpiCurl.php';
include 'lib/EpiOAuth.php';
include 'lib/EpiTwitter.php';
include 'lib/secret.php';

$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$oauth_token = 'xxxx'; //Yes I filled these out in the actual code
$oauth_token_secret = 'xxxx'; //Yes I filled these out in the actual code

$twitterObj->setToken($oauth_token, $oauth_token_secret);
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
$twitterUsername = $twitterInfo->screen_name;

getFriends('csti');

function getFriends ($username){

global $twitterObj, $oauth_token, $oauth_token_secret, $twitterUsername;

$twitterFriends = $twitterObj->get('/statuses/friends.json');
$twitterFriends->response; //not sure if this is necessary but doesnt work either way.

    try{
      foreach($twitterFriends as $friend) {
        echo $friend->screen_name;
      }
    }catch(EpiTwitterException $e){
      echo $e->getMessage();
    }
}


问:
Get List of all the dags in python
I have a list of dags that are hosted on Airflow. I want to get the name of the dags in a AWS lambda function so that I can use the names and trigger the dag using experimental API. I am stuck on getting the names of the dag.
Any help would be appreciated</p>

答:
Since Airflow 2.0, the airflow list_dags command is now:

```<code>airflow dags list [-h] [-o table, json, yaml, plain] [-S SUBDIR] [-v]
</code>```

with the following named arguments:

-o, --output

Possible choices: table, json, yaml, plain

Output format. Allowed values: json, yaml, plain, table (default:
table)

Default: “table”

-S, --subdir

File location or directory from which to look for the dag. Defaults to ‘[AIRFLOW_HOME]/dags’ where [AIRFLOW_HOME] is the value you set for ‘AIRFLOW_HOME’ config you set in ‘airflow.cfg’

Default: “[AIRFLOW_HOME]/dags”

-v, --verbose

Make logging output more verbose

Default: False

See:

Airflow CLI changes in 2.0

Command Line Interface and Environment Variables Reference

Title: Get List of all the dags in python

Body:
Since Airflow 2.0, the airflow list_dags command is now:

airflow dags list [-h] [-o table, json, yaml, plain] [-S SUBDIR] [-v]

with the following named arguments:

-o, --output

Possible choices: table, json, yaml, plain

Output format. Allowed values: json, yaml, plain, table (default:
table)

Default: “table”

-S, --subdir

File location or directory from which to look for the dag. Defaults to ‘[AIRFLOW_HOME]/dags’ where [AIRFLOW_HOME] is the value you set for ‘AIRFLOW_HOME’ config you set in ‘airflow.cfg’

Default: “[AIRFLOW_HOME]/dags”

-v, --verbose

Make logging output more verbose

Default: False

See:

Airflow CLI changes in 2.0

Command Line Interface and Environment Variables Reference


问:
Can values of geom_function arguments (e.g. fill colours) be added to ggplot2 themes?
For consistent data presentation I'm looking to create a new theme which can be used by anyone in my team using R to easily present plots in the same format. I'm using the stata theme as the base, and have so far been able to get the basic plot elements the way I want with the following;

```<code>theme_brand <- function(){
    font <- "Gotham"

    theme_stata() %+replace%

    theme(
      plot.background = element_rect(fill = "white"),

      plot.title = element_text(
                    colour="#555862",
                    family = font,
                    size = 16),

      axis.title = element_text(
                   family = font,
                   size = 14,
                   colour = "#555862"),

      axis.text = element_text(
                   family = font,
                   size = 12),
      axis.line = element_line (colour="#AAACB1"),
      axis.ticks.x = element_line(colour= "#AAACB1"),
      axis.ticks.y = element_line(colour= "#AAACB1"),
      panel.grid.major = element_line(colour = "#AAACB1"),
      panel.grid.minor = element_line(colour = "#D5D5D8"),
      panel.border = element_blank()
    )
}
</code>```

What I would also like to do is set default colours, line styles etc for chart elements such as boxplots, labels and so on. While I've not stumbled on anything explicitly saying this isn't possible, I also haven't found anything showing how it can be done and I note that none of the themes supplied within ggthemes seem to have this functionality. So can it be done? And if not, is there an alternative way to ensure geom_function plots are presented consistently?

答:
You can’t add color palettes to themes, but you can change global defaults by setting a scale function or vector of colors via setOption(). e.g.:

```<code>setOption(“ggplot.fill.discrete”, scales::brewer_pal(palette = “Dark2”)(8))
setOption(“ggplot.color.continuous”, ggplot2::scale_color_viridis_c)
</code>```

Body:
For consistent data presentation I'm looking to create a new theme which can be used by anyone in my team using R to easily present plots in the same format. I'm using the stata theme as the base, and have so far been able to get the basic plot elements the way I want with the following;

theme_brand <- function(){
    font <- "Gotham"

    theme_stata() %+replace%

    theme(
      plot.background = element_rect(fill = "white"),

      plot.title = element_text(
                    colour="#555862",
                    family = font,
                    size = 16),

      axis.title = element_text(
                   family = font,
                   size = 14,
                   colour = "#555862"),

      axis.text = element_text(
                   family = font,
                   size = 12),
      axis.line = element_line (colour="#AAACB1"),
      axis.ticks.x = element_line(colour= "#AAACB1"),
      axis.ticks.y = element_line(colour= "#AAACB1"),
      panel.grid.major = element_line(colour = "#AAACB1"),
      panel.grid.minor = element_line(colour = "#D5D5D8"),
      panel.border = element_blank()
    )
}

What I would also like to do is set default colours, line styles etc for chart elements such as boxplots, labels and so on. While I've not stumbled on anything explicitly saying this isn't possible, I also haven't found anything showing how it can be done and I note that none of the themes supplied within ggthemes seem to have this functionality. So can it be done? And if not, is there an alternative way to ensure geom_function plots are presented consistently?

Body:
You can’t add color palettes to themes, but you can change global defaults by setting a scale function or vector of colors via setOption(). e.g.:

setOption(“ggplot.fill.discrete”, scales::brewer_pal(palette = “Dark2”)(8))
setOption(“ggplot.color.continuous”, ggplot2::scale_color_viridis_c)


问:
How to write code to query sequelize model with where parameter in nested table
My database has a users, likes, dislikes, parcels table.

The likes, dislikes, parcels tables are linked to the users table by the user_id field, which is present in each of the linked tables.

How to sort likes in the users table that have deleted = false field values.
If I make a request to the users model where

```<code>let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
    },
    {
      model: Dislikes,
      as: "dislikes",
    },
    {
      model: Parcels,
      as: "parcels",
    },
  ],
  where: {
    deleted: false,
  },
});
</code>```

In this case, I get all the values of the users table, where the field deleted = false.

```<code>    let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
      where: {
        deleted: false,
      },
    },
    {
      model: Dislikes,
      as: "dislikes",

    },
    {
      model: Parcels,
      as: "parcels",

    },
  ],
  where: {
    deleted: false,
  },
});
</code>```

The text of the request that sequelize generates

SELECT users.id_user,
users.name_1,
users.name_2,
users.name_3,
users.nation,
users.citizenship,
users.dateOfBirth,
users.placeOfWork,
users.education,

users.url_photo,
users.deleted,
likes.id_like AS likes.id_like,
likes.id_user AS likes.id_user,
likes.date AS likes.date,
likes.deleted AS likes.deleted,
dislikes.id_dislike AS dislikes.id_dislike,
dislikes.id_user AS dislikes.id_user,
dislikes.date AS dislikes.date,
parcels.id_parcel AS parcels.id_parcel,
parcels.id_user AS parcels.id_user,
parcels.date AS parcels.date,
parcels.deleted AS parcels.deleted
FROM users AS users
INNER JOIN likes AS likes ON users.id_user = likes.id_user
AND likes.deleted = FALSE
LEFT OUTER JOIN dislikes AS dislikes ON users.id_user = dislikes.id_user
LEFT OUTER JOIN parcels AS parcels ON users.id_user = parcels.id_user
WHERE users.deleted = FALSE;

In this case, I get only those records of the users table that have records in the likes table, respectively, all records in the user table and in the likes table have the field deleted = false.

However, I need to retrieve all records from the users table whether they have related records from the likes table or not. And also all records must have a field deleted - false

答:
I'm not sure that I got your question, but it seems that required: false is what you need:

let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
      where: {
        deleted: false,
      },
      required: false,
    },
    {
      model: Dislikes,
      as: "dislikes",

    },
    {
      model: Parcels,
      as: "parcels",

    },
  ],
  where: {
    deleted: false,
  },
});
```

Body:
My database has a users, likes, dislikes, parcels table.

The likes, dislikes, parcels tables are linked to the users table by the user_id field, which is present in each of the linked tables.

How to sort likes in the users table that have deleted = false field values.
If I make a request to the users model where

let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
    },
    {
      model: Dislikes,
      as: "dislikes",
    },
    {
      model: Parcels,
      as: "parcels",
    },
  ],
  where: {
    deleted: false,
  },
});

In this case, I get all the values of the users table, where the field deleted = false.

    let users = await models.users.findAll({
  include: [
    {
      model: Likes,
      as: "likes",
      where: {
        deleted: false,
      },
    },
    {
      model: Dislikes,
      as: "dislikes",

    },
    {
      model: Parcels,
      as: "parcels",

    },
  ],
  where: {
    deleted: false,
  },
});

The text of the request that sequelize generates

SELECT users.id_user,
users.name_1,
users.name_2,
users.name_3,
users.nation,
users.citizenship,
users.dateOfBirth,
users.placeOfWork,
users.education,

users.url_photo,
users.deleted,
likes.id_like AS likes.id_like,
likes.id_user AS likes.id_user,
likes.date AS likes.date,
likes.deleted AS likes.deleted,
dislikes.id_dislike AS dislikes.id_dislike,
dislikes.id_user AS dislikes.id_user,
dislikes.date AS dislikes.date,
parcels.id_parcel AS parcels.id_parcel,
parcels.id_user AS parcels.id_user,
parcels.date AS parcels.date,
parcels.deleted AS parcels.deleted
FROM users AS users
INNER JOIN likes AS likes ON users.id_user = likes.id_user
AND likes.deleted = FALSE
LEFT OUTER JOIN dislikes AS dislikes ON users.id_user = dislikes.id_user
LEFT OUTER JOIN parcels AS parcels ON users.id_user = parcels.id_user
WHERE users.deleted = FALSE;

In this case, I get only those records of the users table that have records in the likes table, respectively, all records in the user table and in the likes table have the field deleted = false.

However, I need to retrieve all records from the users table whether they have related records from the likes table or not. And also all records must have a field deleted - false


问:
Can I create a template within XSLT?
I want to create a ASP.NET user control from an XML using XSLT.
Currently I really put the result together bit by bit:

```<code><xsl:template match="TextField">
   <xsl:apply-templates select="Label" />
   <xsl:text><![CDATA[<asp:TextBox ID="]]></xsl:text>
   <xsl:value-of select="@id"/>
   <xsl:if test="@defaultValue">
      <xsl:text><![CDATA[" value="]]></xsl:text>
      <xsl:value-of select="@defaultValue"/>
   </xsl:if>
   <xsl:text><![CDATA[" runat="server"></asp:TextBox>]]></xsl:text>
   <xsl:copy-of select="$br"/>
</xsl:template>
</code>```

It would be rally cool if I could instead do something like this:

```<code><xsl:template match="TextField">
   <xsl:apply-templates select="Label" />

   <xsl:variable name="localTemplate" select="expression">
      <xsl:text><![CDATA[
         <asp:TextBox ID="{theID}" value="{theDefaultValue}" runat="server"></asp:TextBox>
      ]]></xsl:text>
      <xsl:copy-of select="$br"/>
   </xsl:variable>

   <!-- replace {theID} and {theDefaultValue} from the corresponding
       values of the input XML and then return the content of that
       variable
   -->
</xsl:template>
</code>```

Because that seems much cleaner and more easy to maintain later on when there is the need to change the html structure.

Is there a way to achieve this and if yes, how would that look like?
I don't need a working solution, just some hints on what to do.

Update: Here is some sample input XML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="XmlForm.xsd">

   <Validation enabled="false" enableValidationSummary="true" />
   <FieldSet>
      <TextField id="firstInput" css-class="textfield-css-class" />

      <TextField id="secondInput" defaultValue="Wrdlbmrpft">
         <Label translatable="true" >Label Text</Label>
      </TextField>
   </FieldSet>
</Form>
</code>```

The output should look like this:

```<code><%@ Control Language="C#" AutoEventWireup="true" Inherits="DevelopmentWeb.WebUserControl1" %>
<asp:TextBox runat="server" ID="firstInput" CssClass="textfield-css-class"></asp:TextBox>
<asp:Label runat="server" AssociatedControlID="secondInput">Label Text</asp:Label>
<asp:TextBox runat="server" ID="secondInput">Wrdlbrmpft</asp:TextBox>
</code>```

答:
I don't think there would be any reason to create a variable. You should be able to do something like this:

```<code>  <xsl:template match="TextField">
    <xsl:apply-templates select="Label" />
    <asp:TextBox ID="{@id}" value="{@defaultValue}" runat="server"/>
    <xsl:copy-of select="$br"/>
  </xsl:template>
</code>```

or this:

```<code>  <xsl:template match="TextField">
    <xsl:apply-templates select="Label" />
    <asp:TextBox runat="server">
      <xsl:if test="@id">
        <xsl:attribute name="ID">
          <xsl:value-of select="@id"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:if test="@defaultValue">
        <xsl:attribute name="value">
          <xsl:value-of select="@defaultValue"/>
        </xsl:attribute>
      </xsl:if>
    </asp:TextBox>
    <xsl:copy-of select="$br"/>
  </xsl:template>
</code>```

Title: Can I create a template within XSLT?

Body:
I want to create a ASP.NET user control from an XML using XSLT.
Currently I really put the result together bit by bit:

<xsl:template match="TextField">
   <xsl:apply-templates select="Label" />
   <xsl:text><![CDATA[<asp:TextBox ID="]]></xsl:text>
   <xsl:value-of select="@id"/>
   <xsl:if test="@defaultValue">
      <xsl:text><![CDATA[" value="]]></xsl:text>
      <xsl:value-of select="@defaultValue"/>
   </xsl:if>
   <xsl:text><![CDATA[" runat="server"></asp:TextBox>]]></xsl:text>
   <xsl:copy-of select="$br"/>
</xsl:template>

It would be rally cool if I could instead do something like this:

<xsl:template match="TextField">
   <xsl:apply-templates select="Label" />

   <xsl:variable name="localTemplate" select="expression">
      <xsl:text><![CDATA[
         <asp:TextBox ID="{theID}" value="{theDefaultValue}" runat="server"></asp:TextBox>
      ]]></xsl:text>
      <xsl:copy-of select="$br"/>
   </xsl:variable>

</xsl:template>

Because that seems much cleaner and more easy to maintain later on when there is the need to change the html structure.

Is there a way to achieve this and if yes, how would that look like?
I don't need a working solution, just some hints on what to do.

Update: Here is some sample input XML:

<?xml version="1.0" encoding="utf-8" ?>
<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="XmlForm.xsd">

   <Validation enabled="false" enableValidationSummary="true" />
   <FieldSet>
      <TextField id="firstInput" css-class="textfield-css-class" />

      <TextField id="secondInput" defaultValue="Wrdlbmrpft">
         Label Text
      </TextField>
   </FieldSet>
</Form>

The output should look like this:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="DevelopmentWeb.WebUserControl1" %>
<asp:TextBox runat="server" ID="firstInput" CssClass="textfield-css-class"></asp:TextBox>
<asp:Label runat="server" AssociatedControlID="secondInput">Label Text</asp:Label>
<asp:TextBox runat="server" ID="secondInput">Wrdlbrmpft</asp:TextBox>

Body:
I don't think there would be any reason to create a variable. You should be able to do something like this:

  <xsl:template match="TextField">
    <xsl:apply-templates select="Label" />
    <asp:TextBox ID="{@id}" value="{@defaultValue}" runat="server"/>
    <xsl:copy-of select="$br"/>
  </xsl:template>

or this:

  <xsl:template match="TextField">
    <xsl:apply-templates select="Label" />
    <asp:TextBox runat="server">
      <xsl:if test="@id">
        <xsl:attribute name="ID">
          <xsl:value-of select="@id"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:if test="@defaultValue">
        <xsl:attribute name="value">
          <xsl:value-of select="@defaultValue"/>
        </xsl:attribute>
      </xsl:if>
    </asp:TextBox>
    <xsl:copy-of select="$br"/>
  </xsl:template>


问:
3d matrix multiplication into multiple 2d matrix multiplications
I have two 3d matrices X and Y both of which have the shape (5, 1825, 77). I'd like to do five 2d matrix multiplications, i.e., X[i, :, :]@Y[i, :, :].T without using a for loop. Is there a way to do this in numpy?

答:
This is interesting for those (like me) who try to avoid for loops at any cost:

```<code>shape = 5, 1825, 77
X = np.random.random(shape)
Y = np.random.random(shape)

p_for = np.empty((shape[0], shape[1], shape[1]))
for i in range(shape[0]):
    p_for[i] = X[i] @ Y[i].T

p_matmul = X @ np.moveaxis(Y, -1, 1)
assert np.allclose(p_for, p_matmul)

p_einsum = np.einsum("ijk,ilk->ijl", X, Y)
assert np.allclose(p_for, p_einsum)
</code>```

The tree methods produce the same result, but, as @JérômeRichard points out:

```<code>%%timeit
prod = np.empty((shape[0], shape[1], shape[1]))
for i in range(5):
    prod[i] = X[i, :, :] @ Y[i, :, :].T
50.4 ms ± 7.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit X @ np.moveaxis(Y, -1, 1)
115 ms ± 1.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit np.einsum("ijk,ilk->ijl", X, Y)
544 ms ± 3.22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
This is interesting for those (like me) who try to avoid for loops at any cost:

shape = 5, 1825, 77
X = np.random.random(shape)
Y = np.random.random(shape)

p_for = np.empty((shape[0], shape[1], shape[1]))
for i in range(shape[0]):
    p_for[i] = X[i] @ Y[i].T

p_matmul = X @ np.moveaxis(Y, -1, 1)
assert np.allclose(p_for, p_matmul)

p_einsum = np.einsum("ijk,ilk->ijl", X, Y)
assert np.allclose(p_for, p_einsum)

The tree methods produce the same result, but, as @JérômeRichard points out:

%%timeit
prod = np.empty((shape[0], shape[1], shape[1]))
for i in range(5):
    prod[i] = X[i, :, :] @ Y[i, :, :].T
50.4 ms ± 7.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit X @ np.moveaxis(Y, -1, 1)
115 ms ± 1.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit np.einsum("ijk,ilk->ijl", X, Y)
544 ms ± 3.22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Delete key and value form a dictionary, if it is longer than 5 symbols
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

```

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

答:
Without converting to string twice:</p>
```<code>{sk: sv
 for k, v in file1data.items()
 if len(sk := str(k)) <= 5
 if len(sv := str(v)) <= 5}
</code>```

Body:
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

Body:
Without converting to string twice:

{sk: sv
 for k, v in file1data.items()
 if len(sk := str(k)) <= 5
 if len(sv := str(v)) <= 5}


问:
Passing JSON file in Postgres with Python
```<code>connection = psycopg2.connect("dbname=db1 user=postgres password=postgres")
cursor = connection.cursor()
cursor.execute("set search_path to public")

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_recordset(NULL::table1, %s);
"""

# change .execute(query_sql) to .execute(query_sql, (data,))
cursor.execute(query_sql, (data,))
connection.commit()
</code>```

So I am trying to pass the contents of "json_template.json" to a Postgres table, but when I do I get the this error:
psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object

I've created the table through psql cmd. Also, here are the contents of my json_template file:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}
Attaching screenshot: json_template.json.

Did some research on the error, however nothing came out. Also tried to rewrite the code in other fashion several times  - still the same error.

Thank you in advance!

Body:
connection = psycopg2.connect("dbname=db1 user=postgres password=postgres")
cursor = connection.cursor()
cursor.execute("set search_path to public")

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_recordset(NULL::table1, %s);
"""

# change .execute(query_sql) to .execute(query_sql, (data,))
cursor.execute(query_sql, (data,))
connection.commit()

So I am trying to pass the contents of "json_template.json" to a Postgres table, but when I do I get the this error:
psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object

I've created the table through psql cmd. Also, here are the contents of my json_template file:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}
Attaching screenshot: json_template.json.

Did some research on the error, however nothing came out. Also tried to rewrite the code in other fashion several times  - still the same error.

Thank you in advance!

Body:
I just changed the JSON file from:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}

To:

[
    {
        "key": "A128",
        "value": "15.6",
        "ts": "2020-10-07 13:28:43.399620+02:00"
    }
]

And it worked. Thank you all for the help!


问:
Chartjs with Typescript: The types of 'interaction.mode' are incompatible between these types
I want to create a React Functional Component with Typescript that displays a chart using chartjs.

My parent passes options and data to the child component that renders the line chart.

When trying to pass the options object I get the following typescript error:

```<code>The types of 'interaction.mode' are incompatible between these types.
Type 'string' is not assignable to type '"index" | "dataset" | "point" | "nearest" | "x" | "y" | undefined'.
</code>```

Which is weird because my options look like this:

```<code>const options = {
    ...
    interaction: {
        ...
        mode: "index"
    },
    ...
}
</code>```

Why is "index" not assignable to "index" | ...?

I tried to recreate the error in stackblitz and although the error don't pop up in the preview it still seem to occur:

Link to Stackblitz

答:
You need to define type of options:</p>
```<code>  import { ChartOptions } from 'chart.js';

  const options: ChartOptions = {
    interaction: {
      intersect: false,
      mode: 'index',
    },
  };
</code>```

Body:
I want to create a React Functional Component with Typescript that displays a chart using chartjs.

My parent passes options and data to the child component that renders the line chart.

When trying to pass the options object I get the following typescript error:

The types of 'interaction.mode' are incompatible between these types.
Type 'string' is not assignable to type '"index" | "dataset" | "point" | "nearest" | "x" | "y" | undefined'.

Which is weird because my options look like this:

const options = {
    ...
    interaction: {
        ...
        mode: "index"
    },
    ...
}

Why is "index" not assignable to "index" | ...?

I tried to recreate the error in stackblitz and although the error don't pop up in the preview it still seem to occur:

Link to Stackblitz

Body:
You need to define type of options:

  import { ChartOptions } from 'chart.js';

  const options: ChartOptions = {
    interaction: {
      intersect: false,
      mode: 'index',
    },
  };


问:
ASP.NET Core middleware vs filters
After reading about ASP.NET Core middleware, I am confused about when I should use filters and when I should use middleware as they seem to achieve the same goal.
When should middleware be used instead of filters?</p>

答:
Filter pipeline is similar to middleware pipeline in many ways, but they also have some differences that should be considered when deciding which approach to be used.

What are the similarities:

Incoming requests pass through a middleware component and outgoing responses to those requests are passing again through the same middleware when going to the client. Some filters (resource, action, and result) are also two-way, others (authorization and exception) run only once for a request, and page filters (Razor pages specific) run three times.

Middlewares can short-circuit a request by directly returning a response, instead of executing the entire middleware pipeline and not passing the request down to later middlewares. Filters can also short-circuit the filter pipeline by directly returning a response.

Middlewares are used for cross-cutting concerns (eg: logging, performance profiling or exception handling). Filters are also used for dealing with cross-cutting concerns.

What are the differences:

A middleware can run for all requests while filters will only run for requests that reach the EndpointMiddleware and execute an action from an API Controller or a Razor Page.

Filters have access to MVC components (eg: ModelState or IActionResults). Middleware works at a lower level compared to filters and is independent of MVC and Razor Pages, so it can't use any of those related components.

Filters are designed to be applied to a subset of requests, not to all of them. For instance, we can apply a filter on a single controller or a single Razor Page. In contrast, middlewares don't have this kind of design.

So, when trying to figure out what should use: filters or middlewares, the answer should come from the above comparison.
As a TL;DR:

middleware is the more general concept, which operates on lower-level abstractions like HttpContext, so can be applied in a wider area. Also we should be aware of the fact that the functionality we need to implement has no MVC-specific requirements

filters can enable us the usage of MVC-constructs and can be used for implementing custom and specific behavior for some MVC actions. It is not so general as middleware.

Title: ASP.NET Core middleware vs filters


问:
Beautiful Soup Find href text based on partial attribute value
I am trying to identify tags in an html document based on part of the attribute value.

I'm interested in any 'a' under 'tr' tag as long as it starts or has :

"AnnoncesImmobilier.asp?rech_cod_pay=" in the href attribute.

HTML source :

```<code><tr bgcolor="#f1efe2" class="Tableau1" valign="middle">
   <td bgcolor="#294a73" height="20"><img alt="" height="1" src="/images/space.gif" width="1"/></td>
   <td>  <a href="AnnoncesImmobilier.asp?rech_cod_pay=TN&rech_cod_vil=10117&rech_cod_loc=1011701" onmouseover="return escape('<b>Gouvernorat</b> : Tunis<br/><b>Délégation</b> : La Marsa<br/><b>Localité</b> : Berge Du Lac');">Berge Du Lac</a> </td>
   <td bgcolor="#294a73"><img alt="" height="1" src="/images/space.gif" width="1"/></td>
   <td onmouseover="return escape('<b>Rubrique</b> : Offres<br/><b>Nature</b> : Terrain<br/><b>Type</b> : Terrain nu');" style="CURSOR:pointer;">  Terrain</td>
</code>```

will give ad_title = "Berge Du Lac"

In the source HTML , each "tr" tag with class "Tableau1" contains an ad with different tr , a , tags for title, price, description etc...

Below is my code :

```<code>import re
from bs4 import BeautifulSoup

# The URL to get data from
URL = 'http://www.tunisie-annonce.com/AnnoncesImmobilier.asp'

data = requests.get(URL)

soup = BeautifulSoup(data.content, "html.parser")

# Variable to extract the ads
ads = soup.find_all("tr", {"class":"Tableau1"})

for ad in ads:
    ad_title = ads.find(text=re.compile('AnnoncesImmobilier.asp?rech_cod_pay=')).parent.get_text())
print(title)
</code>```

ad_title = ads.find(text=re.compile('AnnoncesImmobilier.asp?rech_cod_pay=')).parent.get_text())  is the last snippet that I tried to retrieve the text, but neither this or previous code worked for me.

How can i proceed ?

答:
You do not need a regex here, you can use

titles = []
for ad in ads:
    links = ad.find_all('a', href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h)
    for link in links:
        titles.append(link.get_text())

print(titles)
```
<p>If you want to get a unique list of titles, use a set:</p>
<pre class="lang-py prettyprint-override"><code>titles = set()
for ad in ads:
    links = ad.find_all('a', href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h)
    for link in links:
        titles.add(link.get_text())
</code>```

In both cases, href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h makes sure there is a href attribute and it contains a AnnoncesImmobilier.asp?rech_cod_pay= string.

Body:
I am trying to identify tags in an html document based on part of the attribute value.

I'm interested in any 'a' under 'tr' tag as long as it starts or has :

"AnnoncesImmobilier.asp?rech_cod_pay=" in the href attribute.

HTML source :

     <a href="AnnoncesImmobilier.asp?rech_cod_pay=TN&rech_cod_vil=10117&rech_cod_loc=1011701" onmouseover="return escape('Gouvernorat : Tunis
Délégation : La Marsa
Localité : Berge Du Lac');">Berge Du Lac

   <td onmouseover="return escape('Rubrique : Offres
Nature : Terrain
Type : Terrain nu');" style="CURSOR:pointer;">  Terrain

will give ad_title = "Berge Du Lac"

In the source HTML , each "tr" tag with class "Tableau1" contains an ad with different tr , a , tags for title, price, description etc...

Below is my code :

import re
from bs4 import BeautifulSoup

# The URL to get data from
URL = 'http://www.tunisie-annonce.com/AnnoncesImmobilier.asp'

data = requests.get(URL)

soup = BeautifulSoup(data.content, "html.parser")

# Variable to extract the ads
ads = soup.find_all("tr", {"class":"Tableau1"})

for ad in ads:
    ad_title = ads.find(text=re.compile('AnnoncesImmobilier.asp?rech_cod_pay=')).parent.get_text())
print(title)

ad_title = ads.find(text=re.compile('AnnoncesImmobilier.asp?rech_cod_pay=')).parent.get_text())  is the last snippet that I tried to retrieve the text, but neither this or previous code worked for me.

How can i proceed ?

Body:
You do not need a regex here, you can use

titles = []
for ad in ads:
    links = ad.find_all('a', href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h)
    for link in links:
        titles.append(link.get_text())

print(titles)

If you want to get a unique list of titles, use a set:

titles = set()
for ad in ads:
    links = ad.find_all('a', href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h)
    for link in links:
        titles.add(link.get_text())

In both cases, href=lambda h: h and "AnnoncesImmobilier.asp?rech_cod_pay=" in h makes sure there is a href attribute and it contains a AnnoncesImmobilier.asp?rech_cod_pay= string.


问:
typeof object of array of object in typescript?
How do I replace any below with options's object shape below?

```<code>interface selectComponentProps {
  options: {
    label: string;
    value: string;
  }[];
}

const SelectComponent: React.FC<selectComponentProps> = ({
   options,
}) => {
  const handleChange = (selectedOption: any) => { //here

  };

  return (
    <Select
      options={options}
    />
  );
};
</code>```

答:
You can extract the model for a single option to a separate interface:

```<code>interface selectComponentProps {
  options: selectComponentPropsOption[];
}

interface selectComponentPropsOption {
  label: string;
  value: string;
}
</code>```

Then you can replace any with selectComponentPropsOption.

Body:
How do I replace any below with options's object shape below?

interface selectComponentProps {
  options: {
    label: string;
    value: string;
  }[];
}

const SelectComponent: React.FC<selectComponentProps> = ({
   options,
}) => {
  const handleChange = (selectedOption: any) => { //here

  };

  return (
    <Select
      options={options}
    />
  );
};

Body:
You can extract the model for a single option to a separate interface:

interface selectComponentProps {
  options: selectComponentPropsOption[];
}

interface selectComponentPropsOption {
  label: string;
  value: string;
}

Then you can replace any with selectComponentPropsOption.


问:
No Module named "Fastai" when trying to deploy fastai model on sagemaker
I have trained and built a Fastai(v1) model and exported it as a .pkl file.
Now i want to deploy this model for inference in Amazon Sagemaker

Following the Sagemaker documentation for Pytorch model [https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#write-an-inference-script][1]

Steps taken

Folder structure

```
Sagemaker/
       export.pkl
       code/
           inference.py
           requirement.txt
```
```
requirement.txt

    spacy==2.3.4
    torch==1.4.0
    torchvision==0.5.0
    fastai==1.0.60
    numpy

```

Command i used to create the zip file

```
    cd Sagemaker/
    tar -czvf /tmp/model.tar.gz ./export.pkl ./code
```

This would generate a model.tar.gz file and i upload it to S3 bucket

To deploy this i used the python sagemaker SDK

```<code>
    from sagemaker.pytorch import PyTorchModel
        role = "sagemaker-role-arn"
        model_path = "s3 key for the model.tar.gz file that i created above"
        pytorch_model = PyTorchModel(model_data=model_path,role=role,`entry_point='inference.py',framework_version="1.4.0", py_version="py3")

        predictor = pytorch_model.deploy(instance_type='ml.c5.large', initial_instance_count=1)

</code>```

After executing the above code i see that the model is created in sagemaker and deployed but i end up getting an error running the inference

```<code>
    botocore.errorfactory.ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (500) from primary with message "No module named 'fastai'
    Traceback (most recent call last):
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 110, in transform
        self.validate_and_initialize(model_dir=model_dir)
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 157, in validate_and_initialize
        self._validate_user_module_and_set_functions()
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 170, in _validate_user_module_and_set_functions
        user_module = importlib.import_module(user_module_name)
      File "/opt/conda/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "/opt/ml/model/code/inference.py", line 2, in <module>
        from fastai.basic_train import load_learner, DatasetType, Path
    ModuleNotFoundError: No module named 'fastai'

</code>```

Clearly the fastai module doesn't get downloaded what is the cause for this and what am i doing wrong in this case

答:
To troubleshoot such issues, you should check the CloudWatch logs for the endpoint.

You should check the logs first to see if the requirements.txt was found and installed or if there were any dependency errors.

For packaging the model and your inference scripts, it's recommended to have two files:

model.tar.gz which has the model and the model files.

sourcedir.tar.gz and use SageMaker environment variable SAGEMAKER_SUBMIT_DIRECTORY to point to the file location on S3 s3://bucket/prefix/sourcedir.tar.gz. You can point to the file name using SAGEMAKER_PROGRAM to be inference.py.

Note: when you use source_dir in PyTorchModel, the SDK will package the source_dir, upload it to s3 and define SAGEMAKER_SUBMIT_DIRECTORY.

Body:
I have trained and built a Fastai(v1) model and exported it as a .pkl file.
Now i want to deploy this model for inference in Amazon Sagemaker

Following the Sagemaker documentation for Pytorch model [https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#write-an-inference-script][1]

Steps taken

Folder structure

Sagemaker/
       export.pkl
       code/
           inference.py
           requirement.txt

requirement.txt

    spacy==2.3.4
    torch==1.4.0
    torchvision==0.5.0
    fastai==1.0.60
    numpy

Command i used to create the zip file

    cd Sagemaker/
    tar -czvf /tmp/model.tar.gz ./export.pkl ./code

This would generate a model.tar.gz file and i upload it to S3 bucket

To deploy this i used the python sagemaker SDK

    from sagemaker.pytorch import PyTorchModel
        role = "sagemaker-role-arn"
        model_path = "s3 key for the model.tar.gz file that i created above"
        pytorch_model = PyTorchModel(model_data=model_path,role=role,`entry_point='inference.py',framework_version="1.4.0", py_version="py3")

        predictor = pytorch_model.deploy(instance_type='ml.c5.large', initial_instance_count=1)

After executing the above code i see that the model is created in sagemaker and deployed but i end up getting an error running the inference

    botocore.errorfactory.ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (500) from primary with message "No module named 'fastai'
    Traceback (most recent call last):
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 110, in transform
        self.validate_and_initialize(model_dir=model_dir)
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 157, in validate_and_initialize
        self._validate_user_module_and_set_functions()
      File "/opt/conda/lib/python3.6/site-packages/sagemaker_inference/transformer.py", line 170, in _validate_user_module_and_set_functions
        user_module = importlib.import_module(user_module_name)
      File "/opt/conda/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "/opt/ml/model/code/inference.py", line 2, in <module>
        from fastai.basic_train import load_learner, DatasetType, Path
    ModuleNotFoundError: No module named 'fastai'

Clearly the fastai module doesn't get downloaded what is the cause for this and what am i doing wrong in this case


问:
How to test route queryParams in Angular?
I have a components gets a value from the params of ActivatedRoute.

the components looks like

```<code>constructor(
  private route: ActivatedRoute,
  private router: Router,
  private marketService: MarketService,
) { }

ngOnInit() {
  // New Post
  this.route.queryParams.pipe(
    filter(params => params.type))
    .subscribe(
      params => {
        this.isNew = true;
        this.brd_path = params.type;
        this.category_path = this.route.snapshot.params['category_path'];
      },
      () => { },
      () => { }
    );

  // Edit Post
  this.route.queryParams.pipe(
    filter(params => params.no))
    .subscribe(
      params => {
        if (!this.marketService.getCurrentMarket()) {
          this.router.navigateByUrl('');
          return;
        }
        this.isNew = false;
        this.market_no = +params.no;
      }
    );
}
</code>```

I want to test depend params
isNew, brd_path, category_path, market_no

TEST code

```<code>describe('SellCreateComponent', () => {
  let component: SellCreateComponent;
  let fixture: ComponentFixture<SellCreateComponent>;
  let el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        BrowserAnimationsModule,
      ],
      declarations: [SellCreateComponent],
      providers: [
        { provide: MarketService },
        {
          provide: ActivatedRoute, useValue: {
            paramMap: of(convertToParamMap({ brd_path: 'replica' }))
          }
        },
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(SellCreateComponent);
    component = fixture.componentInstance;
    el = fixture.debugElement.nativeElement;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get the route parameter', fakeAsync(() => {
      component.ngOnInit();

      expect(component.brd_path).toBe('replica');
      expect(component.isNew).toBe(true);
    }));
  });

});
</code>```

when i run the test. i got the error.

SellCreateComponent > ngOnInit > should get the route parameter
TypeError: Cannot read properties of undefined (reading 'pipe')

Thank you!

答:
I think you're mocking ActivatedRoute incorrectly.

You're supplying paramMap but you're looking for queryParams.

Try this:

```<code>provide: ActivatedRoute, useValue: {
            queryParams: of(convertToParamMap({ brd_path: 'replica' }))
          }
</code>```

That should hopefully get rid of that error.

Body:
I have a components gets a value from the params of ActivatedRoute.

the components looks like

constructor(
  private route: ActivatedRoute,
  private router: Router,
  private marketService: MarketService,
) { }

ngOnInit() {
  // New Post
  this.route.queryParams.pipe(
    filter(params => params.type))
    .subscribe(
      params => {
        this.isNew = true;
        this.brd_path = params.type;
        this.category_path = this.route.snapshot.params['category_path'];
      },
      () => { },
      () => { }
    );

  // Edit Post
  this.route.queryParams.pipe(
    filter(params => params.no))
    .subscribe(
      params => {
        if (!this.marketService.getCurrentMarket()) {
          this.router.navigateByUrl('');
          return;
        }
        this.isNew = false;
        this.market_no = +params.no;
      }
    );
}

I want to test depend params
isNew, brd_path, category_path, market_no

TEST code

describe('SellCreateComponent', () => {
  let component: SellCreateComponent;
  let fixture: ComponentFixture<SellCreateComponent>;
  let el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        BrowserAnimationsModule,
      ],
      declarations: [SellCreateComponent],
      providers: [
        { provide: MarketService },
        {
          provide: ActivatedRoute, useValue: {
            paramMap: of(convertToParamMap({ brd_path: 'replica' }))
          }
        },
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(SellCreateComponent);
    component = fixture.componentInstance;
    el = fixture.debugElement.nativeElement;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get the route parameter', fakeAsync(() => {
      component.ngOnInit();

      expect(component.brd_path).toBe('replica');
      expect(component.isNew).toBe(true);
    }));
  });

});

when i run the test. i got the error.

SellCreateComponent > ngOnInit > should get the route parameter
TypeError: Cannot read properties of undefined (reading 'pipe')

Thank you!

Body:
I think you're mocking ActivatedRoute incorrectly.

You're supplying paramMap but you're looking for queryParams.

Try this:

provide: ActivatedRoute, useValue: {
            queryParams: of(convertToParamMap({ brd_path: 'replica' }))
          }

That should hopefully get rid of that error.


问:
How to replace values in one DataFrames in Python with values from another DataFrames where the dates (in datetime format) matches?
Given I have two DataFrames:

```<code>import pandas as pd

df1 = pd.DataFrame([['2017', '1'],
                    ['2018', '2'],
                    ['2019', '3'],
                    ['2020', '4'],
                    ['2021', '5'],
                    ['2022', '6'],
                    ], columns=['datetime', 'values'])

df2 = pd.DataFrame([['2018', '0'],
                    ['2019', '0'],
                    ['2020', '0'],
                    ], columns=['datetime', 'values'])
print(df1)
print(df2)
</code>```

(Assume the values in the column 'datetime' has datetime format and is not string)
How can I replace the values in df1 to the values of df2 where the datetime exists in both without using loops?

答:
You can use combine_first after temporarily setting the index to whatever you want to use as matching columns:

```<code>(df2.set_index('datetime')
    .combine_first(df1.set_index('datetime'))
    .reset_index()
)
</code>```

output:

```<code>  datetime values
0     2017      1
1     2018      0
2     2019      0
3     2020      0
4     2021      5
5     2022      6
</code>```

Body:
Given I have two DataFrames:

import pandas as pd

df1 = pd.DataFrame([['2017', '1'],
                    ['2018', '2'],
                    ['2019', '3'],
                    ['2020', '4'],
                    ['2021', '5'],
                    ['2022', '6'],
                    ], columns=['datetime', 'values'])

df2 = pd.DataFrame([['2018', '0'],
                    ['2019', '0'],
                    ['2020', '0'],
                    ], columns=['datetime', 'values'])
print(df1)
print(df2)

(Assume the values in the column 'datetime' has datetime format and is not string)
How can I replace the values in df1 to the values of df2 where the datetime exists in both without using loops?

Body:
You can use combine_first after temporarily setting the index to whatever you want to use as matching columns:

(df2.set_index('datetime')
    .combine_first(df1.set_index('datetime'))
    .reset_index()
)

output:

  datetime values
0     2017      1
1     2018      0
2     2019      0
3     2020      0
4     2021      5
5     2022      6


问:
Adding textbox on button click with javascript
I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.

I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.

Here is the code I have so far:

```<code>    <html>
    <head>
     <title>Project 4</title>
    </head>

    <body>
            <form name="myForm" onsubmit="return validateForm()">
            Pets: <input type="text" id="pets">
            <input type="button" id="addPet" value="Add Pet">
            <br>
            </form>
        <script type="text/javascript">
            function makeCopy() {
                var copy = <input type="text">;
                return copy;
            }
        </script>
    </body>
</html>
</code>```

There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.

Any suggestions are greatly appreciated.

Update:
I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/

答:
function add(type) {

    //Create an input type dynamically.
    var element = document.createElement("input");
    var text = document.getElementById("textId");

    //Append the element in page (in span).
    text.appendChild(element);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code> h1 {
            color: #0000ff;
        }</code>```

KIAAT

    Adding textbox on button click with javascript

<form>
    <input placeholder="text" name="element" hidden> </input>
    <input type="button" value="Click Me" onclick="add(document.forms[0].element.value)"/>

</form>```

Body:
I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.

I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.

Here is the code I have so far:

     <title>Project 4</title>

            <form name="myForm" onsubmit="return validateForm()">
            Pets: <input type="text" id="pets">
            <input type="button" id="addPet" value="Add Pet">

            </form>

There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.

Any suggestions are greatly appreciated.

Update:
I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/

Body:
function add(type) {

    //Create an input type dynamically.
    var element = document.createElement("input");
    var text = document.getElementById("textId");

    //Append the element in page (in span).
    text.appendChild(element);

}

 h1 {
            color: #0000ff;
        }

<h1>KIAAT</h1>
    <b>Adding textbox on button click with javascript</b>
    <br><br>
<form>
    <input placeholder="text" name="element" hidden> </input>
    <input type="button" value="Click Me" onclick="add(document.forms[0].element.value)"/>
    <span id="textId">&nbsp;</span>
</form>


问:
Update Database leads to "Invalid account ID or license key" message
I'm running the geoipupdate tool (https://github.com/maxmind/geoipupdate) to update the database.
If I run it locally, it works well.
When I use it on my prod server, I get the "Invalid account ID or license key" message.
My account ID and licence key are correct, as it is working on my computer.
Do you have any idea why it bugs?
Thanks a lot!

Matthieu

答: In the end, it was the download that was blocked from the server. So when I had authorization to perform downloads from the server, everything worked fine.</p>