问:
Make a button visible after a PHP script has been executed
Hi all I have a requirement to make an add items button visible once the user has logged in im trying to test this with the below test code but am not sure of the best way to make a button visible after a php call any help would be appreciated.

passwordchecker.php

```<code><?php
        $message = "access granted, you can now add items";
        $message1 = "access denied";
    $user = $_POST['username'];
        $pass = $_POST['password'];
        if ($user == "admin" && $pass == "admin")
        {
        echo "<script type='text/javascript'>
          alert('$message');
          </script>";
        die();
        }
        else
        {
         echo "<script type='text/javascript'>
          alert('$message1');
          </script>";
              die();
        }
?>
</code>```

button we are trying to display

```<code><a href="#AddItems" class="btn btn-default btn-lg history" style="visibility:hidden" id="additems">Add item</a>
</code>```

Any help would be appreciated usually I would use Jquery to show and hide buttons but i'm not sure if this is possible in the current situation or if it is the best way to handle it.

thanks in advance!

答:
First of all use Session variables to check authentication.
Basically, you can be done this without any javascript
simply

```<code>if ($user == "admin" && $pass == "admin")
    {
       ?>
        <a href="#AddItems" class="btn btn-default btn-lg history" style="visibility:hidden" id="additems">Add item</a>
      <?php
      }
</code>```

or if you want to use jQuery

Add item

```<code><?php
    if ($user == "admin" && $pass == "admin")
        {
         ?>
           <script>
               $( document ).ready(function() {
                  $('#additems').show();
                  alert(<?php echo $message;?>);
               });
            </script>
          <?php
          } else {
              <script>
               $( document ).ready(function() {
                  alert(<?php echo $message1;?>);
               });
            </script>
          }
</code>```

using sessions is the best practice for authentication so use

```<code>if (isset($_SESSION['user'])) instead of if ($user == "admin" && $pass == "admin")
</code>```

after setting $_SESSION['user'] in login or somewhere you wanted

Body:
Hi all I have a requirement to make an add items button visible once the user has logged in im trying to test this with the below test code but am not sure of the best way to make a button visible after a php call any help would be appreciated.

passwordchecker.php

<?php
        $message = "access granted, you can now add items";
        $message1 = "access denied";
    $user = $_POST['username'];
        $pass = $_POST['password'];
        if ($user == "admin" && $pass == "admin")
        {
        echo "";
        die();
        }
        else
        {
         echo "";
              die();
        }
?>

button we are trying to display

Add item

Any help would be appreciated usually I would use Jquery to show and hide buttons but i'm not sure if this is possible in the current situation or if it is the best way to handle it.

thanks in advance!

Body:
First of all use Session variables to check authentication.
Basically, you can be done this without any javascript
simply

if ($user == "admin" && $pass == "admin")
    {
       ?>
        <a href="#AddItems" class="btn btn-default btn-lg history" style="visibility:hidden" id="additems">Add item</a>
      <?php
      }

or if you want to use jQuery

Add item

<?php
    if ($user == "admin" && $pass == "admin")
        {
         ?>
           <script>
               $( document ).ready(function() {
                  $('#additems').show();
                  alert(<?php echo $message;?>);
               });
            </script>
          <?php
          } else {
              <script>
               $( document ).ready(function() {
                  alert(<?php echo $message1;?>);
               });
            </script>
          }

using sessions is the best practice for authentication so use

if (isset($_SESSION['user'])) instead of if ($user == "admin" && $pass == "admin")

after setting $_SESSION['user'] in login or somewhere you wanted


来源: stackexchange

问:
Pygame screen display issue
```<code>import pygame
pygame.init()

display_width = (640)
display_height = (480)

title = pygame.display.set_caption("test")
IMG = pygame.image.load("image.png")
screen = pygame.display.set_mode((display_width,display_height))

screen.blit(IMG,(1,1))

pygame.display.update()
</code>```

Whenever I use pygame, even simple displays like this are skewed for me. it shows 0,0 at around the middle of my display screen and i dont know why. Basically, it is showing - x values on the x axis help!
I am using python 2.7 and this seems to not be a coding issue, but rather something else. please help! ty

答:
I've not been able to replicate your problem with the above code in Python 2.7.12, the image is a red, fifty-pixel square:

Here's an extended demo that will draw the image around the cursor position based on the mouse button clicked. Perhaps that'll help you get towards the behaviour you're after.

```<code>import pygame

if __name__ == "__main__":
    pygame.init()
    screen_width, screen_height = 640, 480
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Blit Demo')
    clock = pygame.time.Clock() #for limiting FPS
    FPS = 10
    exit_demo = False
    # start with a white background
    screen.fill(pygame.Color("white"))
    img = pygame.image.load("image.png")
    width, height = img.get_size()
    pos = (1,1)  # initial position to draw the image
    # main loop
    while not exit_demo:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_demo = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # fill the screen with white, erasing everything
                    screen.fill(pygame.Color("white"))
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:  # left
                    pos = (event.pos[0] - width, event.pos[1] - height)
                elif event.button == 2: # middle
                    pos = (event.pos[0] - width // 2, event.pos[1] - height // 2)
                elif event.button == 3: # right
                    pos = event.pos

        # draw the image here
        screen.blit(img, pos)
        # update screen
        pygame.display.update()
        clock.tick(FPS)
    pygame.quit()
    quit()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pygame screen display issue

Body:
import pygame
pygame.init()

display_width = (640)
display_height = (480)

title = pygame.display.set_caption("test")
IMG = pygame.image.load("image.png")
screen = pygame.display.set_mode((display_width,display_height))

screen.blit(IMG,(1,1))

pygame.display.update()

Whenever I use pygame, even simple displays like this are skewed for me. it shows 0,0 at around the middle of my display screen and i dont know why. Basically, it is showing - x values on the x axis help!
I am using python 2.7 and this seems to not be a coding issue, but rather something else. please help! ty

Body:
I've not been able to replicate your problem with the above code in Python 2.7.12, the image is a red, fifty-pixel square:

Here's an extended demo that will draw the image around the cursor position based on the mouse button clicked. Perhaps that'll help you get towards the behaviour you're after.

import pygame

if __name__ == "__main__":
    pygame.init()
    screen_width, screen_height = 640, 480
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Blit Demo')
    clock = pygame.time.Clock() #for limiting FPS
    FPS = 10
    exit_demo = False
    # start with a white background
    screen.fill(pygame.Color("white"))
    img = pygame.image.load("image.png")
    width, height = img.get_size()
    pos = (1,1)  # initial position to draw the image
    # main loop
    while not exit_demo:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_demo = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # fill the screen with white, erasing everything
                    screen.fill(pygame.Color("white"))
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:  # left
                    pos = (event.pos[0] - width, event.pos[1] - height)
                elif event.button == 2: # middle
                    pos = (event.pos[0] - width // 2, event.pos[1] - height // 2)
                elif event.button == 3: # right
                    pos = event.pos

        # draw the image here
        screen.blit(img, pos)
        # update screen
        pygame.display.update()
        clock.tick(FPS)
    pygame.quit()
    quit()


问:
How do you compare duplicate values?
```<code>private int pic = 0;
private List<int> num = null;
.
.
.

