问:
gcloud function php post size issue
I have a gcloud function in PHP that receives a json object.
Inside my function, I read the json object like this: file_get_contents('php://input').

This works for me when the json object that I receive in the function is less than 16KB, but when the json object is greater than 16KB it returns empty.

答:
There is no code, neither client- nor server-side ...

You might be sending as enctype="multipart/form-data"
? https://php.net/manual/en/wrappers.php.php#wrappers.php.input

While file_get_contents('php://input') is questionable by itself.

Instead use the default method signature, which provides ServerRequestInterface $request:

```<code>use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
...

public static function on_https( ServerRequestInterface $request ): ResponseInterface {

    $params = $request->getQueryParams();
    $body = $request->getBody();

    $body->rewind(); // or $body->seek(0);
    $bodyText = $body->getContents();
    $data = json_decode($bodyText);

    return (new Response())
        ->withHeader('Content-Type', 'application/json; charset=utf-8')
        ->withBody(Utils::streamFor(json_encode($data)))
        ->withStatus(200);
}
</code>```

Just recently pushed a template composer project to GitHub, based on the documentation. Not exactly certain about $body->rewind(), that's only required for streams (it may return string already). This requires "guzzlehttp/psr7": "^2.1.0". Also see: What is PSR-7 and how to use it?

Title: gcloud function php post size issue

Body:
There is no code, neither client- nor server-side ...

You might be sending as enctype="multipart/form-data"
? https://php.net/manual/en/wrappers.php.php#wrappers.php.input

While file_get_contents('php://input') is questionable by itself.

Instead use the default method signature, which provides ServerRequestInterface $request:

use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
...

public static function on_https( ServerRequestInterface $request ): ResponseInterface {

    $params = $request->getQueryParams();
    $body = $request->getBody();

    $body->rewind(); // or $body->seek(0);
    $bodyText = $body->getContents();
    $data = json_decode($bodyText);

    return (new Response())
        ->withHeader('Content-Type', 'application/json; charset=utf-8')
        ->withBody(Utils::streamFor(json_encode($data)))
        ->withStatus(200);
}

Just recently pushed a template composer project to GitHub, based on the documentation. Not exactly certain about $body->rewind(), that's only required for streams (it may return string already). This requires "guzzlehttp/psr7": "^2.1.0". Also see: What is PSR-7 and how to use it?


来源: stackexchange

问:
ADF not honoring sink block size in MB (100) for copy activity with ADX as source
I am using ADF copy activity with source as ADX dataset and sink as ADLSGen2. In the settings for the sink I have specified 100 , so that I expect that total data being written is say 1GB , there will be ~ 100 blobs produced.

When I ran the pipeline , there was a single blob of size 1.GGB despite having specified 100 as block size. I experimented with this value multiple times but I observed that it has no impact on number of blobs that get produced in the sink. It's as if it's entirely being ignored. Or it's just that this setting doesn't work when ADX is the source ?

答: strange that Block Size(MB) is not working at my side as well, i've tried the other option Max rows per file, this looks promising, it's creating multiple files with 200000 max rows on each file.

ContentLicense: CC BY-SA 4.0


问:
How to extract all 'href' tags from a div class?
I am working in Python web scrapping using beautiful soup. I couldn't extract 'href' tags and save them to a list.

```<code>[<div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/391/40439">React.js Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40438">Node JS Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40437">React Native Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/391/40436">Python Full Stack Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40435">SEO SPECIALIST</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40434">VR Designer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40433">Automation Tester</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/403/40432">Junior Frontend Developer (ReactJS)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40431">Software Test Engineer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40430">Senior UI Developer (React )</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40429">UI/UX Senior architect</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40428">Front End Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40427">Senior ADF & Power BI Expert</a></div>, <div
class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40426">Software Engineer/ Senior Software Engineer - Odoo</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40425">Team Lead - Php</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40424">Lead - Automation Testing</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40423">Software Engineer/ Senior Software Engineer - PHP</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40422">Software Engineer/Senior Software Engineer - Moodle</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40421">Senior Software Engineer - React Native</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40420">Team Lead-React</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40419">iOS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40418">Flutter Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40417">React Native Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40416">Full Stack Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40415">Angular Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40414">React JS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40413">Node JS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40412">Junior Business Development Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40411">Team Lead - Node</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40410">Team Lead- Ruby on Rails</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/304/40409">Facility in Charge</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40408">Software Engineer/ Senior Software Engineer - Vue</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40407">Lead- UI/UX Designer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40406">Software Engineer/ Senior Software Engineer - React
Js</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40405">Software Engineer/ Senior Software Engineer - Node </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40404">Team Lead - GoLang</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40403">Associate - Business Development.</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40402">Team Lead - React Native</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40401">Lead - Business Analyst</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40400">Software Engineer/Sr.Software Engineer- IOS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40399">Assistant Manager – Business Development </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40398">Marketing Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40397">Associate Software Engineer-Freshers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40396">Software Engineer/Senior Software Engineer-Ruby on Rails</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40395">Senior Software Engineer/ Team Lead - Magento</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40394">Software Engineer/Senior Software Engineer - Java</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/290/40393">SENIOR FULL STACK ENIGNEER - NODEJS/REACTJS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/290/40392">Front End Developer – ReactJS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40391">Software Engineer/Senior Software Engineer - .Net</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/262/40390">Administration Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40389">HR Manager</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40388">MAGENTO DEVELOPER</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40387">PHP DEVELOPER(1-3 YEAR EXP)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40386">SERVER ADMINISTRATOR (1- 4 YEAR ) WITH LINUX EXPERIENCE</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40385">Server Admin- Fresher</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40384">TESTING ENGINEER - TEAM LEAD (4+ Years)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40383">TESTING ENGINEER (2
- 5 YEARS EXP)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40382">PHP DEVELOPER (3+ YEAR)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40381">LARAVEL DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40380">REACT JS DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40379">UI DEVELOPER (0-2 YEAR)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40378">UI Developer(Minimum 1 year)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40377">UI DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40376">UI/UX DESIGNER</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/334/40375">Full Stack Developer-Java, Angular, Spring boot, Microservices</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40374">GRAPHIC DESIGNER - TEAM LEAD</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40373">Digital Marketing - Head</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40372">Social Media Marketing Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40371">Content Writer (Urgent requirement)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40370">Senior React.Js Developer </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40369">Content Writer - Team Lead (Urgent requirement)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40368">PERFORMANCE MARKETING (DIGITAL MARKETING)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40367">Social Media Executive (1 - 3+ Years</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40366">SEO ANALYST (0-1 Year)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40365">SEO ANALYST</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40364">REACT NATIVE DEVELOPER(URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40363">Magento Developers(Min 2 year exp)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40362">ANDROID DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40361">Talent Acquisition Specialist</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40360">Cloud Specialist</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40359">Software Engineer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/com
</code>```

I tried the below code but It didn't work.

```<code>res = requests.get(website_url, verify=False)
soup = BeautifulSoup(res.text, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
url = [tag.get('href') for tag in Links]
</code>```

答:
you can simply use BeutigulSoup and look for a and href:

```<code>from bs4 import BeautifulSoup
import requests
res = requests.get(website_url)
soup = BeautifulSoup(response.content, features="lxml")
urls = []
for a in soup.find_all('a', href=True):
    urls.append(a['href'])
</code>```