.
.
public void ss(){
this.imageList = new List<Image>();
this.imageList.Add(Properties.Resources.1);
this.imageList.Add(Properties.Resources.2);
this.imageList.Add(Properties.Resources.3);
.
.
.
.
.
this.imageList.Add(Properties.Resources.58);
this.imageList.Add(Properties.Resources.59);
 this.pic = GetMyRandomNumber(0, 60);

 if (this.num == null)
    this.num= new List<int>();

 while (this.num.Count < 61)
 {
       pic = GetMyRandomNumber(0, 60);

       if (this.num.Contains(pic) == false)
       {
             this.num.Add(pic);
             break;
       }
 }
 this.pictureBox1.Image = imageList[pic];
</code>```

}

This code checks for duplicates when calling the ss method

Store the value in num, and check if the stored value is duplicated.

But the same value is stored in pic

duplicate values continue to appear.

How do I fix it?

答:
A couple things could be happening here. Inside the "GetMyRandomNumber" method you may be using the "Random" class that needs to be used in a certain way to avoid the object retrieving the same value back to back and considerations for thread safety.

Here is a quote from MSDN on using "Random"

Instead of instantiating individual Random objects, we recommend that you create a single Random instance to generate all the random numbers needed by your app. However, Random objects are not thread safe. If your app calls Random methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0.

It also appears you would like to keep track of the random numbers chosen.

Here is an alternate approach that will also help with the lookup speed.

```<code>    static void Main(string[] args)
    {
        HashSet<int> picked = new HashSet<int>(Enumerable.Range(0, 60));
        int pic = GetMyRandomNumber(picked);
        //...Other code here
    }

    private readonly static object _syncLock = new object();
    private readonly static Random _random = new Random();

    static int GetMyRandomNumber(HashSet<int> picked)
    {
        lock (_syncLock)
        {
            int rand = _random.Next(0, picked.Count);
            picked.Remove(rand);

            return rand;
        }
    }
</code>```

This ensures that once you've chosen a random number from 0-60, it can't be chosen again.

Title: How do you compare duplicate values?

Body:
private int pic = 0;
private List<int> num = null;
.
.
.

.
.
public void ss(){
this.imageList = new List<Image>();
this.imageList.Add(Properties.Resources.1);
this.imageList.Add(Properties.Resources.2);
this.imageList.Add(Properties.Resources.3);
.
.
.
.
.
this.imageList.Add(Properties.Resources.58);
this.imageList.Add(Properties.Resources.59);
 this.pic = GetMyRandomNumber(0, 60);

 if (this.num == null)
    this.num= new List<int>();

 while (this.num.Count < 61)
 {
       pic = GetMyRandomNumber(0, 60);

       if (this.num.Contains(pic) == false)
       {
             this.num.Add(pic);
             break;
       }
 }
 this.pictureBox1.Image = imageList[pic];

}

This code checks for duplicates when calling the ss method

Store the value in num, and check if the stored value is duplicated.

But the same value is stored in pic

duplicate values continue to appear.

How do I fix it?

Body:
A couple things could be happening here. Inside the "GetMyRandomNumber" method you may be using the "Random" class that needs to be used in a certain way to avoid the object retrieving the same value back to back and considerations for thread safety.

Here is a quote from MSDN on using "Random"

Instead of instantiating individual Random objects, we recommend that you create a single Random instance to generate all the random numbers needed by your app. However, Random objects are not thread safe. If your app calls Random methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0.

It also appears you would like to keep track of the random numbers chosen.

Here is an alternate approach that will also help with the lookup speed.

    static void Main(string[] args)
    {
        HashSet<int> picked = new HashSet<int>(Enumerable.Range(0, 60));
        int pic = GetMyRandomNumber(picked);
        //...Other code here
    }

    private readonly static object _syncLock = new object();
    private readonly static Random _random = new Random();

    static int GetMyRandomNumber(HashSet<int> picked)
    {
        lock (_syncLock)
        {
            int rand = _random.Next(0, picked.Count);
            picked.Remove(rand);

            return rand;
        }
    }

This ensures that once you've chosen a random number from 0-60, it can't be chosen again.


问:
N+1 query persists even after using includes?
The following should load a bunch of associated using JOINS:

```<code>Event.where(id: @events.map(&:id))
     .includes(
               :user,
               :event_category,
               task: [:document_tasks, task_followers: :follower]
              )
</code>```

Now when I step through each event and use the associations retrieved above, I should not see any N+1 queries:

```<code>Event.where(id: @events.map(&:id))
     .includes(
                :user,
                :event_category,
                task: [:document_tasks, task_followers: :follower]
      ).each do |event|
        owner = event.task.task_followers.where(owner: true).first.follower
      end
</code>```

But I see a ton of queries like the following:

```<code>D, [2017-12-06T19:46:17.536892 #26637] DEBUG -- :   TaskFollower Load (2.9ms)
SELECT  `task_followers`.* FROM `task_followers`
WHERE `task_followers`.`task_id` = 11635 AND `task_followers`.`owner` = 1
ORDER BY `task_followers`.`id` ASC LIMIT 1
</code>```

Relationships:

```<code>class Event < ActiveRecord::Base
    belongs_to :user
    belongs_to :task
    belongs_to :event_category
end

class Task < ActiveRecord::Base
    has_many :document_tasks, dependent: :destroy
    has_many :task_followers, dependent: :destroy
    has_many :followers, through: :task_followers, dependent: :destroy
    has_one :fullcalendar_engine_event, class_name: 'FullcalendarEngine::Event'
end
</code>```

Why is this happening?

答:
I believe this is due to your calling where(owner: true). This is causing it to send another query to filter your results. Trying replacing it with select(&:owner?) instead.

```<code># Change this line
owner = event.task.task_followers.where(owner: true).first.follower
# to this
owner = event.task.task_followers.select(&:owner?).first.follower
</code>```

Body:
The following should load a bunch of associated using JOINS:

Event.where(id: @events.map(&:id))
     .includes(
               :user,
               :event_category,
               task: [:document_tasks, task_followers: :follower]
              )

Now when I step through each event and use the associations retrieved above, I should not see any N+1 queries:

Event.where(id: @events.map(&:id))
     .includes(
                :user,
                :event_category,
                task: [:document_tasks, task_followers: :follower]
      ).each do |event|
        owner = event.task.task_followers.where(owner: true).first.follower
      end

But I see a ton of queries like the following:

D, [2017-12-06T19:46:17.536892 #26637] DEBUG -- :   TaskFollower Load (2.9ms)
SELECT  `task_followers`.* FROM `task_followers`
WHERE `task_followers`.`task_id` = 11635 AND `task_followers`.`owner` = 1
ORDER BY `task_followers`.`id` ASC LIMIT 1

Relationships:

class Event < ActiveRecord::Base
    belongs_to :user
    belongs_to :task
    belongs_to :event_category
end

class Task < ActiveRecord::Base
    has_many :document_tasks, dependent: :destroy
    has_many :task_followers, dependent: :destroy
    has_many :followers, through: :task_followers, dependent: :destroy
    has_one :fullcalendar_engine_event, class_name: 'FullcalendarEngine::Event'
end

Why is this happening?

Body:
I believe this is due to your calling where(owner: true). This is causing it to send another query to filter your results. Trying replacing it with select(&:owner?) instead.

# Change this line
owner = event.task.task_followers.where(owner: true).first.follower
# to this
owner = event.task.task_followers.select(&:owner?).first.follower


问:
Rstudio will not knit
Rstudio will not knit. I have been using it for a few weeks in a course.

When I try to knit it executes until it comes to some code and it stops. The code is

ggplot(data = gss, aes(x = year, fill = degree)) +
   geom_bar()

The message is

could not find function "ggplot"

This happens with other functions as well. With the code commented out is will run and produce an HTML file.

I have reinstalled R and Rstudio twice. I have had difficulty with my AV software (Bitdefender) blocking the install of some of the apps. The software is a new version updated a couple of weeks ago.

答: Please load the package in the document (R Markdown? You didn't say) before you use any functions in it, e.g., library(ggplot2).

Title: Rstudio will not knit


问:
react native redux storing state across multiple pages
trying to learn redux and having issues passing state around to keep a user up to date, main example - create a user on page 1, navigate to page 2, set something on the user and navigate back to page 1.

having to create an action for page2 navigated passing the user and also creating an action for page 1 navigated passing the user back and forth.

what is the correct usage of redux?

user must be passed back and forth to keep app sync

```<code>{
page1: user: {...data}} set user details,
page2: user: {...data}} passed user details but able to edit user
 details and able to go back to page1
}
</code>```

user can be accessed globally at any time and updated with action calls

```<code>{
 userDetails: {user: {...data}},
 page1: only page specific state, accesses this.props.userDetails.user
 page2: only page specific state, accesses this.props.userDetails.user
}
</code>```

答:
So normally you'd just subscribe whatever component needed user information to the Redux store, typically with react-redux. In page2 you'd dispatch an action to modify the user in the store, then when the reducer processes those modifications, page1 can update with the new value.

An action for mutating the user might look like this:

```<code>{
  type: 'SET_USER_EMAIL',
  email: 'foo@wombat.com'
}
</code>```

You'd dispatch that action from your page2 component. It'd be received in the reducer for the user object in the store:

```<code>switch (action.type) {
  case 'SET_USER_EMAIL':
    return {
      ...state,
      email: action.email
    }
}
</code>```

If both pages are subscribed to the Redux store, there's not really a "passing back and forth" of the user value so much as both pages are notified when the store changes, and can update themselves based on those changes. I guess you'd say that each component listens to the store and can take action when it updates.

Navigation is a somewhat separate issue, though it certainly can use Redux. I feel like possibly you might benefit from revisiting some of the core concepts to make things clearer.

Body:
trying to learn redux and having issues passing state around to keep a user up to date, main example - create a user on page 1, navigate to page 2, set something on the user and navigate back to page 1.

having to create an action for page2 navigated passing the user and also creating an action for page 1 navigated passing the user back and forth.

what is the correct usage of redux?

user must be passed back and forth to keep app sync

{
page1: user: {...data}} set user details,
page2: user: {...data}} passed user details but able to edit user
 details and able to go back to page1
}

user can be accessed globally at any time and updated with action calls

{
 userDetails: {user: {...data}},
 page1: only page specific state, accesses this.props.userDetails.user
 page2: only page specific state, accesses this.props.userDetails.user
}

Body:
So normally you'd just subscribe whatever component needed user information to the Redux store, typically with react-redux. In page2 you'd dispatch an action to modify the user in the store, then when the reducer processes those modifications, page1 can update with the new value.

An action for mutating the user might look like this:

{
  type: 'SET_USER_EMAIL',
  email: 'foo@wombat.com'
}

You'd dispatch that action from your page2 component. It'd be received in the reducer for the user object in the store:

switch (action.type) {
  case 'SET_USER_EMAIL':
    return {
      ...state,
      email: action.email
    }
}

If both pages are subscribed to the Redux store, there's not really a "passing back and forth" of the user value so much as both pages are notified when the store changes, and can update themselves based on those changes. I guess you'd say that each component listens to the store and can take action when it updates.

Navigation is a somewhat separate issue, though it certainly can use Redux. I feel like possibly you might benefit from revisiting some of the core concepts to make things clearer.


问:
PHP json_encode - create JSON array
I've used the json_encode function in the past to create simply JSON objects like this:

```<code>$payload =  array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);
</code>```

which creates this:

```<code>{"user":"john smith","password":"abc12345","group":"sales"}
</code>```

I now need to generate a JSON array like this:

```<code>{
  "query": [
    {
      "Date": "11/01/2017...12/31/2017"
    }
  ]
}
</code>```

but I can't find the correct syntax.

答:
You can simply create a 2d array in php.</p>

```<code>$payload =  array (
    "query" => array(
         array(
             "date" => "11/01/2017...12/31/2017",
             "other sub key" => "other sub value"
         )
    ),
    "other main key" => array(
         array(
             "other sub key" => "other sub value",
             etc...
         )
    )
);
</code>```

Title: PHP json_encode - create JSON array

Body:
I've used the json_encode function in the past to create simply JSON objects like this:

$payload =  array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);

which creates this:

{"user":"john smith","password":"abc12345","group":"sales"}

I now need to generate a JSON array like this:

{
  "query": [
    {
      "Date": "11/01/2017...12/31/2017"
    }
  ]
}

but I can't find the correct syntax.

Body:
You can simply create a 2d array in php.

$payload =  array (
    "query" => array(
         array(
             "date" => "11/01/2017...12/31/2017",
             "other sub key" => "other sub value"
         )
    ),
    "other main key" => array(
         array(
             "other sub key" => "other sub value",
             etc...
         )
    )
);


问:
Add new column on csv file in python pandas
import pandas as np
from pandas import Series, DataFrame

```<code>dframe_final.to_csv('C:/Program Files/source/csv_data/2015/Merged files/jjj_all_merged.csv')
</code>```

I have this part of my code and I need to add a new column at the end of this csv file and name it "New_name".
And populate it based on different criteria:

For example, if cell1 is "a" and cell2 is "b" and cell3 is "1" and cell4 is "2 or 5" then enter "OK"
If not, enter "NOT OK" or leave empty.

```<code>Column 1    Column 2    Column 3    Column 4    "New_name"
a              b           1           2            "OK"
a              b           1           5            "OK"
c              d           e           f          "NOT OK"
</code>```

PLEASE HELP!!! :)

答:
In my case

```<code>with open('csv_file.csv', 'a', newline='') as csvfile:
                fwriter = csv.writer(csvfile, delimiter=',', quotechar='/', quoting=csv.QUOTE_MINIMAL)
                fwriter.writerow(List_to_add)
</code>```

a in options means 'append'. Then I imported the csv file as 'pd.DataFrame'.

```<code>df = pd.read_csv('csv_file.csv')
</code>```

I do not know if this is the best way.

```<code>import pandas as pd
import csv
</code>```

You will need above two things.

Body:
import pandas as np
from pandas import Series, DataFrame

dframe_final.to_csv('C:/Program Files/source/csv_data/2015/Merged files/jjj_all_merged.csv')

I have this part of my code and I need to add a new column at the end of this csv file and name it "New_name".
And populate it based on different criteria:

For example, if cell1 is "a" and cell2 is "b" and cell3 is "1" and cell4 is "2 or 5" then enter "OK"
If not, enter "NOT OK" or leave empty.

Column 1    Column 2    Column 3    Column 4    "New_name"
a              b           1           2            "OK"
a              b           1           5            "OK"
c              d           e           f          "NOT OK"

PLEASE HELP!!! :)

Body:
In my case

with open('csv_file.csv', 'a', newline='') as csvfile:
                fwriter = csv.writer(csvfile, delimiter=',', quotechar='/', quoting=csv.QUOTE_MINIMAL)
                fwriter.writerow(List_to_add)

a in options means 'append'. Then I imported the csv file as 'pd.DataFrame'.

df = pd.read_csv('csv_file.csv')

I do not know if this is the best way.

import pandas as pd
import csv

You will need above two things.


问:
R modify value in one column if content in another column contains string
I am working with a large data set where I want to determine if a column containing text strings passes a logical test where I can subset it out later. Currently, I'm trying to build the test column for each row. The test is based on if the cell contains less than 2 relevant characters, but I want to keep the full set of characters in the actual cell. The following is a simplified example of what I am trying to do:

Suppose I have the following data frame:

```<code>df <- data.frame(matrix(NA, nrow = 5, ncol = 1))
colnames(df) <- "test"
df$test <- c("one", "two", "three", "one", "onetwo")
df$hyp <- ("two", "one", "onetwo", "one", "two")
df$testcount <- sapply(df$test, str_length)
df$hypcount <- sapply(df$hyp, str_length)
df

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         3        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         6        3
</code>```

I want to identify a text string, like "two", and if a row in the test column or hyp column (depending on the test I'm running. I don't want this to run on both columns) contains the string (though is not identical to the string), then I want that same row to subtract the number of characters in the string I identified from the testcount or hypcount columns.

For example, if I run this function on the text string "two" in the test column, then I should get the following output:

```<code>    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3
</code>```

And if I were to run this on the hyp column, then I should get the following output:

```<code>    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0
</code>```

I have tried three approaches. First I tried using an if function to run the replacement conditionally (on this test I tested for the string "one" instead of "two"):

```<code>if(grepl("one", df$test)) {
  df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }
</code>```

But this returns the warning:
"In if (grepl("one", df$test)) { :
  the condition has length > 1 and only the first element will be used"

This leads to a correct substitution for the string "one", but not the string "two". Further, if I substitute for string "two" in the hyp column, the function works, but not if I run the substitution for string "one". I suspect this is because it only runs the test on the first row, and if it is true, then it checks the entire data frame.

Next I tried running the function within an lapply function:

```<code>df <- data.frame(lapply(df, function(x) {
  if(grepl("one", df$test)) {
    df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }}))
</code>```

This also didn't work, though I don't fully understand why. Somehow it ends up returning the output:

```<code>  test hyp testcount hypcount
1    0   0         0        0
2    0   0         0        0
3    3   3         3        3
</code>```

Lastly, I tried running it as an ifelse operation (here I switched to replacing for string "two" so I don't mistakenly think the function works on all rows):

```<code>df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3))
</code>```

The strange thing is, this worked when I first applied it a few days ago. I tested it for the strings "two", "on", and "one", and it worked properly. Now, when I got around to applying it to my actual data, it didn't work. Further, when I went back to the testing to see what went wrong, it no longer is working. It simply returns the error:
  "Error in ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)),  :
  argument "no" is missing, with no default"

I have tried two solutions to this. First, I tried adding a statement into the "no" argument that would have no impact on my data:

```<code> df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), T)
</code>```

However, this causes it to return the output:

```<code>    test    hyp testcount hypcount
1    one    two         1        3
2    two    one         3        3
3  three onetwo         1        6
4    one    one         1        3
5 onetwo    two         0        3
</code>```

Next I tried substituting a meaningful "no" argument:

```<code> df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount))
</code>```

But now it returns the output:

```<code>    test    hyp testcount hypcount
1    one    two        -3        3
2    two    one         0        3
3  three onetwo        -3        6
4    one    one         0        3
5 onetwo    two        -3        3
</code>```

I don't understand this output.

My question is, can anyone help me to understand why this is not working, and offer a solution? Thanks in advance!

答:
I'm not sure I completely understand your problem, but the following reproduces your expected outcome for the two test cases.

```<code># The first argument is the column where you want to find id
# I'm unsure about what you want to subtract; subtracting the entry from
# the count columns corresponds to setting the entry to 0
some_function <- function(col, id, df) {
    idx <- which(colnames(df) == col);
    df[df[, idx] == id, idx + 2] <- 0;
    return(df);
}

some_function("test", "two", df);
#    test    hyp testcount hypcount
#1    one    two         3        3
#2    two    one         0        3
#3  three onetwo         5        6
#4    one    one         3        3
#5 onetwo    two         6        3