Body:
I am working in Python web scrapping using beautiful soup. I couldn't extract 'href' tags and save them to a list.

[
React JS Developer
,
React.js Developers
,
Node JS Developer
,
React Native Developer
,
Python Full Stack Developers
,
SEO SPECIALIST
,
VR Designer
,
Automation Tester
,
Junior Frontend Developer (ReactJS)
,
Software Test Engineer
,
Senior UI Developer (React )
,
UI/UX Senior architect
,
Front End Developer
,
Senior ADF & Power BI Expert
,
Software Engineer/ Senior Software Engineer - Odoo
,
Team Lead - Php
,
Lead - Automation Testing
,
Software Engineer/ Senior Software Engineer - PHP
,
Software Engineer/Senior Software Engineer - Moodle
,
Senior Software Engineer - React Native
,
Team Lead-React
,
iOS Developers
,
Flutter Developers
,
React Native Developers
,
Full Stack Developers
,
Angular Developers
,
React JS Developers
,
Node JS Developers
,
Junior Business Development Executive
,
Team Lead - Node
,
Team Lead- Ruby on Rails
,
Facility in Charge
,
Software Engineer/ Senior Software Engineer - Vue
,
Lead- UI/UX Designer
,
Software Engineer/ Senior Software Engineer - React
Js
,
Software Engineer/ Senior Software Engineer - Node
,
Team Lead - GoLang
,
Associate - Business Development.
,
Team Lead - React Native
,
Lead - Business Analyst
,
Software Engineer/Sr.Software Engineer- IOS
,
Assistant Manager – Business Development
,
Marketing Executive
,
Associate Software Engineer-Freshers
,
Software Engineer/Senior Software Engineer-Ruby on Rails
,
Senior Software Engineer/ Team Lead - Magento
,
Software Engineer/Senior Software Engineer - Java
,
SENIOR FULL STACK ENIGNEER - NODEJS/REACTJS
,
Front End Developer – ReactJS
,
Software Engineer/Senior Software Engineer - .Net
,
Administration Executive
,
HR Manager
,
MAGENTO DEVELOPER
,
PHP DEVELOPER(1-3 YEAR EXP)
,
SERVER ADMINISTRATOR (1- 4 YEAR ) WITH LINUX EXPERIENCE
,
Server Admin- Fresher
,
TESTING ENGINEER - TEAM LEAD (4+ Years)
,
TESTING ENGINEER (2
- 5 YEARS EXP)
,
PHP DEVELOPER (3+ YEAR)
,
LARAVEL DEVELOPER (URGENT REQUIREMENT)
,
REACT JS DEVELOPER (URGENT REQUIREMENT)
,
UI DEVELOPER (0-2 YEAR)
,
UI Developer(Minimum 1 year)
,
UI DEVELOPER (URGENT REQUIREMENT)
,
UI/UX DESIGNER
,
Full Stack Developer-Java, Angular, Spring boot, Microservices
,
GRAPHIC DESIGNER - TEAM LEAD
,
Digital Marketing - Head
,
Social Media Marketing Executive
,
Content Writer (Urgent requirement)
,
Senior React.Js Developer
,
Content Writer - Team Lead (Urgent requirement)
,
PERFORMANCE MARKETING (DIGITAL MARKETING)
,
Social Media Executive (1 - 3+ Years
,
SEO ANALYST (0-1 Year)
,
SEO ANALYST
,
REACT NATIVE DEVELOPER(URGENT REQUIREMENT)
,
Magento Developers(Min 2 year exp)
,
ANDROID DEVELOPER (URGENT REQUIREMENT)
,
Talent Acquisition Specialist
,
Cloud Specialist
,
Software Engineer
,
<a href="https://example.com/companies/company/com

I tried the below code but It didn't work.

res = requests.get(website_url, verify=False)
soup = BeautifulSoup(res.text, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
url = [tag.get('href') for tag in Links]

Body:
you can simply use BeutigulSoup and look for a and href:

from bs4 import BeautifulSoup
import requests
res = requests.get(website_url)
soup = BeautifulSoup(response.content, features="lxml")
urls = []
for a in soup.find_all('a', href=True):
    urls.append(a['href'])


问:
Method that scans array for most common word length, but sends error message if two different elements have the same length
I have a method that takes in an array (created by Scanner input in main) and sorts the array to find the most common words before printing the length of those words. However, I'm also trying to have an error message pop up if two different elements have the same length; this is where I'm having trouble getting started.

Method:

```<code>//Return the length of the most common words
public static int lengthOfWord(String[] arr){

  int arrLength = arr.length;
  int count = 1;
  int maxCount = 1;
  String temp = arr[0];

  //Sort through array
  for (int i = 1; i < arr.length; i++)  {
     if (arr[i] == arr[i - 1]) {
        count++;
     } else {
     if (count > maxCount) {
        maxCount = count;
        temp = arr[i - 1];
     }//End of conditional
     count = 1;
     }//End of conditional
  }// End of for loop

  //Declare most frequent length
  if (count > maxCount) {
     maxCount = count;
     temp = arr[arrLength - 1];
  }//End of conditional

  return temp.length();

}//End of lengthOfWord
</code>```

Any suggestions?

答:
String comparison - arr[i] == arr[i-1] does not work. Each string object is different for Java. Use arr[i].equals(arr[i-1]).

When you check count > maxCount, it means there is definitely a string more frequent than the previous one. However, what if count == maxCount? - It would mean you have found two strings with equal frequency.

Use a flag that tells you if there are multiple max frequency strings or not. So now we are going to check both for greater and equal conditions and based on what is true, we are going to set a flag unique.

//Return the length of the most common words
public static int lengthOfWord(String[] arr){

  int arrLength = arr.length;
  int count = 1;
  int maxCount = 1;
  boolean unique = true;
  String temp = arr[0];

  //Sort through array
  for (int i = 1; i < arr.length; i++)  {
     if (arr[i] == arr[i - 1]) {
        count++;
     } else {
     if (count > maxCount) {
        unique = true;
        maxCount = count;
        temp = arr[i - 1];
     } else if(count == maxCount) {
        unique = false;
     }
     //End of conditional
     count = 1;
     }//End of conditional
  }// End of for loop

  //Declare most frequent length
  if (count > maxCount) {
      unique = true;
      maxCount = count;
      temp = arr[i - 1];
  } else if(count == maxCount) {
      unique = false;
  }//End of conditional

  if(!unique) {
    System.out.println("ERROR"); // or whatever you want to do in this condition
  }

  return temp.length(): ;

}//End
```

Body:
I have a method that takes in an array (created by Scanner input in main) and sorts the array to find the most common words before printing the length of those words. However, I'm also trying to have an error message pop up if two different elements have the same length; this is where I'm having trouble getting started.

Method:

//Return the length of the most common words
public static int lengthOfWord(String[] arr){

  int arrLength = arr.length;
  int count = 1;
  int maxCount = 1;
  String temp = arr[0];

  //Sort through array
  for (int i = 1; i < arr.length; i++)  {
     if (arr[i] == arr[i - 1]) {
        count++;
     } else {
     if (count > maxCount) {
        maxCount = count;
        temp = arr[i - 1];
     }//End of conditional
     count = 1;
     }//End of conditional
  }// End of for loop

  //Declare most frequent length
  if (count > maxCount) {
     maxCount = count;
     temp = arr[arrLength - 1];
  }//End of conditional

  return temp.length();

}//End of lengthOfWord

Any suggestions?


问:
Batch RPG Game with Login Function
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

```<code>title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit
</code>```

I expect it to create the batch file after creating an account so that you can log in later.

答:
I'm using the same thing in my game. You need 2 functions, 1 to load and 1 to save. The save function should look something like this:

```<code>:: My save thing
:save
(
echo %var1%
echo %var2%
) > save.sav
</code>```

and the loading portion should look something like this:

```<code>< save.sav (
set /p var1=
set /p var2=
)
</code>```

also, one major recommendation, put all your scripts into separate files and folders. Like a normal game, example:

```<code>- MainGame
  - Launcher.bat
  - Resources
    - Scripts
      - Save.bat
      - Load.bat
      - Fight.bat
    - Assets
      - Title.txt
</code>```

this is a similar structure to what I used in my game.

Title: Batch RPG Game with Login Function

Body:
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit

I expect it to create the batch file after creating an account so that you can log in later.

Body:
I'm using the same thing in my game. You need 2 functions, 1 to load and 1 to save. The save function should look something like this:

:: My save thing
:save
(
echo %var1%
echo %var2%
) > save.sav

and the loading portion should look something like this:

< save.sav (
set /p var1=
set /p var2=
)

also, one major recommendation, put all your scripts into separate files and folders. Like a normal game, example:

- MainGame
  - Launcher.bat
  - Resources
    - Scripts
      - Save.bat
      - Load.bat
      - Fight.bat
    - Assets
      - Title.txt

this is a similar structure to what I used in my game.


问:
How can I `Enable All Tasks History` in PowerShell?
In the task scheduler GUI it is easy to Enable All Tasks History

See also https://stackoverflow.com/questions/11013132/how-can-i-enable-the-windows-server-task-scheduler-history-recording

How can I Enable All Tasks History through PowerShell?

I have looked at Set-ScheduledTask and New-ScheduledTask, but nothing useful there (as far as I can see).

答:
From an elevated command prompt or PowerShell

wevtutil set-log Microsoft-Windows-TaskScheduler/Operational /enabled:true

ContentLicense: CC BY-SA 3.0


问:
Why I am getting a blank page?
I started following a tutorial today and I dont know why my script is not working?

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(Images/banner.png);
    background-position: center;
    background-size: cover;
    position: relative;

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">
 </head>
<body>
    <section class="header">

    </section>

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

It is supposed to show a background but my website is blank.

I was following this  tutorial at 8:00 - 8:20. He is using brackets.io while I am using VSC. what am I doing wrong?

答:
If you look into your css background-image property then there's an image url which needs to be find the right directory. other than your code doesn't have any content. So it's not showing anything in the display. Otherwise you code is working file. see here, i just changed that image url .

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(https://dummyimage.com/640x360/fff/aaa);
    background-position: center;
    background-size: cover;
    position: relative;

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">
 </head>
<body>
    <section class="header">

    </section>

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

Title: Why I am getting a blank page?

Body:
I started following a tutorial today and I dont know why my script is not working?

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(Images/banner.png);
    background-position: center;
    background-size: cover;
    position: relative;

}

<!DOCTYPE html>

    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">

It is supposed to show a background but my website is blank.

I was following this  tutorial at 8:00 - 8:20. He is using brackets.io while I am using VSC. what am I doing wrong?

Body:
If you look into your css background-image property then there's an image url which needs to be find the right directory. other than your code doesn't have any content. So it's not showing anything in the display. Otherwise you code is working file. see here, i just changed that image url .

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(https://dummyimage.com/640x360/fff/aaa);
    background-position: center;
    background-size: cover;
    position: relative;

}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">
 </head>
<body>
    <section class="header">

    </section>

</body>
</html>


问:
getStateForAction is undefined for react-navigation v6
Currently I am upgrading my react-navigation from v4 to v6. But I am facing problem while getting initial state for my App.

```<code>// AppNavigation.js
// All the screens and packages are imported
function switchNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="loginFlow">
        <Stack.Screen name="loginFlow" component={loginFlow} />
        <Stack.Screen name="mainFlow" component={mainFlow} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
export default switchNavigator;
</code>```

Now I am using the below code to get the initial state and set it if it's undefined in my redux navigation.

```<code>import AppNavigation from '../Navigation/AppNavigation';

export const reducer = (state, action) => {
  const newState = AppNavigation.router.getStateForAction(action, state);
  return newState || state;
};
</code>```

But I am getting this error

```<code>TypeError: undefined is not an object (evaluating '_AppNavigation.default.router.getStateForAction')
</code>```

答:
Here is the Awesome feature that comes from the React Navigation Library With Which We are able to use the navigation options without accessing the Props as the components do.

Please refer to the Below Documentation page from the React Navigation,
I hope it might help you in your achieving.

React Navigation Accessing Navigation Without Props

Body:
Currently I am upgrading my react-navigation from v4 to v6. But I am facing problem while getting initial state for my App.

// AppNavigation.js
// All the screens and packages are imported
function switchNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="loginFlow">
        <Stack.Screen name="loginFlow" component={loginFlow} />
        <Stack.Screen name="mainFlow" component={mainFlow} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
export default switchNavigator;

Now I am using the below code to get the initial state and set it if it's undefined in my redux navigation.

import AppNavigation from '../Navigation/AppNavigation';

export const reducer = (state, action) => {
  const newState = AppNavigation.router.getStateForAction(action, state);
  return newState || state;
};

But I am getting this error

TypeError: undefined is not an object (evaluating '_AppNavigation.default.router.getStateForAction')


问:
Rails 3: Drop a table using migration
I have a table that I created using the migrations, now I want to get rid of this table.  I'm pretty sure I can just back out that migration, but I can't find the syntax to do that.  I found this question from searching Rails DB Migration - How To Drop a Table?

but he basically says you can find what you need and provides a link.  I read that link and I didn't see anything that says how to do it.  I saw pieces of it, but I don't know how to put them together.

I see in the migration it has a self.down method, I really just need to know how to call that.

答:
```<code>rake db:rollback STEP=n
</code>```

where n is the number of steps you need to roll back.  If you leave the STEP off it just rolls back 1.

To migrate to a particular version, use:

```<code>rake db:migrate:down VERSION=20080906120000
</code>```

If you want to quickly apply a table drop, you could create a new migration, run it, then delete it along with the original migration you no longer want.  The syntax for dropping a table is:

```<code>drop_table :table_name
</code>```

Title: Rails 3: Drop a table using migration

Body:
rake db:rollback STEP=n

where n is the number of steps you need to roll back.  If you leave the STEP off it just rolls back 1.

To migrate to a particular version, use:

rake db:migrate:down VERSION=20080906120000

If you want to quickly apply a table drop, you could create a new migration, run it, then delete it along with the original migration you no longer want.  The syntax for dropping a table is:

drop_table :table_name


问:
onEdit Event object access to previous value of a cell that has been modified?
I cannot find any detailled documentation on the event.source object so I would like to know if it's possible to access the previous value of the modified range so I can compare the new values of the range with the old values of the range for validation.

Thanks for your help.

OnEdit(event)

```<code>function onEdit(event)
/* Default onEdit Event function */
{
  var ssa = SpreadsheetApp.getActiveSpreadsheet();
  var ss = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
...
</code>```

答:
This is an old post but it's the first that came up when I was searching and this has since been implemented. You can find the details in the documentation https://developers.google.com/apps-script/guides/triggers/events#edit

[From Docs] It can be accessed with oldValue: Cell value prior to the edit, if any. Only available if the edited range is a single cell. Will be undefined if the cell had no previous content.

So for example you could log the value with the following script:

```<code>function onEdit(e){
  Logger.log(e.oldValue);
}
</code>```

PS: You can see the logs by going to Executions from the left menu (see image below)

Body:
I cannot find any detailled documentation on the event.source object so I would like to know if it's possible to access the previous value of the modified range so I can compare the new values of the range with the old values of the range for validation.

Thanks for your help.

OnEdit(event)

function onEdit(event)
/* Default onEdit Event function */
{
  var ssa = SpreadsheetApp.getActiveSpreadsheet();
  var ss = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
...

Body:
This is an old post but it's the first that came up when I was searching and this has since been implemented. You can find the details in the documentation https://developers.google.com/apps-script/guides/triggers/events#edit

[From Docs] It can be accessed with oldValue: Cell value prior to the edit, if any. Only available if the edited range is a single cell. Will be undefined if the cell had no previous content.

So for example you could log the value with the following script:

function onEdit(e){
  Logger.log(e.oldValue);
}

PS: You can see the logs by going to Executions from the left menu (see image below)


问:
Flatlist is very slow in using big data in react native
i have a big data list of products thats paginate, in every page it load 10 item, but when i add new items to itemlist,flatlist gets very slow,As the number of pages increases, so does the loading time of new products,The function of the choose button is also slowed down.
How to speed up loading I tried all the best methods but it still did not work. Did not React Native really solve this problem?</p>
```<code> export default function Products(props) {
 const toast = useToast();
 const [isLoading, setSetIsLoading] = useState(true);
 const [items, setItems] = useState([]);
  const [fetchStatus, setFetchStatus] = useState(false);
  const [page, setPage] = useState(1);
  const [sending, setSending] = useState(false);

  async function getProducts() {
  let token = await AsyncStorage.getItem('@token');
  let data = {
  token: token,
  page: page,
  };
  await get_products(data)
  .then(res => {
    setItems([...items, ...res.data.data.docs]);
    setPage(res.data.data.nextPage);
  })
  .catch(err => {
    console.log(err);
  });
 }

 async function getNextPage() {
let token = await AsyncStorage.getItem('@token');
let data = {
  token: token,
  page: page,
};
await get_products(data)
  .then(res => {
    setItems([...items, ...res.data.data.docs]);
    setPage(res.data.data.nextPage);
  })
  .catch(err => {
    console.log(err);
  });
 }

 async function selectProduct(id) {
 setSending(true);
 console.log({id});
 let token = await AsyncStorage.getItem('@token');
 let data = {
  product_id: id
 };
 await select_products(data,token).then(res => {
 toast.show({
   description:res.data.message
 })
 setSending(false);
}).catch(rej => {
  console.log({rej})
  toast.show({
    description:rej?.response?.data.message,
  })
  setSending(false);
  })
  }
  useFocusEffect(
  React.useCallback(() => {
  getProducts();
  return () => {
    setItems([]);
    setPage();
    };
   }, []),
 );
 renderItem =({item}) => (
 <Card
  selectProduct={id => selectProduct(id)}
  sending={sending}
  obj={item}
  />
  )
  return (
    <View mb={20}>
    <FlatList
    data={items}
    extraData={items}
    removeClippedSubviews={true}
    renderItem={renderItem}
    keyExtractor={(item) => `${item._id}-item`}
    onEndReached={getNextPage}
    maxToRenderPerBatch="13"
    ListFooterComponent={() => {
      return <ActivityIndicator color="orange" size="large" />;
    }}></FlatList>
    </View>
    );
    }
</code>```

答:
Did you use **map method **?
It can help you for more easily loading data</p>

Body:
i have a big data list of products thats paginate, in every page it load 10 item, but when i add new items to itemlist,flatlist gets very slow,As the number of pages increases, so does the loading time of new products,The function of the choose button is also slowed down.
How to speed up loading I tried all the best methods but it still did not work. Did not React Native really solve this problem?

 export default function Products(props) {
 const toast = useToast();
 const [isLoading, setSetIsLoading] = useState(true);
 const [items, setItems] = useState([]);
  const [fetchStatus, setFetchStatus] = useState(false);
  const [page, setPage] = useState(1);
  const [sending, setSending] = useState(false);

  async function getProducts() {
  let token = await AsyncStorage.getItem('@token');
  let data = {
  token: token,
  page: page,
  };
  await get_products(data)
  .then(res => {
    setItems([...items, ...res.data.data.docs]);
    setPage(res.data.data.nextPage);
  })
  .catch(err => {
    console.log(err);
  });
 }

 async function getNextPage() {
let token = await AsyncStorage.getItem('@token');
let data = {
  token: token,
  page: page,
};
await get_products(data)
  .then(res => {
    setItems([...items, ...res.data.data.docs]);
    setPage(res.data.data.nextPage);
  })
  .catch(err => {
    console.log(err);
  });
 }

 async function selectProduct(id) {
 setSending(true);
 console.log({id});
 let token = await AsyncStorage.getItem('@token');
 let data = {
  product_id: id
 };
 await select_products(data,token).then(res => {
 toast.show({
   description:res.data.message
 })
 setSending(false);
}).catch(rej => {
  console.log({rej})
  toast.show({
    description:rej?.response?.data.message,
  })
  setSending(false);
  })
  }
  useFocusEffect(
  React.useCallback(() => {
  getProducts();
  return () => {
    setItems([]);
    setPage();
    };
   }, []),
 );
 renderItem =({item}) => (
 <Card
  selectProduct={id => selectProduct(id)}
  sending={sending}
  obj={item}
  />
  )
  return (
    <View mb={20}>
    <FlatList
    data={items}
    extraData={items}
    removeClippedSubviews={true}
    renderItem={renderItem}
    keyExtractor={(item) => `${item._id}-item`}
    onEndReached={getNextPage}
    maxToRenderPerBatch="13"
    ListFooterComponent={() => {
      return <ActivityIndicator color="orange" size="large" />;
    }}></FlatList>
    </View>
    );
    }


问:
How can I get DeviceInformation from GattCharacteristic on ValueChanged
I am writing a UWP app that connects to BLE devices. I have it connecting and subscribing to a characteristic. When I get the ValueChanged callback it works great, but I need to get the device ID.

I need this because my app might connect to more than one of the same type of device and want to subscribe to the same characteristic.

Since the code to get the ValueChanged notification is the same for all devices, I need a way to differentiate which device sent the ValueChanged.

答:
Like @Mike Petrichenko's comment, you could get the device ID value like this:</p>
```<code> private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        GattDeviceService service = sender.Service;
        String deviceID = service.DeviceId;
    }
</code>```

Body:
Like @Mike Petrichenko's comment, you could get the device ID value like this:

 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        GattDeviceService service = sender.Service;
        String deviceID = service.DeviceId;
    }


问:
What are the different ways to convert a generator expression to a list?
```<code>mylist = [1, 2, 3, 4, 5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)
</code>```

passing the generator expression to the list function is one way I learned to convert the generator expression into a list. Just curious to know if this can be in  any other different way?

答:
You can unpack the generator:</p>
```<code>[*my_gen]
>>[4,5]
</code>```

Body:
mylist = [1, 2, 3, 4, 5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)

passing the generator expression to the list function is one way I learned to convert the generator expression into a list. Just curious to know if this can be in  any other different way?

Body:
You can unpack the generator:

[*my_gen]
>>[4,5]


问:
Do not show duplicate rows
I am trying to query a MySQL database so I can build a select box. But there are duplicate values being returned. Is there anyway to only show one of each value. Below is my query but when I echo the results it show every row. I need only to show one of each value.

```<code>$query = "SELECT name FROM ImageInfo";

$db = new connection();

$result = $db->query($query);

while($info = mysql_fetch_array($result)){
    $content[] = $info;
    }

    $result=array();
    $count = count($content);

 for ($x=0;$x<$count;++$x)
 {
    $result[$x][] = $content[$x]['name'];
 }

echo json_encode($result);
</code>```

and if names row was as follows"

```<code>name
Mike
Julia
Julia
Julia
Mike
Ben
Tom
Ben
</code>```

when the data echos I am trying to only show

```<code>Mike
Julia
Ben
Tom
</code>```

答:
```<code>$query = "SELECT DISTINCT name FROM ImageInfo";
</code>```

That should do the trick. :)

Title: Do not show duplicate rows

Body:
I am trying to query a MySQL database so I can build a select box. But there are duplicate values being returned. Is there anyway to only show one of each value. Below is my query but when I echo the results it show every row. I need only to show one of each value.

$query = "SELECT name FROM ImageInfo";

$db = new connection();

$result = $db->query($query);

while($info = mysql_fetch_array($result)){
    $content[] = $info;
    }

    $result=array();
    $count = count($content);

 for ($x=0;$x<$count;++$x)
 {
    $result[$x][] = $content[$x]['name'];
 }

echo json_encode($result);

and if names row was as follows"

name
Mike
Julia
Julia
Julia
Mike
Ben
Tom
Ben

when the data echos I am trying to only show

Mike
Julia
Ben
Tom

Body:
$query = "SELECT DISTINCT name FROM ImageInfo";

That should do the trick. :)


问:
OperationalError at /admin/app/question/ no such table: app_question (django)
Im new to this and Im tryna make a q&a type of app, I was just starting then when I went to admin/ to try it out I got

```<code>OperationalError at /admin/app/question/
no such table: app_question

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/app/question/

Django Version: 4.0.1
Python Version: 3.10.1
Installed Applications:
['app',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'crispy_forms',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'users']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
Exception Type: OperationalError at /admin/app/question/
Exception Value: no such table: app_question
</code>```

here is the models.py

```<code>from django.db import models
from django.contrib.auth.backends import ModelBackend
from users.models import CustomUser

# This is the question model
class Question(models.Model):
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    detail = models.TextField()
    add_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

# This is the answer model

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    detail = models.TextField()
    add_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.detail
</code>```

I'd appreciate if its explained in a beginner friendly manner, thank you!

答:
Here is the documentation. You should

run migrate again to create those model tables in your database:

Body:
Im new to this and Im tryna make a q&a type of app, I was just starting then when I went to admin/ to try it out I got

OperationalError at /admin/app/question/
no such table: app_question

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/app/question/

Django Version: 4.0.1
Python Version: 3.10.1
Installed Applications:
['app',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'crispy_forms',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'users']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
Exception Type: OperationalError at /admin/app/question/
Exception Value: no such table: app_question

here is the models.py

from django.db import models
from django.contrib.auth.backends import ModelBackend
from users.models import CustomUser

# This is the question model
class Question(models.Model):
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    detail = models.TextField()
    add_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

# This is the answer model

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    detail = models.TextField()
    add_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.detail

I'd appreciate if its explained in a beginner friendly manner, thank you!


问:
Why is node-sass being built when I upgrade from npm6 to npm7?
My app uses sass, not node-sass. node-sass is nowhere in my package-lock.json.

I'm currently using npm 6 and everything is working fine and has been for years.

When I try to npm install with npm 7, it fails with the below error.

What's going on? Maybe node-sass is a dev dependency of something else and being built?

```<code>npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-sass
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c node scripts/build.js
npm ERR! npm ERR! Building: /opt/local/bin/node /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! npm ERR!   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.3.6"' -I/Users/john/.node-gyp/14.18.3/include/node -I/Users/john/.node-gyp/14.18.3/src -I/Users/john/.node-gyp/14.18.3/deps/uv/include -I/Users/john/.node-gyp/14.18.3/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/eval.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/eval.o ../src/libsass/src/eval.cpp
### above line repeated many times
npm ERR! npm ERR!
</code>```

答:
To see what would happen I tried npm install --package-lock-only, and it succeeded. I could then see the dependency tree. node_modules/sass-loader has node-sass as a peer dependency.

npm7 installs peer dependencies by default and doesn't allow getting into an ambiguous state. (more info: https://stackoverflow.com/a/22004559/168143 )

So, that's why this was happening. I don't know if I wasn't reading the stack trace well enough or if there is some other standard way for me to have figured out what had the dependencies. I'll leave this question without an accepted answer just in case someone has a smarter way to diagnose this sort of thing.

Body:
My app uses sass, not node-sass. node-sass is nowhere in my package-lock.json.

I'm currently using npm 6 and everything is working fine and has been for years.

When I try to npm install with npm 7, it fails with the below error.

What's going on? Maybe node-sass is a dev dependency of something else and being built?

npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-sass
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c node scripts/build.js
npm ERR! npm ERR! Building: /opt/local/bin/node /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! npm ERR!   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.3.6"' -I/Users/john/.node-gyp/14.18.3/include/node -I/Users/john/.node-gyp/14.18.3/src -I/Users/john/.node-gyp/14.18.3/deps/uv/include -I/Users/john/.node-gyp/14.18.3/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/eval.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/eval.o ../src/libsass/src/eval.cpp
### above line repeated many times
npm ERR! npm ERR!


问:
creating a folder inside existing folder in google drive using Javascript
I am creating an application using asp.net mvc and javascript in which I want to create folders inside my existing google drive folder.

below is my code which I got from stackoverflow

```<code>function createFolder() {
    var body = {
        'title': document.getElementById('txtFolderName').value,
        'mimeType': "application/vnd.google-apps.folder"
    };

    var request = gapi.client.drive.files.insert({
        'resource': body
    });

    request.execute(function (resp) {
        console.log('Folder ID: ' + resp.id);
    });
}
</code>```

I am getting the below error

index.html:61 Uncaught TypeError: Cannot read properties of undefined
(reading 'files')

on the following line

var request = gapi.client.drive.files.insert({

here gapi.client.drive is appearing to be undefined

below is my code to authenticate and load google api client

```<code>function authenticate(callback) {
    return gapi.auth2.getAuthInstance()
        .signIn({ scope: "https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file" })
        .then(function () {
            console.log("Sign-in successful");
            callback == undefined ? '' : callback();
        },
            function (err) {
                console.error("Error signing in", err);
            });
}
function loadClient() {
    gapi.client.setApiKey("APIKEY");
    return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")
        .then(function () {
            console.log("GAPI client loaded for API");
        },
            function (err) {
                console.error("Error loading GAPI client for API", err);
            });
}
</code>```

what is the problem here?

and what I need to do if I want to create a folder inside another folder?

thanks in advance

答:
I thought that in your script, https://docs.googleapis.com/$discovery/rest?version=v1 of gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1") is used for Google Docs API v1. I think that the reason for your error message of Uncaught TypeError: Cannot read properties of undefined (reading 'files') is due to this.

In your goal, it seems that you want to create a folder into a specific folder. In this case, please use Drive API. But, when I saw your current script for creating the folder, Drive API v2 is used. So, please modify as follows.

From:

```<code>return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")
</code>```

To:

```<code>return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/drive/v2/rest")
</code>```

By this modification, I thought that your createFolder() works. But in your current createFolder(), the folder is created to the root folder. When you want to create the folder into a specific folder, please modify the request body as follows.

```<code>  var body = {
    'title': document.getElementById('txtFolderName').value,
    'mimeType': "application/vnd.google-apps.folder",
    'parents': [{'id': '###folderId###'}]
  };
</code>```

Note:

As additional information, if you want to use Drive API v3, please modify it as follows.

From

```<code>  return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")
</code>```

To

```<code>  return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/drive/v3/rest")
</code>```

And, please modify createFolder() as follows.

```<code>  var body = {
    'name': document.getElementById('txtFolderName').value,
    'mimeType': "application/vnd.google-apps.folder",
    'parents': ['###folderId###']
  };

  var request = gapi.client.drive.files.create({ 'resource': body });
</code>```

References:

Files: insert of Drive API v2

Files: create of Drive API v3

Body:
I am creating an application using asp.net mvc and javascript in which I want to create folders inside my existing google drive folder.

below is my code which I got from stackoverflow

function createFolder() {
    var body = {
        'title': document.getElementById('txtFolderName').value,
        'mimeType': "application/vnd.google-apps.folder"
    };

    var request = gapi.client.drive.files.insert({
        'resource': body
    });

    request.execute(function (resp) {
        console.log('Folder ID: ' + resp.id);
    });
}

I am getting the below error

index.html:61 Uncaught TypeError: Cannot read properties of undefined
(reading 'files')

on the following line

var request = gapi.client.drive.files.insert({

here gapi.client.drive is appearing to be undefined

below is my code to authenticate and load google api client

function authenticate(callback) {
    return gapi.auth2.getAuthInstance()
        .signIn({ scope: "https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file" })
        .then(function () {
            console.log("Sign-in successful");
            callback == undefined ? '' : callback();
        },
            function (err) {
                console.error("Error signing in", err);
            });
}
function loadClient() {
    gapi.client.setApiKey("APIKEY");
    return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")
        .then(function () {
            console.log("GAPI client loaded for API");
        },
            function (err) {
                console.error("Error loading GAPI client for API", err);
            });
}

what is the problem here?

and what I need to do if I want to create a folder inside another folder?

thanks in advance

Body:
I thought that in your script, https://docs.googleapis.com/$discovery/rest?version=v1 of gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1") is used for Google Docs API v1. I think that the reason for your error message of Uncaught TypeError: Cannot read properties of undefined (reading 'files') is due to this.

In your goal, it seems that you want to create a folder into a specific folder. In this case, please use Drive API. But, when I saw your current script for creating the folder, Drive API v2 is used. So, please modify as follows.

From:

return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")

To:

return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/drive/v2/rest")

By this modification, I thought that your createFolder() works. But in your current createFolder(), the folder is created to the root folder. When you want to create the folder into a specific folder, please modify the request body as follows.

  var body = {
    'title': document.getElementById('txtFolderName').value,
    'mimeType': "application/vnd.google-apps.folder",
    'parents': [{'id': '###folderId###'}]
  };

Note:

As additional information, if you want to use Drive API v3, please modify it as follows.

From

  return gapi.client.load("https://docs.googleapis.com/$discovery/rest?version=v1")

To

  return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/drive/v3/rest")

And, please modify createFolder() as follows.

  var body = {
    'name': document.getElementById('txtFolderName').value,
    'mimeType': "application/vnd.google-apps.folder",
    'parents': ['###folderId###']
  };

  var request = gapi.client.drive.files.create({ 'resource': body });

References:

Files: insert of Drive API v2

Files: create of Drive API v3


答:
url(Images/banner.png);

All code is right .but Check the file where you store the Images .

Title: Why I am getting a blank page?


问:
Microsoft Graph - Message center receive more the 100 object
I'm writing an application integration which message center I need to display all of them but receive only 100.

API endpoint:

```<code>GET https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages
</code>```

Official docs

Is there any option to get all of the messages?

答:
As mentioned in the doc:

The response is paginated and each page contains 100 objects.

Anyway, you can try to use the $top query parameter to specify the page size of the result set.

```<code>GET https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages?$top=1000
</code>```

Resources:

Paging

Body:
I'm writing an application integration which message center I need to display all of them but receive only 100.

API endpoint:

GET https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages

Official docs

Is there any option to get all of the messages?

Body:
As mentioned in the doc:

The response is paginated and each page contains 100 objects.

Anyway, you can try to use the $top query parameter to specify the page size of the result set.

GET https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages?$top=1000

Resources:

Paging


答: You are not including your primary image folder. you just copy this tutorial. So you include your image folder as ../your-folder-name/image-name</p>

Title: Why I am getting a blank page?

Body:
I started following a tutorial today and I dont know why my script is not working?

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(Images/banner.png);
    background-position: center;
    background-size: cover;
    position: relative;

}

<!DOCTYPE html>

    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">

It is supposed to show a background but my website is blank.

I was following this  tutorial at 8:00 - 8:20. He is using brackets.io while I am using VSC. what am I doing wrong?


问:
Dijkstra Algorithm = SSSP

What i have learnt , that dijkstra cannot work with negative edge weights . For that we have to use bellman ford .

Bellman fords works well with negative edge weights and negative cycles , which are not reachable from source otherwise, it will return a msg "Negative cycles exist".

But, this graph shown above works well with dijkstra , even though negative edge weights exist. So, how to know when to use dijkstra with negative edge weights ??

What is think , is that dijkstra can or cannot work with negative weight edges.
If negative cycle exists, then it will not work. But if not exists, it can or cannot work.

Am i right ?? plz guide me for this ??

答:
check the following code

```<code>    import networkx as nx
    g = nx.Graph()
    g.add_edge(1, 2, weigbt=-10)
    g.add_edge(2, 3, weight = -5)
    g.add_edge(1, 3, weight =-6)
    print(nx.single_source_dijkstra(g, 1, 3))
</code>```

it doesn't matter if all of your edges are positive or negative, the Dijkstra SSSP will give you the same answer.
HOWEVER, it doesn't mean that for any graph with negative edge, the Dijkstra shortest path MAY give right answer in case of negative edge but that doesn't mean it WILL give right answer.

Title: Dijkstra Algorithm = SSSP

Body:
check the following code

    import networkx as nx
    g = nx.Graph()
    g.add_edge(1, 2, weigbt=-10)
    g.add_edge(2, 3, weight = -5)
    g.add_edge(1, 3, weight =-6)
    print(nx.single_source_dijkstra(g, 1, 3))

it doesn't matter if all of your edges are positive or negative, the Dijkstra SSSP will give you the same answer.
HOWEVER, it doesn't mean that for any graph with negative edge, the Dijkstra shortest path MAY give right answer in case of negative edge but that doesn't mean it WILL give right answer.


问:
jQuery Animate Question
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

```<code><body>

<script language="javascript" type="text/javascript">
$(function() {
    // when we click on the a-href id 'togglen', we move the overDiv to the left.
$('#togglen').click(function() {
    // simple animation
    $('#overDiv').animate({
      left: parseInt($('#overDiv').css('left'),10) == 0 ? -$('#overDiv').outerWidth() : 0
    });
  }); //
});

</script>
<div><a href="#" id="togglen">+</a></div>
<div style="background-color:#CCC; width:180px;  position:absolute; left:0; overflow:hidden; float:left;" id="overDiv">Lorem ipsum.</div>
</code>```

答:
Set the position of sliding div to relative and float left the div with +. This way there is no hard coding of any values in the div with +

Working demo

Title: jQuery Animate Question

Body:
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

+

Lorem ipsum.


问:
Access the routerlink data
I have a routerlink in an anchor tag, and I want to access the value passed. How can I do it?

As you can see in the above screenshot, "bob" is the data is being passed to the component when this anchor tag is clicked, so how can I access this value in the component when it loads? Please note that it is a child component of another component therefore route is not used.

答:
You can access the data using the Activated Route service of Angular by injecting it into the component you need data in. For example, the anchor is in Component A, and you navigate to Component B where you require the data Bob. You can inject the Acvtivated Route in Component B and get the param using it

   constructor(private activatedRoute: ActivatedRoute){

   ngOnInit(): void {
          // For Params
       this.activatedRoute.params.subscribe((params: Params) => {
            // Should display Bob
            console.log(params);
        });

        this.activatedRoute.queryParams.subscribe((queryParams: Params) => {
            //Should display { debug: true} object
            console.log(queryParams);
        });
    }
}
```

Title: Access the routerlink data


问:
Search for closes index on SQL table
I have a hypothetical SQL table "EVENTS", with two columns, a UUID index column, and a DateTime column,
The table is populated with values ranging from 1900-01-01 to today, it is not ordered, there are numerous dates missing.

The query that I have to run is basically 'retrieve all events that happened at the requested date (start to the end of the day) or the closest previous date'

If I were looking for all events in a day that I know that exists in the database it would be something as simple as:

```<code>SELECT * FROM Events e
WHERE
e.date BETWEEN $START_OF_DAY AND $END_OF_DAY;
</code>```

But if that date doesn't exist I must retrieve the latest date up to the requested date.

答:
Grab current day, but if no records found, will return all records from the nearest previous day with records.
So in my sample data, Jan 2 returns 3 events dated Jan 1

SQL Server Solution

```<code>DECLARE @Input DATE = '2022-01-02' /*Try Jan 1,2,3, or 4*/
DROP TABLE IF EXISTS #Event

CREATE TABLE #Event (ID INT IDENTITY(1,1),EventDateTime DATETIME)
INSERT INTO #Event
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00')

SELECT TOP (1) WITH TIES *
FROM #Event AS A
CROSS APPLY (SELECT EventDate = CAST(EventDateTime AS DATE)) AS B
WHERE B.EventDate <= @Input
ORDER BY B.EventDate DESC
</code>```

SQL Fiddle wasn't letting me create a variable, but here's a the code conceptually for a more efficient version for MySQL. It grabs the desired date range in the first query, then uses it to filter in the second query. I think it should perform far better than the accepted answer assuming you have an index on EventDateTime

```<code>CREATE TABLE Event (
ID MEDIUMINT NOT NULL AUTO_INCREMENT
,EventDateTime DATETIME
,PRIMARY KEY (ID));

INSERT INTO Event (EventDateTime)
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00');

/*Need to save these off to variables to use in later query*/
SELECT TIMESTAMP(CAST(EventDateTime AS DATE)) AS StartRange
  ,TIMESTAMP(CAST(EventDateTime AS DATE)) + INTERVAL 1 DAY AS EndRange
FROM Event
WHERE EventDateTime < DATE_ADD('2022-01-04' /*Input*/,INTERVAL 1 DAY)
ORDER BY EventDateTime DESC
LIMIT 1;

SELECT *
FROM Event
WHERE EventDateTime >= StartRange
AND EventDateTime < EndRange
</code>```

Title: Search for closes index on SQL table

Body:
I have a hypothetical SQL table "EVENTS", with two columns, a UUID index column, and a DateTime column,
The table is populated with values ranging from 1900-01-01 to today, it is not ordered, there are numerous dates missing.

The query that I have to run is basically 'retrieve all events that happened at the requested date (start to the end of the day) or the closest previous date'

If I were looking for all events in a day that I know that exists in the database it would be something as simple as:

SELECT * FROM Events e
WHERE
e.date BETWEEN $START_OF_DAY AND $END_OF_DAY;

But if that date doesn't exist I must retrieve the latest date up to the requested date.

Body:
Grab current day, but if no records found, will return all records from the nearest previous day with records.
So in my sample data, Jan 2 returns 3 events dated Jan 1

SQL Server Solution

DECLARE @Input DATE = '2022-01-02' /*Try Jan 1,2,3, or 4*/
DROP TABLE IF EXISTS #Event

CREATE TABLE #Event (ID INT IDENTITY(1,1),EventDateTime DATETIME)
INSERT INTO #Event
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00')

SELECT TOP (1) WITH TIES *
FROM #Event AS A
CROSS APPLY (SELECT EventDate = CAST(EventDateTime AS DATE)) AS B
WHERE B.EventDate <= @Input
ORDER BY B.EventDate DESC

SQL Fiddle wasn't letting me create a variable, but here's a the code conceptually for a more efficient version for MySQL. It grabs the desired date range in the first query, then uses it to filter in the second query. I think it should perform far better than the accepted answer assuming you have an index on EventDateTime

CREATE TABLE Event (
ID MEDIUMINT NOT NULL AUTO_INCREMENT
,EventDateTime DATETIME
,PRIMARY KEY (ID));

INSERT INTO Event (EventDateTime)
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00');

/*Need to save these off to variables to use in later query*/
SELECT TIMESTAMP(CAST(EventDateTime AS DATE)) AS StartRange
  ,TIMESTAMP(CAST(EventDateTime AS DATE)) + INTERVAL 1 DAY AS EndRange
FROM Event
WHERE EventDateTime < DATE_ADD('2022-01-04' /*Input*/,INTERVAL 1 DAY)
ORDER BY EventDateTime DESC
LIMIT 1;

SELECT *
FROM Event
WHERE EventDateTime >= StartRange
AND EventDateTime < EndRange


问:
make a RTL navigation Drawer in android
I want to make my navigation open from right to left. But as soon as I change any of these steps my program face to error force closed after click on navigation after running the app.

My main_activity.xml

```<code><include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />
</code>```

My custom_toolbar.xml

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_gravity="right"
    android:background="@color/colorPrimary">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title"
        android:padding="8dp"
        android:textColor="#fff"
        android:textSize="18sp"
        />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/cnews"
        android:tint="#fff"
        android:layout_gravity="right"
        />
</android.support.v7.widget.Toolbar>

//content
<include layout="@layout/content_main" /> </LinearLayout>
</code>```

My appbar_main.xml

```<code><include layout="@layout/toolbar_main" />
</code>```

My main_activity.java

```<code>import android.app.FragmentManager; import android.os.Bundle;  import android.support.design.widget.NavigationView;  import android.support.v4.view.GravityCompat;  import android.support.v4.widget.DrawerLayout;  import android.support.v7.app.ActionBarDrawerToggle;   import android.support.v7.app.AppCompatActivity;   import android.support.v7.widget.Toolbar; import android.view.Menu;   import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.home_page) {
            Home_page_fragment homeFragment = new Home_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , homeFragment, homeFragment.getTag()).commit();
        } else if (id == R.id.tour_page) {
            Tour_page_fragment tourFragment = new Tour_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , tourFragment, tourFragment.getTag()).commit();

        } else if (id == R.id.lstour_page) {
            LsTour_page_fragment LstourFragment = new LsTour_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , LstourFragment, LstourFragment.getTag()).commit();

        } else if (id == R.id.hotel_page) {

        } else if (id == R.id.agency_page) {

        } else if (id == R.id.news_page) {

        }else if (id == R.id.logbook_page) {

        }else if (id == R.id.message_page) {

        }else if (id == R.id.favorite_page) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    } }