some_function("hyp", "two", df)
#    test    hyp testcount hypcount
#1    one    two         3        0
#2    two    one         3        3
#3  three onetwo         5        6
#4    one    one         3        3
#5 onetwo    two         6        0
</code>```

Also, you say "contains the string (though is not identical to the string)", but for entries containing "onetwo" you do not subtract the count values. So it is complete matches that you are after?

Body:
I am working with a large data set where I want to determine if a column containing text strings passes a logical test where I can subset it out later. Currently, I'm trying to build the test column for each row. The test is based on if the cell contains less than 2 relevant characters, but I want to keep the full set of characters in the actual cell. The following is a simplified example of what I am trying to do:

Suppose I have the following data frame:

df <- data.frame(matrix(NA, nrow = 5, ncol = 1))
colnames(df) <- "test"
df$test <- c("one", "two", "three", "one", "onetwo")
df$hyp <- ("two", "one", "onetwo", "one", "two")
df$testcount <- sapply(df$test, str_length)
df$hypcount <- sapply(df$hyp, str_length)
df

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         3        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         6        3

I want to identify a text string, like "two", and if a row in the test column or hyp column (depending on the test I'm running. I don't want this to run on both columns) contains the string (though is not identical to the string), then I want that same row to subtract the number of characters in the string I identified from the testcount or hypcount columns.

For example, if I run this function on the text string "two" in the test column, then I should get the following output:

    test    hyp testcount hypcount
1    one    two         3        3
2    two    one         0        3
3  three onetwo         5        6
4    one    one         3        3
5 onetwo    two         3        3

And if I were to run this on the hyp column, then I should get the following output:

    test    hyp testcount hypcount
1    one    two         3        0
2    two    one         3        3
3  three onetwo         5        3
4    one    one         3        3
5 onetwo    two         6        0

I have tried three approaches. First I tried using an if function to run the replacement conditionally (on this test I tested for the string "one" instead of "two"):

if(grepl("one", df$test)) {
  df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }

But this returns the warning:
"In if (grepl("one", df$test)) { :
  the condition has length > 1 and only the first element will be used"

This leads to a correct substitution for the string "one", but not the string "two". Further, if I substitute for string "two" in the hyp column, the function works, but not if I run the substitution for string "one". I suspect this is because it only runs the test on the first row, and if it is true, then it checks the entire data frame.

Next I tried running the function within an lapply function:

df <- data.frame(lapply(df, function(x) {
  if(grepl("one", df$test)) {
    df[which(grepl("one", df$test)), ]$testcount = df[which(grepl("one", df$test)), ]$testcount - 3
  }}))

This also didn't work, though I don't fully understand why. Somehow it ends up returning the output:

  test hyp testcount hypcount
1    0   0         0        0
2    0   0         0        0
3    3   3         3        3

Lastly, I tried running it as an ifelse operation (here I switched to replacing for string "two" so I don't mistakenly think the function works on all rows):

df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3))

The strange thing is, this worked when I first applied it a few days ago. I tested it for the strings "two", "on", and "one", and it worked properly. Now, when I got around to applying it to my actual data, it didn't work. Further, when I went back to the testing to see what went wrong, it no longer is working. It simply returns the error:
  "Error in ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)),  :
  argument "no" is missing, with no default"

I have tried two solutions to this. First, I tried adding a statement into the "no" argument that would have no impact on my data:

 df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), T)

However, this causes it to return the output:

    test    hyp testcount hypcount
1    one    two         1        3
2    two    one         3        3
3  three onetwo         1        6
4    one    one         1        3
5 onetwo    two         0        3

Next I tried substituting a meaningful "no" argument:

 df$testcount <- ifelse(grepl("two", df$test), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount - 3), (df[which(grepl("two", df$test)), ]$testcount = df[which(grepl("two", df$test)), ]$testcount))

But now it returns the output:

    test    hyp testcount hypcount
1    one    two        -3        3
2    two    one         0        3
3  three onetwo        -3        6
4    one    one         0        3
5 onetwo    two        -3        3

I don't understand this output.

My question is, can anyone help me to understand why this is not working, and offer a solution? Thanks in advance!

Body:
I'm not sure I completely understand your problem, but the following reproduces your expected outcome for the two test cases.

# The first argument is the column where you want to find id
# I'm unsure about what you want to subtract; subtracting the entry from
# the count columns corresponds to setting the entry to 0
some_function <- function(col, id, df) {
    idx <- which(colnames(df) == col);
    df[df[, idx] == id, idx + 2] <- 0;
    return(df);
}

some_function("test", "two", df);
#    test    hyp testcount hypcount
#1    one    two         3        3
#2    two    one         0        3
#3  three onetwo         5        6
#4    one    one         3        3
#5 onetwo    two         6        3

some_function("hyp", "two", df)
#    test    hyp testcount hypcount
#1    one    two         3        0
#2    two    one         3        3
#3  three onetwo         5        6
#4    one    one         3        3
#5 onetwo    two         6        0

Also, you say "contains the string (though is not identical to the string)", but for entries containing "onetwo" you do not subtract the count values. So it is complete matches that you are after?


问:
Angular 4-5 HttpClientModule display data
With HttpModule I used this code to get data from Express.js REST API:

```<code>getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}
</code>```

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

```<code>this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });
</code>```

But it doesn't work.

答: HttpClient works best when you cast the returned data. See this link where a complete mini project is setup to show how to get and display data.</p>

Body:
With HttpModule I used this code to get data from Express.js REST API:

getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });

But it doesn't work.


问:
Delete mongo recored by the timestamp in its id
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

```<code>const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});
</code>```

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

```<code>db.messages.remove({createdAt : {$lt : deletionDate}});
</code>```

答:
Use mongo shell:

```<code>db.collection.find({"_id": { "$gt": ObjectId.fromDate(new Date('2017-10-01'))}})
</code>```

Use mongoose:

```<code>Model.find({ _id: { $gt: mongoose.Types.ObjectId.createFromTime(new Date('2018-01-01')) } })
</code>```

will find the needed docs.

Body:
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

db.messages.remove({createdAt : {$lt : deletionDate}});

Body:
Use mongo shell:

db.collection.find({"_id": { "$gt": ObjectId.fromDate(new Date('2017-10-01'))}})

Use mongoose:

Model.find({ _id: { $gt: mongoose.Types.ObjectId.createFromTime(new Date('2018-01-01')) } })

will find the needed docs.


问:
How can I properly get my Luis chatbot working?
I have to connect Luis to node.js and create my first chatbot that, as a first stage should handle simple requests.

I have checked the following links :
https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-recognize-intent-luis

https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/intelligence-LUIS

but getting started has proven to be difficult, what I've done as a first stage is:

```<code>var restify = require('restify');
var builder = require('botbuilder');
var http = require('http');
var recognizer = require ('recognizer');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url);
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: MY_APP_ID,
    appPassword:MY_PASSWORD
});

var bot = new builder.UniversalBot(connector, function (session,args) {
}
});
    var recognizer = new builder.LuisRecognizer(LUIS_ENDPOINT_URL);
    bot.recognizer(recognizer);
</code>```

and not sure how to move forward from here.

What I have in a Luis intent is: calendar.add
what I have as entities is: calendar.location and calendar.subject

what I want the user to say in the bot framework channel emulator:

```<code>add a business meeting schedule in Paris.
</code>```

What the bot should say: Understood the location is Paris and subject is business meeting.

答:
It seems that the utterance add a business meeting schedule in Paris. doesn't match the Calendar.Add intent. So you can try to manually add this utterance in the intent in your LUIS application.

Go to your LUIS application, click Intents list, click Calendar.Add into the edit page.

Type the utterance add a business meeting schedule in Paris. in the box, type enter add the utterance into the list.

Click the business and meeting letters into a big square brackets, select Calendar.Subject in dropdown list, the same click Paris and select Calendar.Location. Finishing the actions, it should looks like:

Click Save to save the edition. Then Train and publish your LUIS application.

Then your bot should match the utterance.

Body:
I have to connect Luis to node.js and create my first chatbot that, as a first stage should handle simple requests.

I have checked the following links :
https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-recognize-intent-luis

https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/intelligence-LUIS

but getting started has proven to be difficult, what I've done as a first stage is:

var restify = require('restify');
var builder = require('botbuilder');
var http = require('http');
var recognizer = require ('recognizer');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url);
});

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: MY_APP_ID,
    appPassword:MY_PASSWORD
});

var bot = new builder.UniversalBot(connector, function (session,args) {
}
});
    var recognizer = new builder.LuisRecognizer(LUIS_ENDPOINT_URL);
    bot.recognizer(recognizer);

and not sure how to move forward from here.

What I have in a Luis intent is: calendar.add
what I have as entities is: calendar.location and calendar.subject

what I want the user to say in the bot framework channel emulator:

add a business meeting schedule in Paris.

What the bot should say: Understood the location is Paris and subject is business meeting.


问:
Null-able DatePicker in windows universal apps
In my windows universal app for tablet, I am working with datepicker to which current date is set automatically. But how do I make it blank or nullable. i have got two date pickers ValidFrom and ValidUntil. ValidFrom datepicker is fine as it is mandatory entry. But ValidUntil DatePicker is not mandatory but the user can still see the current date on it which I want to make it blank.

Is there any way I can use TextBox/TextBlock for UI and onClick/onTouch populate the datePicker? I tried to have a look but could not find any relevant samples.

datePicker is different in both windows phone and tablet apps. My application is an universal for tablets.

Could you suggest what is the best way to make the ValidUntil datepicker nullable? or textBox which populates the datePicker.

Another question is even if i populate the datePicker onClick/onTouch of textBox will it populate as a calender or just a single row with user selecting date/month/year separately?

XAML

```<code><DatePicker/>
</code>```

答:
I was looking for something similar and the answer posted here was very useful.

My XAML ended up being something like the following where the Button Content is bound to the same field that the DatePickerFlyout is so that it will show the selected value:

```<code><Button Content="{Binding Path=SomeDate, Mode=OneWay}">
    <Button.Flyout>
        <DatePickerFlyout Date="{Binding Path=SomeDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    </Button.Flyout>
</Button>
</code>```

Add in some simple styling to the button and a converter for showing the date in the button and another one for changing the DatePicker's DateTimeOffset value to a DateTime and you're done.

Body:
In my windows universal app for tablet, I am working with datepicker to which current date is set automatically. But how do I make it blank or nullable. i have got two date pickers ValidFrom and ValidUntil. ValidFrom datepicker is fine as it is mandatory entry. But ValidUntil DatePicker is not mandatory but the user can still see the current date on it which I want to make it blank.

Is there any way I can use TextBox/TextBlock for UI and onClick/onTouch populate the datePicker? I tried to have a look but could not find any relevant samples.

datePicker is different in both windows phone and tablet apps. My application is an universal for tablets.

Could you suggest what is the best way to make the ValidUntil datepicker nullable? or textBox which populates the datePicker.

Another question is even if i populate the datePicker onClick/onTouch of textBox will it populate as a calender or just a single row with user selecting date/month/year separately?

XAML

<DatePicker/>

Body:
I was looking for something similar and the answer posted here was very useful.

My XAML ended up being something like the following where the Button Content is bound to the same field that the DatePickerFlyout is so that it will show the selected value:

<Button Content="{Binding Path=SomeDate, Mode=OneWay}">
    <Button.Flyout>
        <DatePickerFlyout Date="{Binding Path=SomeDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    </Button.Flyout>
</Button>

Add in some simple styling to the button and a converter for showing the date in the button and another one for changing the DatePicker's DateTimeOffset value to a DateTime and you're done.


问:
What is this mean <aaa> in typescript?
Below is my code

```<code>public static postData(language: string, money: number): Promise<testModel.Item[]> {
    return ........
    });
}
</code>```

What is this code mean and Promise< testModel.Item[] > mean in here?

答:
The Promise<testModel.item[]> is the function return type in this snippet. Eg, it declares that the function postData returns a promise that resolves with an array of testModel.item.

The <> syntax (in this case) is used to supply the parameters of a generic type. You can read about generics in typescript here.

Title: What is this mean <aaa> in typescript?

Body:
Below is my code

public static postData(language: string, money: number): Promise<testModel.Item[]> {
    return ........
    });
}

What is this code mean and Promise< testModel.Item[] > mean in here?


问:
Javascript parsing Times without Date
I need to parse and manipulate Times without Dates in my code. For example i might get the string "15:00" from a timepicker. I want to turn this into a Time object of some kind - I normally work in Python which has distinct Date, Time, and Datetime objects.

However all the solutions i've seen focus on using the Date object. This cannot parse a string like "15:00" since it requires day information. I don't want to add arbitrary Date information to Times - especially since Date appears to make assumptions about things like daylight saving depending on the day and the locale, and there appears to be a risk of it automatically attempting to translate the time into a given locale. Furthermore I want to be able to add times, e.g. "15:00 + 1 hour"

What is the recommended solution to parse and handle "raw" times not associated to dates?

答:
I had to do this recently for a project but didnt really need to include moment.js, the method I used was to manually parse the time like this:

```<code>function parseTime(time) {
    let timeInt = parseInt(time);
    let minutes = time.substring(3,5);

    // you could then add or subtract time here as needed

    if(time > '12:00') {
         return `${timeInt - 12}:${minutes} PM`;
    } else {
         return `${timeInt}:${minutes} AM`;
    }
}
</code>```

Use this as an alternative starter if you don't want to use moment. Note this example uses es6 syntax.

Title: Javascript parsing Times without Date

Body:
I had to do this recently for a project but didnt really need to include moment.js, the method I used was to manually parse the time like this:

function parseTime(time) {
    let timeInt = parseInt(time);
    let minutes = time.substring(3,5);

    // you could then add or subtract time here as needed

    if(time > '12:00') {
         return `${timeInt - 12}:${minutes} PM`;
    } else {
         return `${timeInt}:${minutes} AM`;
    }
}

Use this as an alternative starter if you don't want to use moment. Note this example uses es6 syntax.


问:
Maven - How to compile tests without running them ?
Is there a way in Maven to compile the tests without running them ? I want to use the IDE to run specific tests and not all of them.</p>

答:
you can try to use parameter -DskipTests

References:

Maven Surefire Plugin # skipTests


问:
How to configure Alexa ask-cli with a valid AWS profile?
After playing around with the nice browser GUIs of developer.amazon.com and aws.amazon.com things getting serious and now I want to use ask-cli to initialize Alexa skills and their lambda functions.

When I want to ask init, it tells me, I should select a profile or create a new one. Both jump to the browser and use OAuth to authenticate my ask installation.

```<code>~ ask init
? Please create a new profile or overwrite the existing profile.
 (Use arrow keys)
  ──────────────
❯ Create new profile
  ──────────────
  Profile              Associated AWS Profile
  [default]                 ** NULL **
  [aws_profile]             ** NULL **
</code>```

But the AWS Profile will not associate my AWS Profile.

My LamdaFunction will not load/deploy, if I don't connect the profile with AWS.

```<code>No AWS credential setup for profile: [default].
Lambda clone skipped. CLI lambda functionalities can be enabled
by running `ask init` again to add 'aws_profile' to ASK cli_config
</code>```

How could I connect my ask-cli correctly?

答:
You need to first download and install aws CLI on your local machine. You can download aws CLI from below link.

http://docs.aws.amazon.com/cli/latest/userguide/installing.html

If you are working with your root account user then you have to generate your access ID and secret key else you have to create new IAM user with lambda execute permission.

You can generate root user access ID and secret key from below link.
https://console.aws.amazon.com/iam/home

Then click on Manage Security  credential as shown in below image and after ignoring the warnings you can process and click Access Key ID and secret key link and generate new one and copy them.

Run aws configure command to configure your aws account and it will ask for Access ID and secret key that you generated and will setup your aws account.

aws configure

After aws configure, you can run again ask init command again to configure account.

ask init

Body:
After playing around with the nice browser GUIs of developer.amazon.com and aws.amazon.com things getting serious and now I want to use ask-cli to initialize Alexa skills and their lambda functions.

When I want to ask init, it tells me, I should select a profile or create a new one. Both jump to the browser and use OAuth to authenticate my ask installation.

~ ask init
? Please create a new profile or overwrite the existing profile.
 (Use arrow keys)
  ──────────────
❯ Create new profile
  ──────────────
  Profile              Associated AWS Profile
  [default]                 ** NULL **
  [aws_profile]             ** NULL **

But the AWS Profile will not associate my AWS Profile.

My LamdaFunction will not load/deploy, if I don't connect the profile with AWS.

No AWS credential setup for profile: [default].
Lambda clone skipped. CLI lambda functionalities can be enabled
by running `ask init` again to add 'aws_profile' to ASK cli_config

How could I connect my ask-cli correctly?


问:
Which will be the best way to adapt an web app running in Express to mobile?
I have make a simple web application in express (Node.js) with ejs as a template/view system.

Very simple. For some reasons I need to make that app working on mobile devices just to have some push notifications: chrome notifications works great but some devices (android) have this feature blocked by default also IOS blocks chrome notifications

So the only way is by converting this simple web app into some kind of mobile app. Ionic look's great but you need to adapt your view tags and code..also I don't know if you can combine it with express.

Which will be the best way to adapt an web app running in express to mobile?

答: I was currently solving the same problem for my new problem you can Convert your Web App to a Mobile App with Apache Cordova , specifically using the Ionic framework, you won't change much on Server side(node.js), however few change as to be made on angular js and very little on view to adapt on ionic design view which very similar to bootstrap tags</p>


问:
Implementing isRequestFromAssistant in Node.js on actions-on-google project fulfillment
I am having trouble implementing the isRequestFromAssistant method to verify requests to my fulfillment webhook.  Using Node.js, I instantiate the following variables at the start of my index.js file:

```<code>const App = require('actions-on-google').ApiAiApp;
const app = new App({ request, response });
</code>```

I then use "app" with the .ask and .tell and other methods throughout my functions.

The code I see in the docs for implementing isRequestFromAssistant is:

```<code>const app = new ActionsSdkApp({request, response});
app.isRequestFromAssistant('my-project-id')
  .then(() => {
    app.ask('Hey there, thanks for stopping by!');
  })
  .catch(err => {
    response.status(400).send();
  });
</code>```

If I leave out the first line and use my existing app variable, created with the .ApiAi method instead of the .ActionsSdkApp method, it doesn't work.  If I create a new variable App1 and app1 using the .ActionsSdkApp method and change the above code to be app1.isRequestFromAssistant, it also doesn't work.  I have tried other variations with no luck.

When I say it doesn't work, I mean I receive a 500 Internal Server Error when I call it.  I am hosting it with NGROK currently.  I am still a beginner with Node.js, although I have managed to get the other 700 lines of code working just fine, learning mostly from Google searches and reading these forums.

答:
Set the secure (randomly generated) auth header & key values in the dialogflow Fulfillment page, then in nodejs:

```<code>if (app.isRequestFromDialogflow("replace_with_key", "replace_with_value")) {
  console.log("Request came from dialogflow!");
  // rest of bot
} else {
  console.log("Request did not come from dialogflow!");
  response.status(400).send();
}
</code>```

Also see: https://developers.google.com/actions/reference/nodejs/DialogflowApp#isRequestFromDialogflow

Body:
I am having trouble implementing the isRequestFromAssistant method to verify requests to my fulfillment webhook.  Using Node.js, I instantiate the following variables at the start of my index.js file:

const App = require('actions-on-google').ApiAiApp;
const app = new App({ request, response });

I then use "app" with the .ask and .tell and other methods throughout my functions.

The code I see in the docs for implementing isRequestFromAssistant is:

const app = new ActionsSdkApp({request, response});
app.isRequestFromAssistant('my-project-id')
  .then(() => {
    app.ask('Hey there, thanks for stopping by!');
  })
  .catch(err => {
    response.status(400).send();
  });

If I leave out the first line and use my existing app variable, created with the .ApiAi method instead of the .ActionsSdkApp method, it doesn't work.  If I create a new variable App1 and app1 using the .ActionsSdkApp method and change the above code to be app1.isRequestFromAssistant, it also doesn't work.  I have tried other variations with no luck.

When I say it doesn't work, I mean I receive a 500 Internal Server Error when I call it.  I am hosting it with NGROK currently.  I am still a beginner with Node.js, although I have managed to get the other 700 lines of code working just fine, learning mostly from Google searches and reading these forums.

Body:
Set the secure (randomly generated) auth header & key values in the dialogflow Fulfillment page, then in nodejs:

if (app.isRequestFromDialogflow("replace_with_key", "replace_with_value")) {
  console.log("Request came from dialogflow!");
  // rest of bot
} else {
  console.log("Request did not come from dialogflow!");
  response.status(400).send();
}

Also see: https://developers.google.com/actions/reference/nodejs/DialogflowApp#isRequestFromDialogflow


问:
Why is there an extra space in between a variable and punctuation in a string? Python
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

```<code>def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")
</code>```

This is the output it gives.

```<code>Right... So your name is Raven .
</code>```

How do I get rid of the space in between the name and the punctuation?

答:
Use the string variable substitution with %s as in:

```<code>def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is %s." % name)
</code>```

or use the .format() function that is a built-in method for str in:

```<code>def nameConfirmation():
    name = chooseName()
    output = "Right... So your name is {}.".format(name)
    print(output)