</code>```

I changed "Start" to "end" in .xml main activity and java main activity get force closed!

I change "start" to "right" get force closed!!

I used RTL library but again get forced closed!!!

Thanks in advance.

答:
I suggest you that use this code to Oncreate main_activity.java :

```<code>getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
</code>```

Title: make a RTL navigation Drawer in android

Body:
I want to make my navigation open from right to left. But as soon as I change any of these steps my program face to error force closed after click on navigation after running the app.

My main_activity.xml

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

My custom_toolbar.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_gravity="right"
    android:background="@color/colorPrimary">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title"
        android:padding="8dp"
        android:textColor="#fff"
        android:textSize="18sp"
        />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/cnews"
        android:tint="#fff"
        android:layout_gravity="right"
        />
</android.support.v7.widget.Toolbar>

//content
<include layout="@layout/content_main" /> </LinearLayout>

My appbar_main.xml

<include layout="@layout/toolbar_main" />

My main_activity.java

import android.app.FragmentManager; import android.os.Bundle;  import android.support.design.widget.NavigationView;  import android.support.v4.view.GravityCompat;  import android.support.v4.widget.DrawerLayout;  import android.support.v7.app.ActionBarDrawerToggle;   import android.support.v7.app.AppCompatActivity;   import android.support.v7.widget.Toolbar; import android.view.Menu;   import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.home_page) {
            Home_page_fragment homeFragment = new Home_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , homeFragment, homeFragment.getTag()).commit();
        } else if (id == R.id.tour_page) {
            Tour_page_fragment tourFragment = new Tour_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , tourFragment, tourFragment.getTag()).commit();

        } else if (id == R.id.lstour_page) {
            LsTour_page_fragment LstourFragment = new LsTour_page_fragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.mainContent , LstourFragment, LstourFragment.getTag()).commit();

        } else if (id == R.id.hotel_page) {

        } else if (id == R.id.agency_page) {

        } else if (id == R.id.news_page) {

        }else if (id == R.id.logbook_page) {

        }else if (id == R.id.message_page) {

        }else if (id == R.id.favorite_page) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    } }

I changed "Start" to "end" in .xml main activity and java main activity get force closed!

I change "start" to "right" get force closed!!

I used RTL library but again get forced closed!!!

Thanks in advance.

Body:
I suggest you that use this code to Oncreate main_activity.java :

getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);


问:
How do I pass primary key of the entry created by a django-form, to the form in next page after that
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship):

```<code>class Project(models.Model):
    title = models.CharField(max_length=2000)
    state_of_project = models.CharField(max_length=10, default='ongoing')
    introduction = models.TextField(blank=True)