</code>```

or you could use the shorter f"" format as in:

```<code>def nameConfirmation():
    name = chooseName()
    print(f"Right... So your name is {name}.")
</code>```

For more on string manipulation and formatting in Python3, Check the following:

https://www.digitalocean.com/community/tutorials/an-introduction-to-string-functions-in-python-3
https://www.digitalocean.com/community/tutorials/an-introduction-to-working-with-strings-in-python-3
https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3

Body:
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")

This is the output it gives.

Right... So your name is Raven .

How do I get rid of the space in between the name and the punctuation?

Body:
Use the string variable substitution with %s as in:

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is %s." % name)

or use the .format() function that is a built-in method for str in:

def nameConfirmation():
    name = chooseName()
    output = "Right... So your name is {}.".format(name)
    print(output)

or you could use the shorter f"" format as in:

def nameConfirmation():
    name = chooseName()
    print(f"Right... So your name is {name}.")

For more on string manipulation and formatting in Python3, Check the following:

https://www.digitalocean.com/community/tutorials/an-introduction-to-string-functions-in-python-3
https://www.digitalocean.com/community/tutorials/an-introduction-to-working-with-strings-in-python-3
https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3

ContentLicense: CC BY-SA 4.0


问:
How to get very first word before and after 'text'
I am after the very first word before v and after 'v'.

```<code>df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})
</code>```

I have a dataframe that looks like:

```<code>cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce
</code>```

I want it to look like:

```<code>cans v macroni
chocolate v chocolate
Chocolate v sauce
</code>```

How can this be achieved in pandas?  The common element is 'v'.

答:
You can pass a regular expression to the string operations on the text columns.

```<code>df.text.str.extract(r'(\w+ v \w+)', expand=True)

# returns:
                     0
0       choc v macroni
1  sundaes v chocolate
2    Chocolate v sauce
</code>```

Body:
I am after the very first word before v and after 'v'.

df = pd.DataFrame({'text': ["cans choc v macroni ice",
                            "chocolate sundaes v chocolate ice cream",
                            "Chocolate v sauce"]})

I have a dataframe that looks like:

cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce

I want it to look like:

cans v macroni
chocolate v chocolate
Chocolate v sauce

How can this be achieved in pandas?  The common element is 'v'.

Body:
You can pass a regular expression to the string operations on the text columns.

df.text.str.extract(r'(\w+ v \w+)', expand=True)

# returns:
                     0
0       choc v macroni
1  sundaes v chocolate
2    Chocolate v sauce


答:
That would be something like this</p>

```<code>$array = array(
    'query' => array(
        array('Date' => '11-01-2017')
        )
    );

echo '```';
print_r(json_encode($array, JSON_PRETTY_PRINT));
</code>```

<p>Result</p>

```<code>{
    "query": [
        {
            "Date": "11-01-2017"
        }
    ]
}
</code>```

Title: PHP json_encode - create JSON array

Body:
I've used the json_encode function in the past to create simply JSON objects like this:

$payload =  array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);

which creates this:

{"user":"john smith","password":"abc12345","group":"sales"}

I now need to generate a JSON array like this:

{
  "query": [
    {
      "Date": "11/01/2017...12/31/2017"
    }
  ]
}

but I can't find the correct syntax.

Body:
That would be something like this

$array = array(
    'query' => array(
        array('Date' => '11-01-2017')
        )
    );

echo '<pre>';
print_r(json_encode($array, JSON_PRETTY_PRINT));

Result

{
    "query": [
        {
            "Date": "11-01-2017"
        }
    ]
}


答:
```<code>$payload = json_encode($payload, JSON_PRETTY_PRINT);
</code>```

reference: http://php.net/manual/en/function.json-encode.php

Title: PHP json_encode - create JSON array

Body:
$payload = json_encode($payload, JSON_PRETTY_PRINT);

reference: http://php.net/manual/en/function.json-encode.php


问:
Cannot create property 'guid' on string 'loading'
I have this code in JS. The purpose of this is that, when the #savecard-button is clicked, it will go through submitting, but will delay it for a certain amount of time and then go through the process and so on.

```<code> $('#savecard-button').on('click', function(){
    $('#savecard-button').submit('loading').delay(1000).queue(function () {
        if ($('#form-addcard').find('.has-error').length) {
          return false;
        }else{
            $(this).attr('disabled',true);
            $(this).html('<i class=".$code."></i> Saving Changes');
            $(this).button('reset');
        }
});
</code>```

});

but when trying to submit, I get this error on the console:

```<code>Uncaught TypeError: Cannot create property 'guid' on string 'loading'
</code>```

Is the parameter "loading" depreciated? Because months ago, its still working. If so, can you please advise what I have to replace here? Thanks

答:
I was able to get my button's loading state work properly after a few experiments on the code. I got rid of the "loading" parameter as I think the submit function doesn't have it.</p>

```<code>    $('#savecard-button').on('click', function() {
        var $this = $(this);
        //$this.attr('disabled',true);
        $this.html('<i class="fa fa-spinner fa-spin"></i> Saving Changes');

        setTimeout(function() {
            $this.attr('disabled',true);
           $this.button('reset');
       }, 0);
    });
</code>```

Body:
I have this code in JS. The purpose of this is that, when the #savecard-button is clicked, it will go through submitting, but will delay it for a certain amount of time and then go through the process and so on.

 $('#savecard-button').on('click', function(){
    $('#savecard-button').submit('loading').delay(1000).queue(function () {
        if ($('#form-addcard').find('.has-error').length) {
          return false;
        }else{
            $(this).attr('disabled',true);
            $(this).html(' Saving Changes');
            $(this).button('reset');
        }
});

});

but when trying to submit, I get this error on the console:

Uncaught TypeError: Cannot create property 'guid' on string 'loading'

Is the parameter "loading" depreciated? Because months ago, its still working. If so, can you please advise what I have to replace here? Thanks

Body:
I was able to get my button's loading state work properly after a few experiments on the code. I got rid of the "loading" parameter as I think the submit function doesn't have it.

    $('#savecard-button').on('click', function() {
        var $this = $(this);
        //$this.attr('disabled',true);
        $this.html('<i class="fa fa-spinner fa-spin"></i> Saving Changes');

        setTimeout(function() {
            $this.attr('disabled',true);
           $this.button('reset');
       }, 0);
    });


问:
How to generate HMAC-SHA256 in .Net Core?
I am using this page to generate some test HMAC-SHA256 hashes for some texts:

https://www.liavaag.org/English/SHA-Generator/HMAC/

However, when I try to use the approach in this MSDN guide in my .Net Core project, I do not get the same results. Could some one explain to me how to get identical results to those I get from the previous web page in my C# code?

Here is my code:

```<code>// My own GetHash method usage:
var hashed = PasswordHelper.GetHash("Test", Encoding.UTF8.GetBytes("123"));

public static string GetHash(string password, byte[] salt)
{
    // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
    string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: password,
        salt: salt,
        prf: KeyDerivationPrf.HMACSHA256,
        iterationCount: 10000,
        numBytesRequested: 256 / 8));
    return hashed;
}
</code>```

答:
Using the following approach:

```<code>public static String GetHash(String text, String key)
{
    // change according to your needs, an UTF8Encoding
    // could be more suitable in certain situations
    ASCIIEncoding encoding = new ASCIIEncoding();

    Byte[] textBytes = encoding.GetBytes(text);
    Byte[] keyBytes = encoding.GetBytes(key);

    Byte[] hashBytes;

    using (HMACSHA256 hash = new HMACSHA256(keyBytes))
        hashBytes = hash.ComputeHash(textBytes);

    return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
</code>```

you will get the same result as the site you provided:

```<code>Console.WriteLine(GetHash("qwerty","123456"));
// 3364ad93c083dc76d7976b875912442615cc6f7e3ce727b2316173800ca32b3a
</code>```

Proof:

Actually, the code you are using, which is based on this tutorial and on KeyDerivation.Pbkdf2, is producing different results because it uses a much more complex parametrization and another encoding. But despite the results being different, you should REALLY use the approach provided by the example, and stick on the UTF8 encoding.

Body:
I am using this page to generate some test HMAC-SHA256 hashes for some texts:

https://www.liavaag.org/English/SHA-Generator/HMAC/

However, when I try to use the approach in this MSDN guide in my .Net Core project, I do not get the same results. Could some one explain to me how to get identical results to those I get from the previous web page in my C# code?

Here is my code:

// My own GetHash method usage:
var hashed = PasswordHelper.GetHash("Test", Encoding.UTF8.GetBytes("123"));

public static string GetHash(string password, byte[] salt)
{
    // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
    string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: password,
        salt: salt,
        prf: KeyDerivationPrf.HMACSHA256,
        iterationCount: 10000,
        numBytesRequested: 256 / 8));
    return hashed;
}

Body:
Using the following approach:

public static String GetHash(String text, String key)
{
    // change according to your needs, an UTF8Encoding
    // could be more suitable in certain situations
    ASCIIEncoding encoding = new ASCIIEncoding();

    Byte[] textBytes = encoding.GetBytes(text);
    Byte[] keyBytes = encoding.GetBytes(key);

    Byte[] hashBytes;

    using (HMACSHA256 hash = new HMACSHA256(keyBytes))
        hashBytes = hash.ComputeHash(textBytes);

    return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}

you will get the same result as the site you provided:

Console.WriteLine(GetHash("qwerty","123456"));
// 3364ad93c083dc76d7976b875912442615cc6f7e3ce727b2316173800ca32b3a

Proof:

Actually, the code you are using, which is based on this tutorial and on KeyDerivation.Pbkdf2, is producing different results because it uses a much more complex parametrization and another encoding. But despite the results being different, you should REALLY use the approach provided by the example, and stick on the UTF8 encoding.


问:
how do I access the main class's stage? + Can I pass functions as arguments like this?
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

```<code>
    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}
</code>```

And for the draggable.as:

```<code>
package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}
</code>```

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

答:
If TestAPP is your document class. You can access to the stage thru the stage property (like your are doing in your example).
If TestAPP is not the document class, you should listen first to the ADDED_TO_STAGE event and then access to the stage property.
There is no need to add _mainStage property because you already have the stage property.
In order to move objects around, you need to use the ENTER_FRAME event.</p>

ContentLicense: CC BY-SA 2.5

Body:
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}

And for the draggable.as:

package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!


问:
Apache POI: Open Template, write, Save as. crashes and creates corrupt file
I have been writing a program to write names on a roster and have written most of the methods for finding and sorting.
The goal of this method is to open an existing file, write in a cell, and save as a different file.
I think the problem may be the  template file because it consists of 2 sheets. one sheet is to collect all the names and the second sheet has an image with text boxes linked to the first page to print onto the text box

```<code>public static void FindTemplate(String Session) throws FileNotFoundException, IOException
{
    if(Session.toLowerCase().contains("Level 1".toLowerCase()))
         // generic roster as an else
    {

        FileInputStream In = new FileInputStream("Directory\\Templates\\A Template.xls");
        HSSFWorkbook wb = new HSSFWorkbook(In);
        HSSFSheet sheet = wb.getSheetAt(0);
        Cell cell = null;
        cell = sheet.getRow(0).getCell(0);

        cell.setCellValue("Found it");//just as a test for now
        In.close();

        wb.write(new FileOutputStream("WA1.xls"));
        wb.close();

    }
}
</code>```

When i run it i get a large error that i don't understand. The error is at wb.write(new FileOutputStream("WA1.xls")); I have saved files like this before in my other methods. Also a new file is created but it is corrupt.

```<code>Error:
 WAException in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/bidimap/TreeBidiMap
at org.apache.poi.hpsf.Section.<init>(Section.java:178)
at org.apache.poi.hpsf.MutableSection.<init>(MutableSection.java:41)
at org.apache.poi.hpsf.PropertySet.init(PropertySet.java:494)
at org.apache.poi.hpsf.PropertySet.<init>(PropertySet.java:196)
at org.apache.poi.hpsf.MutablePropertySet.<init>(MutablePropertySet.java:44)
at org.apache.poi.hpsf.SpecialPropertySet.<init>(SpecialPropertySet.java:47)
at org.apache.poi.hpsf.DocumentSummaryInformation.<init>(DocumentSummaryInformation.java:99)
at org.apache.poi.hpsf.PropertySetFactory.create(PropertySetFactory.java:116)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:236)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:197)
at org.apache.poi.POIDocument.readPropertySet(POIDocument.java:175)
at org.apache.poi.POIDocument.readProperties(POIDocument.java:158)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.updateEncryptionInfo(HSSFWorkbook.java:2295)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.getBytes(HSSFWorkbook.java:1506)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1428)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1414)
at rosterWrite.FindTemplate(rosterWrite.java:79)
at rosterWrite.main(rosterWrite.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.bidimap.TreeBidiMap
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 18 more
</code>```

答: The error message is Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.bidimap.TreeBidiMap, that means your project is lack of the TreeBidiMap class of the Apache commons-collections library. If you using maven, just add commons-collection library to your pom.xml as this page shows. If not, you need to download the library from official site and put it to your project.

Body:
I have been writing a program to write names on a roster and have written most of the methods for finding and sorting.
The goal of this method is to open an existing file, write in a cell, and save as a different file.
I think the problem may be the  template file because it consists of 2 sheets. one sheet is to collect all the names and the second sheet has an image with text boxes linked to the first page to print onto the text box

public static void FindTemplate(String Session) throws FileNotFoundException, IOException
{
    if(Session.toLowerCase().contains("Level 1".toLowerCase()))
         // generic roster as an else
    {

        FileInputStream In = new FileInputStream("Directory\\Templates\\A Template.xls");
        HSSFWorkbook wb = new HSSFWorkbook(In);
        HSSFSheet sheet = wb.getSheetAt(0);
        Cell cell = null;
        cell = sheet.getRow(0).getCell(0);

        cell.setCellValue("Found it");//just as a test for now
        In.close();

        wb.write(new FileOutputStream("WA1.xls"));
        wb.close();

    }
}

When i run it i get a large error that i don't understand. The error is at wb.write(new FileOutputStream("WA1.xls")); I have saved files like this before in my other methods. Also a new file is created but it is corrupt.

Error:
 WAException in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/bidimap/TreeBidiMap
at org.apache.poi.hpsf.Section.<init>(Section.java:178)
at org.apache.poi.hpsf.MutableSection.<init>(MutableSection.java:41)
at org.apache.poi.hpsf.PropertySet.init(PropertySet.java:494)
at org.apache.poi.hpsf.PropertySet.<init>(PropertySet.java:196)
at org.apache.poi.hpsf.MutablePropertySet.<init>(MutablePropertySet.java:44)
at org.apache.poi.hpsf.SpecialPropertySet.<init>(SpecialPropertySet.java:47)
at org.apache.poi.hpsf.DocumentSummaryInformation.<init>(DocumentSummaryInformation.java:99)
at org.apache.poi.hpsf.PropertySetFactory.create(PropertySetFactory.java:116)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:236)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:197)
at org.apache.poi.POIDocument.readPropertySet(POIDocument.java:175)
at org.apache.poi.POIDocument.readProperties(POIDocument.java:158)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.updateEncryptionInfo(HSSFWorkbook.java:2295)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.getBytes(HSSFWorkbook.java:1506)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1428)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1414)
at rosterWrite.FindTemplate(rosterWrite.java:79)
at rosterWrite.main(rosterWrite.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.bidimap.TreeBidiMap
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 18 more


问:
How to convert inline assembly __asm to byte
well i want to create a detour to my custom injected function so a code like that works

```<code>void *DetourCreate(BYTE *src, const BYTE *dst)
{
    int len = 5;
    BYTE* jmp = (BYTE*)malloc(len + 5);
    DWORD dwBack;
    VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &dwBack);
    memcpy(jmp, src, len);
    jmp += len;
    jmp[0] = 0xE9;
    *(DWORD*)(jmp + 1) = (DWORD)(src + len - jmp) - 5;
    src[0] = 0xE9;
    *(DWORD*)(src + 1) = (DWORD)(dst - src) - 5;
    VirtualProtect(src, len, dwBack, &dwBack);
    return(jmp - len);
}
</code>```

but i find it irritating to use opcodes so is there a way to use __asm instead ? like this pseudo code for instance

```<code>void DetourCreate(byte *src, const byte *dst)
{
    DWORD dwBack;
    VirtualProtect(src, sizeof(*dst), PAGE_EXECUTE_READWRITE, &dwBack);
    *src = __asm{
        call dst
    };
    VirtualProtect(src, sizeof(*dst), dwBack, &dwBack);
}
</code>```

答:
To convert inline assembly to the corresponding bytes, you can write your assembly inside of a __declspec(naked) function and use WriteProcessMemory to write data into the external process, using the inline assembly function as the source.

Here is an example that Writes from the assembly into a local buffer:

```<code>__declspec(naked) int assembly()
{
    __asm
    {
        push eax;   // \x50
        mov eax, 1; // \xB8 \x01\x00\x00\x00
        pop eax;    // \x58
    }
}