class Role(models.Model):
    role_name =  models.CharField(max_length=30)
    project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True)

    def __str__(self):
        return self.role_name
</code>```

After submitting a form for model Project, I wanted to redirect user to fill the next form for model Role. The new roles added there should automatically have their foreign key project point towards the project created just before.

How can I make that happen? I am specifically having problem adding mechanism of passing the primary key of newly submitted entry (for model Project) to the next form(for model Role).

答:
You have to pass the primary key to urls.py and get it through the views.py

for example :

```<code>#urls.py
path("add-role/<int:project_id>" ,views.add_role , name="add.role"),

------------

#views.py
def add_role(request , project_id):
        project = Project.objects.get(id=project_id)
        if request.method == "POST":
            form = ProjectForm(request.POST)
            if form.is_valid():
                f = form.save(commit=False)
                f.project = project
                f.save()
                return redirect("projects")
            else:
                return render(request , 'add-project.html' ,{"form":form})
        return render(request , 'add-project.html' ,  {"project":project})
</code>```

and something like this in your html:

```<code><form method="post" action="{% url 'add.role' project.id %}">
 {% csrf_token %}
 <input type="text" name="role_name" />
</form>
</code>```

Body:
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship):

class Project(models.Model):
    title = models.CharField(max_length=2000)
    state_of_project = models.CharField(max_length=10, default='ongoing')
    introduction = models.TextField(blank=True)

class Role(models.Model):
    role_name =  models.CharField(max_length=30)
    project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True)

    def __str__(self):
        return self.role_name

After submitting a form for model Project, I wanted to redirect user to fill the next form for model Role. The new roles added there should automatically have their foreign key project point towards the project created just before.

How can I make that happen? I am specifically having problem adding mechanism of passing the primary key of newly submitted entry (for model Project) to the next form(for model Role).

Body:
You have to pass the primary key to urls.py and get it through the views.py

for example :

#urls.py
path("add-role/<int:project_id>" ,views.add_role , name="add.role"),

------------

#views.py
def add_role(request , project_id):
        project = Project.objects.get(id=project_id)
        if request.method == "POST":
            form = ProjectForm(request.POST)
            if form.is_valid():
                f = form.save(commit=False)
                f.project = project
                f.save()
                return redirect("projects")
            else:
                return render(request , 'add-project.html' ,{"form":form})
        return render(request , 'add-project.html' ,  {"project":project})

and something like this in your html:

<form method="post" action="{% url 'add.role' project.id %}">
 {% csrf_token %}
 <input type="text" name="role_name" />
</form>


问:
Capture all Windows 7 Touch events, not just on my form when it has focus
I have an application which has a form, but the fact that it has a form is irrelevant.

With this app, I need to listen to all Operating System level Touch events. Basically I need to capture that the screen has been touched no matter which form has focus, gather all the info like coordinates etc. and then do whatever with it.

I'll actually be sending it on to another app via a Windows Message but that's not relevant either. I just need to know how to listen and capture ALL OS level touch + drag events etc.

答:
This link explains the topic of keyboard/mouse event hooks.

It is a rather advanced subject however, filled with lots of low-level interop.  I'd avoid such a task and try to come up with a different solution for this.  What is your final goal with this application?