int main()
{
    unsigned char buffer[7] = { 0 };

    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, GetCurrentProcessId());
    WriteProcessMemory(hProc, &buffer, &assembly, 7, NULL);

    for (auto c : buffer)
    {
        printf("0x%hhX ", c);
    }

    std::getchar();

    return 0;
}
</code>```

We use declspec to make sure no function prologue/epilogue gets in our way.
The output is just for this proof of concept and will read:
0x50 0xB8 0x1 0x0 0x0 0x0 0x58

Should be simple enough to Write to a target process using this technique.

Using the Capstone disassembler is the ultimate solution if you find yourself doing this often, it's very easy to use.

Body:
well i want to create a detour to my custom injected function so a code like that works

void *DetourCreate(BYTE *src, const BYTE *dst)
{
    int len = 5;
    BYTE* jmp = (BYTE*)malloc(len + 5);
    DWORD dwBack;
    VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &dwBack);
    memcpy(jmp, src, len);
    jmp += len;
    jmp[0] = 0xE9;
    *(DWORD*)(jmp + 1) = (DWORD)(src + len - jmp) - 5;
    src[0] = 0xE9;
    *(DWORD*)(src + 1) = (DWORD)(dst - src) - 5;
    VirtualProtect(src, len, dwBack, &dwBack);
    return(jmp - len);
}

but i find it irritating to use opcodes so is there a way to use __asm instead ? like this pseudo code for instance

void DetourCreate(byte *src, const byte *dst)
{
    DWORD dwBack;
    VirtualProtect(src, sizeof(*dst), PAGE_EXECUTE_READWRITE, &dwBack);
    *src = __asm{
        call dst
    };
    VirtualProtect(src, sizeof(*dst), dwBack, &dwBack);
}

Body:
To convert inline assembly to the corresponding bytes, you can write your assembly inside of a __declspec(naked) function and use WriteProcessMemory to write data into the external process, using the inline assembly function as the source.

Here is an example that Writes from the assembly into a local buffer:

__declspec(naked) int assembly()
{
    __asm
    {
        push eax;   // \x50
        mov eax, 1; // \xB8 \x01\x00\x00\x00
        pop eax;    // \x58
    }
}

int main()
{
    unsigned char buffer[7] = { 0 };

    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, GetCurrentProcessId());
    WriteProcessMemory(hProc, &buffer, &assembly, 7, NULL);

    for (auto c : buffer)
    {
        printf("0x%hhX ", c);
    }

    std::getchar();

    return 0;
}

We use declspec to make sure no function prologue/epilogue gets in our way.
The output is just for this proof of concept and will read:
0x50 0xB8 0x1 0x0 0x0 0x0 0x58

Should be simple enough to Write to a target process using this technique.

Using the Capstone disassembler is the ultimate solution if you find yourself doing this often, it's very easy to use.


问:
Possible to include an Android App Widget inside an existing app (AppWidgetHost), without the Select Widgets list?
We're trying to host a 3rd party widget inside our own app, and we're trying to figure out how it can be added upon our app's installation, without having the user need to select it from the Select Widgets list. The reason being, our client needs their users to choose this specific widget (and we're trying to keep the code separate so they can update this specific widget, inside our app, on their own), and it's not a great UX for a user to be able to choose a different one by accident.  Is there a way to filter the Select Widget list even?  Or just have it show the one we need it to show?  And since we have access to this 3rd party widget's source, would that help?

We can tell so far that the only way to add a widget to a widget host is to allocate an id, run    ACTION.APPWIDGET_PICK     and user can choose from there..  But we really need to find a way for either that list to be filtered somehow, or this third party widget be installed when our app (host) is installed too.

Any ideas?

Thanks!

答:
This is how you embed a widget in your app without the select widgets list. The user will just see a confirmation dialog.</p>

```<code>public boolean createWidget(View view, String packageName, String className) {
    // Get the list of installed widgets
    AppWidgetProviderInfo newAppWidgetProviderInfo = null;
    List<AppWidgetProviderInfo> appWidgetInfos;
    appWidgetInfos = mAppWidgetManager.getInstalledProviders();
    boolean widgetIsFound = false;
    for(int j = 0; j < appWidgetInfos.size(); j++)
    {
        if (appWidgetInfos.get(j).provider.getPackageName().equals(packageName) && appWidgetInfos.get(j).provider.getClassName().equals(className))
        {
            // Get the full info of the required widget
            newAppWidgetProviderInfo = appWidgetInfos.get(j);
            widgetIsFound = true;
            break;
        }
    }

    if (!widgetIsFound) {
        return false;
    } else {
        // Create Widget
        int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
        AppWidgetHostView hostView = mAppWidgetHost.createView(getApplicationContext(), appWidgetId, newAppWidgetProviderInfo);
        hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

        // Add it to your layout
        LinearLayout widgetLayout = view.findViewById(R.id.widget_view);
        widgetLayout.addView(hostView);

        // And bind widget IDs to make them actually work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            boolean allowed = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, newAppWidgetProviderInfo.provider);

            if (!allowed) {
                // Request permission - https://stackoverflow.com/a/44351320/1816603
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, newAppWidgetProviderInfo.provider);
                final int REQUEST_BIND_WIDGET = 1987;
                startActivityForResult(intent, REQUEST_BIND_WIDGET);
            }
        }

        return true;
    }
}
</code>```

Body:
This is how you embed a widget in your app without the select widgets list. The user will just see a confirmation dialog.

public boolean createWidget(View view, String packageName, String className) {
    // Get the list of installed widgets
    AppWidgetProviderInfo newAppWidgetProviderInfo = null;
    List<AppWidgetProviderInfo> appWidgetInfos;
    appWidgetInfos = mAppWidgetManager.getInstalledProviders();
    boolean widgetIsFound = false;
    for(int j = 0; j < appWidgetInfos.size(); j++)
    {
        if (appWidgetInfos.get(j).provider.getPackageName().equals(packageName) && appWidgetInfos.get(j).provider.getClassName().equals(className))
        {
            // Get the full info of the required widget
            newAppWidgetProviderInfo = appWidgetInfos.get(j);
            widgetIsFound = true;
            break;
        }
    }

    if (!widgetIsFound) {
        return false;
    } else {
        // Create Widget
        int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
        AppWidgetHostView hostView = mAppWidgetHost.createView(getApplicationContext(), appWidgetId, newAppWidgetProviderInfo);
        hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

        // Add it to your layout
        LinearLayout widgetLayout = view.findViewById(R.id.widget_view);
        widgetLayout.addView(hostView);

        // And bind widget IDs to make them actually work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            boolean allowed = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, newAppWidgetProviderInfo.provider);

            if (!allowed) {
                // Request permission - https://stackoverflow.com/a/44351320/1816603
                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, newAppWidgetProviderInfo.provider);
                final int REQUEST_BIND_WIDGET = 1987;
                startActivityForResult(intent, REQUEST_BIND_WIDGET);
            }
        }

        return true;
    }
}


问:
Warning encountered regarding react-native component keys
I'm fairly new to react-native. I encountered a problem with dynamic rendering of components.

I'm using a swiper component. When there is only one card to be rendered i get a warning:

"Warning: Encountered two children with the same key, 0. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."

Everything works fine when there is more than one card to be rendered but when there is only one card to be rendered I get the warning.

I read this : Understanding unique keys for array children in React.js

But its not really making sense to me :(

I also posted my question here :

https://github.com/alexbrillant/react-native-deck-swiper/issues/90

Any help would be appreciated!

Thanks

Edit: added code.

Screenshots of my code is in the links above but I think the most relevant code would be :

```<code>cards.push(<MyPetCard
petId={responseJson[x].petId}
petName={responseJson[x].name}
breed={responseJson[x].breed}
gender={responseJson[x].gender}
category={responseJson[x].category}
description={responseJson[x].description}
birthday={responseJson[x].birthday}
imageInfo={image}
petAge={responseJson[x].age}
distance={petDistance}
significantValue={responseJson[x].significant}
/>);
</code>```

render method looks like this

答:
FYI, My problem was specifically with react-native-deck-swiper
I was encountering a warning if the cards array passed to the swiper contained only one element.

Seems the swiper component was preparing the next card to be rendered but since the cards only had one item, the component keys were duplicated.

I also posted the answer here:

https://github.com/alexbrillant/react-native-deck-swiper/issues/90

hope it helps!

Body:
I'm fairly new to react-native. I encountered a problem with dynamic rendering of components.

I'm using a swiper component. When there is only one card to be rendered i get a warning:

"Warning: Encountered two children with the same key, 0. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."

Everything works fine when there is more than one card to be rendered but when there is only one card to be rendered I get the warning.

I read this : Understanding unique keys for array children in React.js

But its not really making sense to me :(

I also posted my question here :

https://github.com/alexbrillant/react-native-deck-swiper/issues/90

Any help would be appreciated!

Thanks

Edit: added code.

Screenshots of my code is in the links above but I think the most relevant code would be :

cards.push(<MyPetCard
petId={responseJson[x].petId}
petName={responseJson[x].name}
breed={responseJson[x].breed}
gender={responseJson[x].gender}
category={responseJson[x].category}
description={responseJson[x].description}
birthday={responseJson[x].birthday}
imageInfo={image}
petAge={responseJson[x].age}
distance={petDistance}
significantValue={responseJson[x].significant}
/>);

render method looks like this