问:
Unity 2D player movement
I had my unity movement working on my computer, however when i try to play on my android it is not moving for me at all. I am sure it is probably a small error i am overlooking but i would be very appreciative of any help! I do not get any errors when i try yo run my code if that is of any assistance! I will supply the code below:</p>

```<code>using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class PlayerControler : MonoBehaviour {

    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    //public Text winText;          //Store a reference to the UI Text component which will display the 'You win' message.
    private double count;               //Integer to store the number of pickups collected so far.

    //Player movement controls
    private Vector3 touchPosition;  //where your finger touches screen
    private Vector3 direction;      //direction you drag sprite
    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    public float speed = 10f;               //Floating point variable to store the player's movement speed.

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        //winText.text = " "; //error here??

        //Call our SetCountText function which will update the text with the current value for count.
        //SetCountText ();
    }

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            rb2d.velocity = new Vector2(direction.x , direction.y) * speed;

            if(touch.phase == TouchPhase.Ended)
            {
                rb2d.velocity = Vector2.zero;
            }
        }
    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            //SetCountText ();
        }

    }
</code>```

答:
Here is my 2D Player Movement Controller.

Code(Character Controller) -

```<code>using UnityEngine;
using UnityEngine.Events;

public class CharacterController2D : MonoBehaviour
{
    [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    [SerializeField] private LayerMask m_WhatIsGround;                          // A mask determining what is ground to the character
    [SerializeField] private Transform m_GroundCheck;                           // A position marking where to check if the player is grounded.
    [SerializeField] private Transform m_CeilingCheck;                          // A position marking where to check for ceilings
    [SerializeField] private Collider2D m_CrouchDisableCollider;                // A collider that will be disabled when crouching

    const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    private bool m_Grounded;            // Whether or not the player is grounded.
    const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    private Rigidbody2D m_Rigidbody2D;
    private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    private Vector3 m_Velocity = Vector3.zero;

    [Header("Events")]
    [Space]

    public UnityEvent OnLandEvent;

    [System.Serializable]
    public class BoolEvent : UnityEvent<bool> { }

    public BoolEvent OnCrouchEvent;
    private bool m_wasCrouching = false;

    private void Awake()
    {
        m_Rigidbody2D = GetComponent<Rigidbody2D>();

        if (OnLandEvent == null)
            OnLandEvent = new UnityEvent();

        if (OnCrouchEvent == null)
            OnCrouchEvent = new BoolEvent();
    }

    private void FixedUpdate()
    {
        bool wasGrounded = m_Grounded;
        m_Grounded = false;

        // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
        // This can be done using layers instead but Sample Assets will not overwrite your project settings.
        Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
            {
                m_Grounded = true;
                if (!wasGrounded)
                    OnLandEvent.Invoke();
            }
        }
    }

    public void Move(float move, bool crouch, bool jump)
    {
        // If crouching, check to see if the character can stand up
        if (!crouch)
        {
            // If the character has a ceiling preventing them from standing up, keep them crouching
            if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
            {
                crouch = true;
            }
        }

        //only control the player if grounded or airControl is turned on
        if (m_Grounded || m_AirControl)
        {

            // If crouching
            if (crouch)
            {
                if (!m_wasCrouching)
                {
                    m_wasCrouching = true;
                    OnCrouchEvent.Invoke(true);
                }

                // Reduce the speed by the crouchSpeed multiplier
                move *= m_CrouchSpeed;

                // Disable one of the colliders when crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = false;
            }
            else
            {
                // Enable the collider when not crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = true;

                if (m_wasCrouching)
                {
                    m_wasCrouching = false;
                    OnCrouchEvent.Invoke(false);
                }
            }

            // Move the character by finding the target velocity
            Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
            // And then smoothing it out and applying it to the character
            m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);

            // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
            // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
        }
        // If the player should jump...
        if (m_Grounded && jump)
        {
            // Add a vertical force to the player.
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }
    }

    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}
</code>```

And here is the actual Character Movement Code -

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController2D controller;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;

    private void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if(Input.GetButtonDown("Jump"))
        {
            jump = true;
        }
    }

    private void FixedUpdate()
    {
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
        jump = false;
    }
}
</code>```

Title: Unity 2D player movement

Body:
I had my unity movement working on my computer, however when i try to play on my android it is not moving for me at all. I am sure it is probably a small error i am overlooking but i would be very appreciative of any help! I do not get any errors when i try yo run my code if that is of any assistance! I will supply the code below:

using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class PlayerControler : MonoBehaviour {

    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    //public Text winText;          //Store a reference to the UI Text component which will display the 'You win' message.
    private double count;               //Integer to store the number of pickups collected so far.

    //Player movement controls
    private Vector3 touchPosition;  //where your finger touches screen
    private Vector3 direction;      //direction you drag sprite
    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    public float speed = 10f;               //Floating point variable to store the player's movement speed.

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        //winText.text = " "; //error here??

        //Call our SetCountText function which will update the text with the current value for count.
        //SetCountText ();
    }

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            rb2d.velocity = new Vector2(direction.x , direction.y) * speed;

            if(touch.phase == TouchPhase.Ended)
            {
                rb2d.velocity = Vector2.zero;
            }
        }
    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            //SetCountText ();
        }

    }

Body:
Here is my 2D Player Movement Controller.

Code(Character Controller) -

using UnityEngine;
using UnityEngine.Events;

public class CharacterController2D : MonoBehaviour
{
    [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    [SerializeField] private LayerMask m_WhatIsGround;                          // A mask determining what is ground to the character
    [SerializeField] private Transform m_GroundCheck;                           // A position marking where to check if the player is grounded.
    [SerializeField] private Transform m_CeilingCheck;                          // A position marking where to check for ceilings
    [SerializeField] private Collider2D m_CrouchDisableCollider;                // A collider that will be disabled when crouching

    const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    private bool m_Grounded;            // Whether or not the player is grounded.
    const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    private Rigidbody2D m_Rigidbody2D;
    private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    private Vector3 m_Velocity = Vector3.zero;

    [Header("Events")]
    [Space]

    public UnityEvent OnLandEvent;

    [System.Serializable]
    public class BoolEvent : UnityEvent<bool> { }

    public BoolEvent OnCrouchEvent;
    private bool m_wasCrouching = false;

    private void Awake()
    {
        m_Rigidbody2D = GetComponent<Rigidbody2D>();

        if (OnLandEvent == null)
            OnLandEvent = new UnityEvent();

        if (OnCrouchEvent == null)
            OnCrouchEvent = new BoolEvent();
    }

    private void FixedUpdate()
    {
        bool wasGrounded = m_Grounded;
        m_Grounded = false;

        // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
        // This can be done using layers instead but Sample Assets will not overwrite your project settings.
        Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
            {
                m_Grounded = true;
                if (!wasGrounded)
                    OnLandEvent.Invoke();
            }
        }
    }

    public void Move(float move, bool crouch, bool jump)
    {
        // If crouching, check to see if the character can stand up
        if (!crouch)
        {
            // If the character has a ceiling preventing them from standing up, keep them crouching
            if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
            {
                crouch = true;
            }
        }

        //only control the player if grounded or airControl is turned on
        if (m_Grounded || m_AirControl)
        {

            // If crouching
            if (crouch)
            {
                if (!m_wasCrouching)
                {
                    m_wasCrouching = true;
                    OnCrouchEvent.Invoke(true);
                }

                // Reduce the speed by the crouchSpeed multiplier
                move *= m_CrouchSpeed;

                // Disable one of the colliders when crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = false;
            }
            else
            {
                // Enable the collider when not crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = true;

                if (m_wasCrouching)
                {
                    m_wasCrouching = false;
                    OnCrouchEvent.Invoke(false);
                }
            }

            // Move the character by finding the target velocity
            Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
            // And then smoothing it out and applying it to the character
            m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);

            // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
            // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
        }
        // If the player should jump...
        if (m_Grounded && jump)
        {
            // Add a vertical force to the player.
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }
    }

    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

And here is the actual Character Movement Code -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController2D controller;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;

    private void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if(Input.GetButtonDown("Jump"))
        {
            jump = true;
        }
    }

    private void FixedUpdate()
    {
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
        jump = false;
    }
}


来源: stackexchange

问:
Can We Shut Down a Azure HDInsight Cluster When Not In Use to Avoid Charge
I created a hadoop cluster in Azure HDInsight, however it does not seem to be any option for me to shut down the cluster when not in use, it has incurred charges over the past few days. Anyone knows if there is an option for doing so? It sounds rather silly that users have to continuously pay for the cluster when in effect most of the jobs run on a cluster are periodic.</p>

答:
Unfortunately, there is no option to stop an HDInsight cluster.

Note:  It is recommended to delete the cluster after running your job to cut down the cost.

I would suggest you to vote up an idea submitted by another Azure customer.

https://feedback.azure.com/forums/217335-hdinsight/suggestions/7104546-add-a-feature-to-shut-down-an-hd-insight-cluster

All of the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Azure.

Reference: Azure HDinsight - Pause/shut down clusters

ContentLicense: CC BY-SA 4.0


问:
how to set a top-down position in a graph networkx
This is my extended work from here.
I would like to set the last element 'm' in the unique_liss  appears at the top position of the rest nodes like this.
However, most of the image generated would be like this:

this is my codes:

```<code>Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
for node in edgesList:
    print('node-', node)
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A
import numpy as np
seed = 31
pos = nx.spring_layout(G)
plt.figure(figsize=(15,8))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500,
        seed=seed, node_color = 'skyblue')
</code>```

Although i change the for ..loop into a reversed loop as below:

```<code>for node in reversed(edgesList):
    print('node-', node)
    G.add_edge(*node,sep=',')
</code>```

it's doesn't guarantees that the last element of the node 'm' to be appread on the top position of the rest.
Appreciate if anyone can help on how to set the last node to be permanently appear at the top position ?

答:
Here is an idea that updates the positions in the layout based on the relative position of a node of interest to the center of the graph:

```<code>def get_graph_centroid(pos):
    return np.mean(np.array([a for a in pos.values()]), axis=0)

def find_flip(node_of_interest, pos):

    node_x, node_y = pos[node_of_interest]
    cx, cy = get_graph_centroid(pos)

    flip = [1,1]

    if node_x < cx:
        flip[0] = -1
    if node_y < cy:
        flip[1] = -1

    return flip

def make_flip(pos, flip):

    x,y = flip
    pos = {key: (x*a,y*b) for key, (a,b) in pos.items()}

    return pos

pos = nx.spring_layout(G)
plt.subplot(121)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('normal layout')

plt.subplot(122)
flip = find_flip('m', pos)
pos = make_flip(pos, flip)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('flipped layout')
</code>```

Note that this code only ensures that the node is top right wrt the center, not that is the closest node to the top right corner

Body:
This is my extended work from here.
I would like to set the last element 'm' in the unique_liss  appears at the top position of the rest nodes like this.
However, most of the image generated would be like this:

this is my codes:

Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
for node in edgesList:
    print('node-', node)
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A
import numpy as np
seed = 31
pos = nx.spring_layout(G)
plt.figure(figsize=(15,8))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500,
        seed=seed, node_color = 'skyblue')

Although i change the for ..loop into a reversed loop as below:

for node in reversed(edgesList):
    print('node-', node)
    G.add_edge(*node,sep=',')

it's doesn't guarantees that the last element of the node 'm' to be appread on the top position of the rest.
Appreciate if anyone can help on how to set the last node to be permanently appear at the top position ?

Body:
Here is an idea that updates the positions in the layout based on the relative position of a node of interest to the center of the graph:

def get_graph_centroid(pos):
    return np.mean(np.array([a for a in pos.values()]), axis=0)

def find_flip(node_of_interest, pos):

    node_x, node_y = pos[node_of_interest]
    cx, cy = get_graph_centroid(pos)

    flip = [1,1]

    if node_x < cx:
        flip[0] = -1
    if node_y < cy:
        flip[1] = -1

    return flip

def make_flip(pos, flip):

    x,y = flip
    pos = {key: (x*a,y*b) for key, (a,b) in pos.items()}

    return pos

pos = nx.spring_layout(G)
plt.subplot(121)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('normal layout')

plt.subplot(122)
flip = find_flip('m', pos)
pos = make_flip(pos, flip)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('flipped layout')

Note that this code only ensures that the node is top right wrt the center, not that is the closest node to the top right corner


问:
Is it ok to run SQL CE 4.0 under .net 3.5?
I was wondering if anyone has run SQL CE 4.0 private deployment under a .net 3.5 application without issue.

Thanks.

答:
According to this walkthrough.... it will .... and I quote, "work perfectly".  I started a small project myself and while I didn't finish it, I never ran into any show stopping bugs either.

Do note however some of the updates to the comments below his blog entry.  They point out some gotcha's (not related to .net 3.5 but how he was setting up CE).

ContentLicense: CC BY-SA 3.0


问:
Why do I keep getting a warning: A cookie associated with a resource at http://127.0.0.1/ was set with `SameSite=None` but without `Secure`
Full warning message:

```<code>A cookie associated with a resource at http://127.0.0.1/ was set with `SameSite=None` but without `Secure`. A future release of Chrome will only deliver cookies marked `SameSite=None` if they are also marked `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5633521622188032.
</code>```

However, I set cookies like:

```<code>res.cookie("token", token, {httpOnly: true, sameSite: 'none', secure: true});
</code>```

Is there a way to get rid of this warning?

答:
For a cookie required in a third-party or cross-site context, you should set both SameSite=None and Secure, as you are doing in your original example.

First question though - do you definitely need this cookie to be cross-site? In other words, are you expecting different sites to make a request to yours that require this cookie to be sent? Examples here would be if your site is embedded within an iframe on another site, hosting images where you want to have cookies included, or creating a token for additional security on a cross-site form submission.

If not, consider SameSite=Lax for this cookie instead. That way it will only be sent for requests within your site.

However, when you are developing on 127.0.0.1 or localhost you generally do not have a certificate for a valid HTTPS connection. I would suggest, in Express, using app.get('env); to get your current environment ('development' or 'production') and then using that to choose if you set Secure or not.

For example:

const express = require('express');
const app = express();

if (app.get('env') !== 'development') {
  // production settings, assume HTTPS
  app.set('cookie config', { httpOnly: true, sameSite: 'lax', secure: true });
} else {
  // development settings, no HTTPS
  app.set('cookie config', { httpOnly: true, sameSite: 'lax' });
}

// Later on when setting a cookie within your route, middleware, etc.
res.cookie('token', token, app.get('cookie config'));
```

<p>You could also set up multiple cookie configs if you have different use cases on your site.</p>

<pre class="lang-js prettyprint-override"><code>if (app.get('env') !== 'development') {
  // production settings, assume HTTPS
  app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax', secure: true });
  app.set('cookie config 3p', { httpOnly: true, sameSite: 'none', secure: true });
} else {
  // development settings, no HTTPS
  app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax' });
  // Assumes that I'm hosting all my test sites under localhost,
  // so the browser won't actually see them as 3p
  app.set('cookie config 3p', { httpOnly: true, sameSite: 'lax' });
}
</code>```

You could also look up creating a self-signed certificate for your localhost environment, but that can be a bit of a pain. If you're going to do that, the effort might be better put into using some kind of container or vm for development.

Body:
Full warning message:

A cookie associated with a resource at http://127.0.0.1/ was set with `SameSite=None` but without `Secure`. A future release of Chrome will only deliver cookies marked `SameSite=None` if they are also marked `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5633521622188032.

However, I set cookies like:

res.cookie("token", token, {httpOnly: true, sameSite: 'none', secure: true});

Is there a way to get rid of this warning?

Body:
For a cookie required in a third-party or cross-site context, you should set both SameSite=None and Secure, as you are doing in your original example.

First question though - do you definitely need this cookie to be cross-site? In other words, are you expecting different sites to make a request to yours that require this cookie to be sent? Examples here would be if your site is embedded within an iframe on another site, hosting images where you want to have cookies included, or creating a token for additional security on a cross-site form submission.

If not, consider SameSite=Lax for this cookie instead. That way it will only be sent for requests within your site.

However, when you are developing on 127.0.0.1 or localhost you generally do not have a certificate for a valid HTTPS connection. I would suggest, in Express, using app.get('env); to get your current environment ('development' or 'production') and then using that to choose if you set Secure or not.

For example:

const express = require('express');
const app = express();

if (app.get('env') !== 'development') {
  // production settings, assume HTTPS
  app.set('cookie config', { httpOnly: true, sameSite: 'lax', secure: true });
} else {
  // development settings, no HTTPS
  app.set('cookie config', { httpOnly: true, sameSite: 'lax' });
}

// Later on when setting a cookie within your route, middleware, etc.
res.cookie('token', token, app.get('cookie config'));

You could also set up multiple cookie configs if you have different use cases on your site.

if (app.get('env') !== 'development') {
  // production settings, assume HTTPS
  app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax', secure: true });
  app.set('cookie config 3p', { httpOnly: true, sameSite: 'none', secure: true });
} else {
  // development settings, no HTTPS
  app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax' });
  // Assumes that I'm hosting all my test sites under localhost,
  // so the browser won't actually see them as 3p
  app.set('cookie config 3p', { httpOnly: true, sameSite: 'lax' });
}

You could also look up creating a self-signed certificate for your localhost environment, but that can be a bit of a pain. If you're going to do that, the effort might be better put into using some kind of container or vm for development.


问:
Regex to check validation in Django
I am trying to code for the following validation in Django:
"Capital Letters are allowed only as of the first-word letter or only if all letters in a word are uppercase"
I have done this till now, but it is failing, Can someone please help me?

For example:

```<code>This is The GOOD day - acceptable
ThIS is THE gOOD day - not acceptable
</code>```

My code:

```<code>RegexValidator(
        regex='(^[A-Z][\sa-z0-9]+$)|(^([A-Z]\w*\s*)+$)',
        message='Capital Letters are allowed only as first word letter or only if all letters in word are uppercase',
        code='invalid_capitalisation'
)
</code>```

答:
You may use

```<code>^(?!.*[a-z][A-Z])(?!.*[A-Z][a-z]+[A-Z]).*
</code>```

See the regex demo

Details

^ - start of string

(?!.*[a-z][A-Z]) - no lowercase letter followed with an uppercase one anywhere in the string is allowed

(?!.*[A-Z][a-z]+[A-Z]) - no uppercase letter followed with any 1 or more lowercase letters followed with an uppercase one anywhere in the string is allowed

.* - any 0 or more chars other than line break chars, as many as possible

Title: Regex to check validation in Django

Body:
I am trying to code for the following validation in Django:
"Capital Letters are allowed only as of the first-word letter or only if all letters in a word are uppercase"
I have done this till now, but it is failing, Can someone please help me?

For example:

This is The GOOD day - acceptable
ThIS is THE gOOD day - not acceptable

My code:

RegexValidator(
        regex='(^[A-Z][\sa-z0-9]+$)|(^([A-Z]\w*\s*)+$)',
        message='Capital Letters are allowed only as first word letter or only if all letters in word are uppercase',
        code='invalid_capitalisation'
)

Body:
You may use

^(?!.*[a-z][A-Z])(?!.*[A-Z][a-z]+[A-Z]).*

See the regex demo

Details

^ - start of string

(?!.*[a-z][A-Z]) - no lowercase letter followed with an uppercase one anywhere in the string is allowed

(?!.*[A-Z][a-z]+[A-Z]) - no uppercase letter followed with any 1 or more lowercase letters followed with an uppercase one anywhere in the string is allowed

.* - any 0 or more chars other than line break chars, as many as possible


问:
Using the dbm module in Python 3
I'm learning about database files and the dbm module in Python 3.1.3, and am having trouble using some of the methods from the anydbm module in Python 2.

The keys method works fine,

```<code>import dbm

db = dbm.open('dbm', 'c')
db['modest'] = 'mouse'
db['dream'] = 'theater'

for key in db.keys():
    print(key)
</code>```

yields:

```<code>b'modest'
b'dream'
</code>```

but items and values,

```<code>for k,v in db.items():
    print(k, v)

for val in db.values():
    print(val)
</code>```

bring up an AttributeError: '_dbm.dbm' object has no attribute 'items'.

Also, this:

```<code>for key in db:
    print(key)
</code>```

gets a TypeError: '_dbm.dbm' object is not iterable.

Do these methods just not work in the dbm module in Python 3? If that's true, is there anything else that I could use instead?

答:
The purpose of these sort of simple databases is to act as key/value stores. It you want all the values, you have to iterate over all the keys. Ie:

```<code>values = [db[key] for key in db.keys()]
</code>```

That will not be fast. It may me that this sort of key/value store isn't really what you need. Perhaps SQLite would be better?

That said, you can access dumbdbm under the name of dbm.dumb in Python 3.

```<code>>>> import dbm
>>> db = dbm.dumb.open('dbm', 'c')
>>>
>>> db['modest'] = 'mouse'
>>> db['dream'] = 'theater'
>>> for key in db.keys():
...     print(key)
...
b'modest'
b'dream'
>>> for k,v in db.items():
...     print(k, v)
...
b'modest' b'mouse'
b'dream' b'theater'
>>> for val in db.values():
...     print(val)
...
b'mouse'
b'theater'
</code>```

Title: Using the dbm module in Python 3

Body:
I'm learning about database files and the dbm module in Python 3.1.3, and am having trouble using some of the methods from the anydbm module in Python 2.

The keys method works fine,

import dbm

db = dbm.open('dbm', 'c')
db['modest'] = 'mouse'
db['dream'] = 'theater'

for key in db.keys():
    print(key)

yields:

b'modest'
b'dream'

but items and values,

for k,v in db.items():
    print(k, v)

for val in db.values():
    print(val)

bring up an AttributeError: '_dbm.dbm' object has no attribute 'items'.

Also, this:

for key in db:
    print(key)

gets a TypeError: '_dbm.dbm' object is not iterable.

Do these methods just not work in the dbm module in Python 3? If that's true, is there anything else that I could use instead?

Body:
The purpose of these sort of simple databases is to act as key/value stores. It you want all the values, you have to iterate over all the keys. Ie:

values = [db[key] for key in db.keys()]

That will not be fast. It may me that this sort of key/value store isn't really what you need. Perhaps SQLite would be better?

That said, you can access dumbdbm under the name of dbm.dumb in Python 3.

>>> import dbm
>>> db = dbm.dumb.open('dbm', 'c')
>>>
>>> db['modest'] = 'mouse'
>>> db['dream'] = 'theater'
>>> for key in db.keys():
...     print(key)
...
b'modest'
b'dream'
>>> for k,v in db.items():
...     print(k, v)
...
b'modest' b'mouse'
b'dream' b'theater'
>>> for val in db.values():
...     print(val)
...
b'mouse'
b'theater'


问:
About infinite loop and memory crash
When I made a program using Visual Studio, I accidentally caught an infinite loop several times. I was embarrassed to see the same sentence being printed very quickly, so I just closed the console. However, when I searched it, it is said that if I get an infinite loop, I need to shut down the processor with ctrl + c.

What I'm worried about is the memory crash. In the microprocessor class, I learned that if I don't exit the infinite loop program properly, it will crash in memory. Is it true that the infinite loop keeps running even if I close the console? If so, is there a workaround?

答:
When you exit the console application then your infinite loop also gets's terminated because the infinite loop is the part of your console window. If you're worried that your infinite loop doesn't terminate then you can simply check in the task manager (if there are any unnecessary process running in background or not).

**But it is not possible that(your infinite loop will be running ) after terminating the console window **

It does not harm your memory.

Title: About infinite loop and memory crash


问:
Selenium ReadTimeout error while logging in
Building my very first test with Selenium + Ruby. There is a step where I have to log in.
I am passing login and password, then the script clicks "Log in" button.

The login process may take a while (system specifics - it's constantly like that and ok). So, while my script is waiting to log in, after ~100 seconds my code breaks into the error:
/usr/local/Cellar/ruby@2.5/2.5.8/lib/ruby/2.5.0/net/protocol.rb:181:in `rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)

I assume I need to set up something like a timeout timing up to 240 sec for example but can't find the right way of doing that.

Could you help me to set up a right timeout property, please?

Thank you!

```<code>require 'selenium-webdriver'

driver = Selenium::WebDriver.for :chrome
# driver.manage.timeouts.implicit_wait = 240 - Tried it, didn't help
# driver.manage.timeouts.page_load = 240 -

driver.navigate.to 'https://webiste.com'

#Entering my login and password
driver.find_element(id: 'admin_user_email').send_keys('MY_LOGIN')
driver.find_element(id: 'admin_user_password').send_keys('MY_PASSWORD')

#Clicking Login button and at this step my script breaks after ~100 sec
driver.find_element(id: 'admin_user_submit_action').click

driver.navigate.to 'https://another_URL_after_logged_in'

puts 'You are on the page'
</code>```

答:
As asked for in the comments. The timeout can be increased by doing this:

client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 240 # Or whatever you need
driver = Selenium::WebDriver.for :chrome, :http_client => client
```

Body:
Building my very first test with Selenium + Ruby. There is a step where I have to log in.
I am passing login and password, then the script clicks "Log in" button.

The login process may take a while (system specifics - it's constantly like that and ok). So, while my script is waiting to log in, after ~100 seconds my code breaks into the error:
/usr/local/Cellar/ruby@2.5/2.5.8/lib/ruby/2.5.0/net/protocol.rb:181:in `rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)

I assume I need to set up something like a timeout timing up to 240 sec for example but can't find the right way of doing that.

Could you help me to set up a right timeout property, please?

Thank you!

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :chrome
# driver.manage.timeouts.implicit_wait = 240 - Tried it, didn't help
# driver.manage.timeouts.page_load = 240 -

driver.navigate.to 'https://webiste.com'

#Entering my login and password
driver.find_element(id: 'admin_user_email').send_keys('MY_LOGIN')
driver.find_element(id: 'admin_user_password').send_keys('MY_PASSWORD')

#Clicking Login button and at this step my script breaks after ~100 sec
driver.find_element(id: 'admin_user_submit_action').click

driver.navigate.to 'https://another_URL_after_logged_in'

puts 'You are on the page'


问:
print variables using ${ var } in javascript

The above is a screenshot a tutorial in which the tutor used ${ var } to print a variable in js.

But when i ran the same code, i got like this:

What is the actual problem?

答: you must use the backtick [ ` ] ; instead of the using [ ' ],So you can solve it.


问:
How can select all columns except some columns in SQL Server 2017?
I have a lot of queries that join in a query, these queries join with one id column that this column repeat.

```<code>select t1.* , t2.* , t3.* , ...
from (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
where t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...
</code>```

Queries have many columns, I want to select all columns except some columns in each query.

For example :

```<code>select
    t1.(all columns except some columns),
    t2.(all columns except some columns),
    t3.* , ...
from
    (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
where
     t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...
</code>```

how can I select all columns except some columns in sql 17?
thanks for advice.

答:
This is just a work around-</p>

```<code>-- In step 1 insert your query output to a temp table
SELECT *
INTO #Temp
FROM
(
   select t1.* , t2.* , t3.* , ...
   from (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
   where t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...
)

-- Then drop all columns from the temp table you wants to exclude
-- from your final selection
ALTER TABLE #Temp
DROP COLUMN column_name1, column_name2

-- Finally, just select all records from temp table
SELECT * FROM #Temp
</code>```

Body:
I have a lot of queries that join in a query, these queries join with one id column that this column repeat.

select t1.* , t2.* , t3.* , ...
from (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
where t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...

Queries have many columns, I want to select all columns except some columns in each query.

For example :

select
    t1.(all columns except some columns),
    t2.(all columns except some columns),
    t3.* , ...
from
    (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
where
     t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...

how can I select all columns except some columns in sql 17?
thanks for advice.

Body:
This is just a work around-

-- In step 1 insert your query output to a temp table
SELECT *
INTO #Temp
FROM
(
   select t1.* , t2.* , t3.* , ...
   from (query1) as t1 , (query2) as t2 , (query3) as t3 , ...
   where t1.id1 = t2.id2 and t1.id1 = t3.id3 and ...
)

-- Then drop all columns from the temp table you wants to exclude
-- from your final selection
ALTER TABLE #Temp
DROP COLUMN column_name1, column_name2

-- Finally, just select all records from temp table
SELECT * FROM #Temp


问:
how to turn a for loop with if statement working on datetime df into a list comprehension
I am trying to  turn the below for loop with if statement into a list comprehension.

```<code># Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1
</code>```

I tried

```<code>[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]
</code>```

but I keep getting a syntaxerror

答:
Assignments are statements.
Statements are not usable inside list comprehension. Use the loop

You should really never do it but for the sake of completeness:

```<code>trip_counts = {'AM': 0, 'PM': 0}

[trip_counts.__setitem__('AM', trip_counts['AM']+1) if trip['start']['hour'] <12 else trip_counts.__setitem__('PM', trip_counts['PM']+1) for trip in onebike_datetimes]

print(f"With list comprehension: {trip_counts}")
OUT: With list comprehension: {'AM': 1, 'PM': 2}
</code>```

Body:
I am trying to  turn the below for loop with if statement into a list comprehension.

# Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1

I tried

[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]

but I keep getting a syntaxerror

Body:
Assignments are statements.
Statements are not usable inside list comprehension. Use the loop

You should really never do it but for the sake of completeness:

trip_counts = {'AM': 0, 'PM': 0}

[trip_counts.__setitem__('AM', trip_counts['AM']+1) if trip['start']['hour'] <12 else trip_counts.__setitem__('PM', trip_counts['PM']+1) for trip in onebike_datetimes]

print(f"With list comprehension: {trip_counts}")
OUT: With list comprehension: {'AM': 1, 'PM': 2}


问:
Is there a `valueof` similar to `keyof` in TypeScript?
I want to be able to assign an object property to a value given a key and value as inputs yet still be able to determine the type of the value. It's a bit hard to explain so this code should reveal the problem:

```<code>type JWT = { id: string, token: string, expire: Date };
const obj: JWT = { id: 'abc123', token: 'tk01', expire: new Date(2018, 2, 14) };

function print(key: keyof JWT) {
    switch (key) {
        case 'id':
        case 'token':
            console.log(obj[key].toUpperCase());
            break;
        case 'expire':
            console.log(obj[key].toISOString());
            break;
    }
}

function onChange(key: keyof JWT, value: any) {
    switch (key) {
        case 'id':
        case 'token':
            obj[key] = value + ' (assigned)';
            break;
        case 'expire':
            obj[key] = value;
            break;
    }
}

print('id');
print('expire');
onChange('id', 'def456');
onChange('expire', new Date(2018, 3, 14));
print('id');
print('expire');

onChange('expire', 1337); // should fail here at compile time
print('expire'); // actually fails here at run time
</code>```

I tried changing value: any to value: valueof JWT but that didn't work.

Ideally, onChange('expire', 1337) would fail because 1337 is not a Date type.

How can I change value: any to be the value of the given key?

答:
One-liner:

type ValueTypesOfPropFromMyCoolType = MyCoolType[keyof MyCoolType];
```

<p>Example on a generic method:</p>

```declare function doStuff<V extends MyCoolType[keyof MyCoolType]>(propertyName: keyof MyCoolType, value: V) => void;
```

Body:
I want to be able to assign an object property to a value given a key and value as inputs yet still be able to determine the type of the value. It's a bit hard to explain so this code should reveal the problem:

type JWT = { id: string, token: string, expire: Date };
const obj: JWT = { id: 'abc123', token: 'tk01', expire: new Date(2018, 2, 14) };

function print(key: keyof JWT) {
    switch (key) {
        case 'id':
        case 'token':
            console.log(obj[key].toUpperCase());
            break;
        case 'expire':
            console.log(obj[key].toISOString());
            break;
    }
}

function onChange(key: keyof JWT, value: any) {
    switch (key) {
        case 'id':
        case 'token':
            obj[key] = value + ' (assigned)';
            break;
        case 'expire':
            obj[key] = value;
            break;
    }
}

print('id');
print('expire');
onChange('id', 'def456');
onChange('expire', new Date(2018, 3, 14));
print('id');
print('expire');

onChange('expire', 1337); // should fail here at compile time
print('expire'); // actually fails here at run time

I tried changing value: any to value: valueof JWT but that didn't work.

Ideally, onChange('expire', 1337) would fail because 1337 is not a Date type.

How can I change value: any to be the value of the given key?

Body:
One-liner:

type ValueTypesOfPropFromMyCoolType = MyCoolType[keyof MyCoolType];

Example on a generic method:

declare function doStuff<V extends MyCoolType[keyof MyCoolType]>(propertyName: keyof MyCoolType, value: V) => void;


问:
Waiting until the task finishes
How could I make my code wait until the task in DispatchQueue finishes? Does it need any CompletionHandler or something?

```<code>func myFunction() {
    var a: Int?

    DispatchQueue.main.async {
        var b: Int = 3
        a = b
    }

    // wait until the task finishes, then print

    print(a) // - this will contain nil, of course, because it
             // will execute before the code above

}
</code>```

I'm using Xcode 8.2 and writing in Swift 3.

答:
Swift 5 version of the solution</p>
```<code>func myCriticalFunction() {
    var value1: String?
    var value2: String?

    let group = DispatchGroup()

    group.enter()
    //async operation 1
    DispatchQueue.global(qos: .default).async {
        // Network calls or some other async task
        value1 = //out of async task
        group.leave()
    }

    group.enter()
    //async operation 2
    DispatchQueue.global(qos: .default).async {
        // Network calls or some other async task
        value2 = //out of async task
        group.leave()
    }

    group.wait()

    print("Value1 \(value1) , Value2 \(value2)")
}
</code>```

Title: Waiting until the task finishes

Body:
How could I make my code wait until the task in DispatchQueue finishes? Does it need any CompletionHandler or something?

func myFunction() {
    var a: Int?

    DispatchQueue.main.async {
        var b: Int = 3
        a = b
    }

    // wait until the task finishes, then print

    print(a) // - this will contain nil, of course, because it
             // will execute before the code above

}

I'm using Xcode 8.2 and writing in Swift 3.

Body:
Swift 5 version of the solution

func myCriticalFunction() {
    var value1: String?
    var value2: String?

    let group = DispatchGroup()

    group.enter()
    //async operation 1
    DispatchQueue.global(qos: .default).async {
        // Network calls or some other async task
        value1 = //out of async task
        group.leave()
    }

    group.enter()
    //async operation 2
    DispatchQueue.global(qos: .default).async {
        // Network calls or some other async task
        value2 = //out of async task
        group.leave()
    }

    group.wait()

    print("Value1 \(value1) , Value2 \(value2)")
}


问:
Replace field value in property file using batch
Can anyone help me to replace a field value in property file using batch.

I have this field in my application.properties file: accessKey=AKIAJ2Q and I want to replace it with accessKey=XXXXX

I tried with sed command as recommanded here but it didn't work. The send command is not recognized by windows 10.

I tried also the following code:

```<code>SET key="XXXXX"
FOR /F %i IN (application.properties) DO SET accessKey=%key%
pause
</code>```

Any help would be appreciated.

Thanks

答:
There is surely a way to replace a string inside a txt/properties file using pure batch.

Taking above example to replace accessKey in application.properties
  file.

```<code>@ECHO OFF
SETLOCAL
SET "sourcedir=C:\<Add directory path of application.properties>"
(
 FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\application.properties") DO (
  FOR /f "tokens=1*delims==" %%g IN ("%%a") DO (
   IF /i "%%g"=="accessKey" (
      ECHO(%%g=xxxx
    ) ELSE (
      ECHO(%%a)
  )
 )
)>application_new.properties
:: This new file now contains a modified version.

rem ECHO(MOVE /y application_new.properties "%sourcedir%\application.properties"

GOTO :EOF
</code>```

Body:
Can anyone help me to replace a field value in property file using batch.

I have this field in my application.properties file: accessKey=AKIAJ2Q and I want to replace it with accessKey=XXXXX

I tried with sed command as recommanded here but it didn't work. The send command is not recognized by windows 10.

I tried also the following code:

SET key="XXXXX"
FOR /F %i IN (application.properties) DO SET accessKey=%key%
pause

Any help would be appreciated.

Thanks

Body:
There is surely a way to replace a string inside a txt/properties file using pure batch.

Taking above example to replace accessKey in application.properties
  file.

@ECHO OFF
SETLOCAL
SET "sourcedir=C:\<Add directory path of application.properties>"
(
 FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\application.properties") DO (
  FOR /f "tokens=1*delims==" %%g IN ("%%a") DO (
   IF /i "%%g"=="accessKey" (
      ECHO(%%g=xxxx
    ) ELSE (
      ECHO(%%a)
  )
 )
)>application_new.properties
:: This new file now contains a modified version.

rem ECHO(MOVE /y application_new.properties "%sourcedir%\application.properties"

GOTO :EOF


问:
why can't using variable in php-ml least square?
where in php-ml looping variable is always error array_unshift like this:

```<code>Fatal error: Uncaught TypeError: array_unshift() expects parameter 1 to be array, string given in C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php:100 Stack trace: #0 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(100): array_unshift('[2018, 1, 1], [...', 1) #1 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(81): Phpml\Regression\LeastSquares->getSamplesMatrix() #2 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(42): Phpml\Regression\LeastSquares->computeCoefficients() #3 C:\xampp\htdocs\prediksi\admin\modul\show_predict.php(40): Phpml\Regression\LeastSquares->train(Array, Array) #4 C:\xampp\htdocs\prediksi\admin\index.php(85): require('C:\\xampp\\htdocs...') #5 {main} thrown in C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php on line 100
</code>```

why this happen?

there is my code to looping :

```<code>$query1 = "SELECT * FROM master_data";

$result1 = mysqli_query($conn, $query1);

$data1 = "";

while($row1 = mysqli_fetch_array($result1)){
    $TH=number_clean($row1['TH']);
    $B=$row1['B'];

$data1 .= "[".$row1["T"].", ".$B.", ".$TH."], ";

}

$data1 = substr($data1, 0, -2);

$query2 = "SELECT * from master_data";

$result2 = mysqli_query($conn, $query2);

$data2 = "";

while($row2 = mysqli_fetch_array($result2)){

  $data2 .= "".$row2["Penjualan"].", ";

}

$data2 = substr($data2, 0, -2);

$tgl=$_POST['tgl'];
$dat1=$_POST['data1'];
$dat2=$_POST['data2'];

$samples = [$dat1];
$targets = [$dat2];

$regression = new LeastSquares();
$regression->train($samples, $targets);
$result = round($regression->predict([$t, $b, $th]));
echo $t."<br>";
echo $b."<br>";
echo $th."<br>";
echo $result."<br>";
</code>```

and the result is in up of my question

when i use manual (insert one by one) it works

why this happen ?

答:
The issue is when you are calling array_unshift you are passing a string, not a variable. Looking at your function you should change it to:

```<code>private function getSamplesMatrix() {
    $samples = [];
    array_unshift($samples, 1);
    return new Matrix($samples);
}
</code>```

Remove the foreach loop.

However I'm confused by your code as you are performing array_unshift on an empty array. You can achieve the same thing with:

```<code>$samples = array(1);
</code>```

Body:
where in php-ml looping variable is always error array_unshift like this:

Fatal error: Uncaught TypeError: array_unshift() expects parameter 1 to be array, string given in C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php:100 Stack trace: #0 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(100): array_unshift('[2018, 1, 1], [...', 1) #1 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(81): Phpml\Regression\LeastSquares->getSamplesMatrix() #2 C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php(42): Phpml\Regression\LeastSquares->computeCoefficients() #3 C:\xampp\htdocs\prediksi\admin\modul\show_predict.php(40): Phpml\Regression\LeastSquares->train(Array, Array) #4 C:\xampp\htdocs\prediksi\admin\index.php(85): require('C:\\xampp\\htdocs...') #5 {main} thrown in C:\xampp\htdocs\prediksi\assets\main system\vendor\php-ai\php-ml\src\Phpml\Regression\LeastSquares.php on line 100

why this happen?

there is my code to looping :

$query1 = "SELECT * FROM master_data";

$result1 = mysqli_query($conn, $query1);

$data1 = "";

while($row1 = mysqli_fetch_array($result1)){
    $TH=number_clean($row1['TH']);
    $B=$row1['B'];

$data1 .= "[".$row1["T"].", ".$B.", ".$TH."], ";

}

$data1 = substr($data1, 0, -2);

$query2 = "SELECT * from master_data";

$result2 = mysqli_query($conn, $query2);

$data2 = "";

while($row2 = mysqli_fetch_array($result2)){

  $data2 .= "".$row2["Penjualan"].", ";

}

$data2 = substr($data2, 0, -2);

$tgl=$_POST['tgl'];
$dat1=$_POST['data1'];
$dat2=$_POST['data2'];

$samples = [$dat1];
$targets = [$dat2];

$regression = new LeastSquares();
$regression->train($samples, $targets);
$result = round($regression->predict([$t, $b, $th]));
echo $t."
";
echo $b."
";
echo $th."
";
echo $result."
";

and the result is in up of my question

when i use manual (insert one by one) it works

why this happen ?

Body:
The issue is when you are calling array_unshift you are passing a string, not a variable. Looking at your function you should change it to:

private function getSamplesMatrix() {
    $samples = [];
    array_unshift($samples, 1);
    return new Matrix($samples);
}

Remove the foreach loop.

However I'm confused by your code as you are performing array_unshift on an empty array. You can achieve the same thing with:

$samples = array(1);


问:
Wsgi number of process and threads setting in AWS Beanstalk
I have an AWS beanstalk env and have old setting of wsgi (given below), I do not have idea how does this work internally, can anybody guide me?

```<code>NumProcesses:7 -- number of process
NumThreads:5 -- number of thread in each process
</code>```

How memory and cpu are being used with this configuration because there is no memory and cpu settings in AWS beanstalk level.

答:
These parameters are part of configuration option for Python environment:

aws:elasticbeanstalk:application:environment.

They mean (from docs):

NumProcesses: The number of daemon processes that should be started for the process group when running WSGI applications (default value 1).

NumThreads: The number of threads to be created to handle requests in each daemon process within the process group when running WSGI applications (default value 15).

Internally, these values map to uwsgi or gunicorn configuration options in your EB environment. For example:

```<code>uwsgi --http :8000 --wsgi-file application.py --master --processes 4 --threads 2
</code>```

Their impact on  memory and cpu usage of your instance(s) is based on your application and how resource intensive it is. If you are not sure how to set them up, maybe keeping them at default values would be a good start.

The settings are also available in the EB console, under Software category:

Body:
I have an AWS beanstalk env and have old setting of wsgi (given below), I do not have idea how does this work internally, can anybody guide me?

NumProcesses:7 -- number of process
NumThreads:5 -- number of thread in each process

How memory and cpu are being used with this configuration because there is no memory and cpu settings in AWS beanstalk level.

Body:
These parameters are part of configuration option for Python environment:

aws:elasticbeanstalk:application:environment.

They mean (from docs):

NumProcesses: The number of daemon processes that should be started for the process group when running WSGI applications (default value 1).

NumThreads: The number of threads to be created to handle requests in each daemon process within the process group when running WSGI applications (default value 15).

Internally, these values map to uwsgi or gunicorn configuration options in your EB environment. For example:

uwsgi --http :8000 --wsgi-file application.py --master --processes 4 --threads 2

Their impact on  memory and cpu usage of your instance(s) is based on your application and how resource intensive it is. If you are not sure how to set them up, maybe keeping them at default values would be a good start.

The settings are also available in the EB console, under Software category:


问:
What does quote in select is intended to do?
I am stuck on a select I saw in production code which looks similar to this one and is a part of a PL/SQL procedure (rest of it I consider as irrelevant):

```<code>SELECT 'Tag1' FIELD_ONE, 'English' FIELD_TWO, 'DummyData' FIELD_THREE FROM SOME_TABLE;
</code>```

What are these quotes intended to do?

答:
In SQL, the single quote is used to define string and date constant values (which in the documentation are called "literal values").  In this case, your query returns three columns, each a string.

You are, of course, free to write your code however you like.  I recommend always using as for column aliases:

```<code>SELECT 'Tag1' as FIELD_ONE, 'English' as FIELD_TWO, 'DummyData' as FIELD_THREE
FROM SOME_TABLE;
</code>```

This makes it much easier to debug errors if you leave out a comma.

Body:
I am stuck on a select I saw in production code which looks similar to this one and is a part of a PL/SQL procedure (rest of it I consider as irrelevant):

SELECT 'Tag1' FIELD_ONE, 'English' FIELD_TWO, 'DummyData' FIELD_THREE FROM SOME_TABLE;

What are these quotes intended to do?

Body:
In SQL, the single quote is used to define string and date constant values (which in the documentation are called "literal values").  In this case, your query returns three columns, each a string.

You are, of course, free to write your code however you like.  I recommend always using as for column aliases:

SELECT 'Tag1' as FIELD_ONE, 'English' as FIELD_TWO, 'DummyData' as FIELD_THREE
FROM SOME_TABLE;

This makes it much easier to debug errors if you leave out a comma.


问:
How can I stash only staged changes in Git?
Is there a way I can stash just my staged changes? The scenario I'm having issues with is when I've worked on several bugs at a given time, and have several unstaged changes. I'd like to be able to stage these files individually, create my .patch files, and stash them away until the code is approved. This way, when it's approved I can stash my entire (current) session, pop that bug and push the code.

Am I going about this the wrong way? Am I misunderstanding how git can work in other ways to simplify my process?

答:
TL;DR; git stash-staged

After creating an alias:

```<code>git config --global alias.stash-staged '!bash -c "git stash -- \$(git diff --staged --name-only)"'
</code>```

Here git diff returns list of --staged files --name-only

And then we pass this list as pathspec to git stash commad.

From man git stash:

```<code>git stash [--] [<pathspec>...]

<pathspec>...
   The new stash entry records the modified states only for the files
   that match the pathspec. The index entries and working tree
   files are then rolled back to the state in HEAD only for these
   files, too, leaving files that do not match the pathspec intact.

</code>```

Body:
TL;DR; git stash-staged

After creating an alias:

git config --global alias.stash-staged '!bash -c "git stash -- \$(git diff --staged --name-only)"'

Here git diff returns list of --staged files --name-only

And then we pass this list as pathspec to git stash commad.

From man git stash:

git stash [--] [<pathspec>...]

<pathspec>...
   The new stash entry records the modified states only for the files
   that match the pathspec. The index entries and working tree
   files are then rolled back to the state in HEAD only for these
   files, too, leaving files that do not match the pathspec intact.


问:
FutureBuilder return passed to var Flutter
I need to store some data inside a ".txt" file into a variable.
To do this I'm using a FutureBuilder.
The idea is to handle the reading action (async) with FutureBuilder and pass the FutureBuilder return to my global variable that will be updated when needed.

```<code>  Future<String> _read() async {
   try {
   final file = await _localBio;
   String body = await file.readAsString();
   // Read the file.
   return body;
   } catch (e) {
   // If encountering an error, return 0.
   return "Can't read";
 }
}

var bio ="";

String _ReadBio(){
FutureBuilder<String>(
  future: _read(),
  builder: (context, snapshot){
    if (snapshot.hasData) {
      bio=snapshot.data.toString(); //this isn't done
      return Text("");
    }
    else {
      return Text("Error occured");
    }
  }
);
return "";
}
</code>```

Then in the TextField I want to show what is stored inside bio that should be the content of "bio.txt".

```<code>child: Text(
 _ReadBio()== "" //always true if no error occured
 ? bio
 : "Tell us something about you...",
 ),
</code>```

But what is showed is the first bio value, I don't know why.

答:
I strongly suggest you to read about FutureBuilder.

You are missing the point od FutureBuilder because its is a widget to place in a widget tree what you have done is placed on a function that returns a empty string.

Instead you can do it like this,

```<code>Future<Widget> _readAndBuildBioWidget(){
   return FutureBuilder<String>(
     future: _read(),
     builder: (context, snapshot){
       if (snapshot.hasData) {
         bio=snapshot.data.toString(); //this isn't done
         return Text(bio ?? "");
       }
       else {
         return Text("Error occured");
      }
    }
  );
  return "";
}

@override
void build() {
   return Scaffold(
     child: _readAndBuildBioWidget(),
   );
}
</code>```

Or you can do as below,

```<code>class _HomeScreenState extends State<HomeScreen> {
  var bio = "";

  Future<String> _read() async {
    try {
      final file = await _localBio;
      String body = await file.readAsString();
      return body;
    } catch (e) {
      return "Can't read";
    }
  }

  @override
  void initState() {
    _read().then((onValue) => bio = onValue);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text(bio ?? "")),
    );
  }
}
</code>```

Note above code snippet I haven't tested. I just wanted to give a rough idea.

Body:
I need to store some data inside a ".txt" file into a variable.
To do this I'm using a FutureBuilder.
The idea is to handle the reading action (async) with FutureBuilder and pass the FutureBuilder return to my global variable that will be updated when needed.

  Future<String> _read() async {
   try {
   final file = await _localBio;
   String body = await file.readAsString();
   // Read the file.
   return body;
   } catch (e) {
   // If encountering an error, return 0.
   return "Can't read";
 }
}

var bio ="";

String _ReadBio(){
FutureBuilder<String>(
  future: _read(),
  builder: (context, snapshot){
    if (snapshot.hasData) {
      bio=snapshot.data.toString(); //this isn't done
      return Text("");
    }
    else {
      return Text("Error occured");
    }
  }
);
return "";
}

Then in the TextField I want to show what is stored inside bio that should be the content of "bio.txt".

child: Text(
 _ReadBio()== "" //always true if no error occured
 ? bio
 : "Tell us something about you...",
 ),

But what is showed is the first bio value, I don't know why.

Body:
I strongly suggest you to read about FutureBuilder.

You are missing the point od FutureBuilder because its is a widget to place in a widget tree what you have done is placed on a function that returns a empty string.

Instead you can do it like this,

Future<Widget> _readAndBuildBioWidget(){
   return FutureBuilder<String>(
     future: _read(),
     builder: (context, snapshot){
       if (snapshot.hasData) {
         bio=snapshot.data.toString(); //this isn't done
         return Text(bio ?? "");
       }
       else {
         return Text("Error occured");
      }
    }
  );
  return "";
}

@override
void build() {
   return Scaffold(
     child: _readAndBuildBioWidget(),
   );
}

Or you can do as below,

class _HomeScreenState extends State<HomeScreen> {
  var bio = "";

  Future<String> _read() async {
    try {
      final file = await _localBio;
      String body = await file.readAsString();
      return body;
    } catch (e) {
      return "Can't read";
    }
  }

  @override
  void initState() {
    _read().then((onValue) => bio = onValue);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text(bio ?? "")),
    );
  }
}

Note above code snippet I haven't tested. I just wanted to give a rough idea.


问:
Using Selenium to grab specific information in Python
So I am quite new to using Selenium and thus and quite unsure how to do this, or even word it for this matter.

But what I am trying to do is to use selenium to grab the following values and then store them into a list.

Image provided of the inspector window of Firefox, to show what I am trying to grab (Highlighted)

https://i.stack.imgur.com/rHk9R.png

答:
In Selenium, you access elements using functions find_element(s)_by_xxx(), where xxx is for example the tag name, element name or class name (and more). The functions find_element_... return the first element that matches the argument, while find_elements_... return all matching elements.

Selenium has a [good documentation][1], in section "Getting started" you can find several examples of basic usage.

As to your question, the following code should collect the values you want:

```<code>    from selenium import webdriver

    driver = webdriver.Firefox()  # driver for the browser you use

    select_elem = driver.find_element_by_name('ctl00_Content...')  # full name of the element
    options = select_elem.find_elements_by_tag_name('option')

    values = []

    for option in options:
      val = option.get_attribute('value')
      values.append(val)
</code>```

Body:
In Selenium, you access elements using functions find_element(s)_by_xxx(), where xxx is for example the tag name, element name or class name (and more). The functions find_element_... return the first element that matches the argument, while find_elements_... return all matching elements.

Selenium has a [good documentation][1], in section "Getting started" you can find several examples of basic usage.

As to your question, the following code should collect the values you want:

    from selenium import webdriver

    driver = webdriver.Firefox()  # driver for the browser you use

    select_elem = driver.find_element_by_name('ctl00_Content...')  # full name of the element
    options = select_elem.find_elements_by_tag_name('option')

    values = []

    for option in options:
      val = option.get_attribute('value')
      values.append(val)


答:
It means that you didn't select those values from columns but as "constants". For example:</p>

```<code>SQL> SELECT 'Tag1' FIELD_ONE, 'English' FIELD_TWO, 'DummyData' FIELD_THREE FROM dual;

FIEL FIELD_T FIELD_THR
---- ------- ---------
Tag1 English DummyData

SQL>
</code>```

Title: What does quote in select is intended to do?

Body:
It means that you didn't select those values from columns but as "constants". For example:

SQL> SELECT 'Tag1' FIELD_ONE, 'English' FIELD_TWO, 'DummyData' FIELD_THREE FROM dual;

FIEL FIELD_T FIELD_THR
---- ------- ---------
Tag1 English DummyData

SQL>


问:
How to create json dinamically nesting info inside an array
I'm developing a code to analyse image pixels (totally 1,048,576 for each image). As it's going to be a huge amount of info to insert on a database I decided that the best option may be to create a file to store all results.

So on, I'm using PHP-Laravel. Not going to show the entire code, but give some hints about I did.

1.-First of all I created at the beggining of my code the command to create my results.txt file:

```<code>$resultsFile = Storage::put('results/results.txt', '');
</code>```

2.- After processing info this is what I want to store: the resulting material and coordinates

```<code>$data_to_insert = [
                    'material' => 'how',
                    'coord_x' => $pixel_x,
                    'coord_y' => $pixel_y,
                ];
</code>```

3.- I created this headers for my file:

```<code>$headers = [
             'orbit' => 'Vesta Test',
              'results' => []
];

$headers['results'] = $data_para_insertar;
file_put_contents('results.txt', json_encode($headers));
</code>```

Well the problem comes when I try to get the info already stored:

```<code>$json_data = json_decode(Storage::get('results/results.txt'), true);
</code>```

And try to merge my already results stored with my new result:

```<code>$results = array_merge($json_data['results'], $data_to_insert);
</code>```

I just store the last register to my file:

```<code>{"orbit":"Vesta Test","results":{"material":"how","coord_x":946,"coord_y":963}}
</code>```

I would like to store info on "results" in this way or similar

```<code>{
  "orbit":"Vesta Test",
  "results": [
              {"material":"how","coord_x":946,"coord_y":963},
              {"material":"how","coord_x":955,"coord_y":933},
              .....
   ]
}
</code>```

All happens inside a for statement.

Thanks a lot for your help.

答:
Instead of the

```<code>$results = array_merge($json_data['results'], $data_to_insert);
</code>```

you need to append the data to the results element, you can use

```<code>$json_data['results'][] = $data_to_insert;
</code>```

Body:
I'm developing a code to analyse image pixels (totally 1,048,576 for each image). As it's going to be a huge amount of info to insert on a database I decided that the best option may be to create a file to store all results.

So on, I'm using PHP-Laravel. Not going to show the entire code, but give some hints about I did.

1.-First of all I created at the beggining of my code the command to create my results.txt file:

$resultsFile = Storage::put('results/results.txt', '');

2.- After processing info this is what I want to store: the resulting material and coordinates

$data_to_insert = [
                    'material' => 'how',
                    'coord_x' => $pixel_x,
                    'coord_y' => $pixel_y,
                ];

3.- I created this headers for my file:

$headers = [
             'orbit' => 'Vesta Test',
              'results' => []
];

$headers['results'] = $data_para_insertar;
file_put_contents('results.txt', json_encode($headers));

Well the problem comes when I try to get the info already stored:

$json_data = json_decode(Storage::get('results/results.txt'), true);

And try to merge my already results stored with my new result:

$results = array_merge($json_data['results'], $data_to_insert);

I just store the last register to my file:

{"orbit":"Vesta Test","results":{"material":"how","coord_x":946,"coord_y":963}}

I would like to store info on "results" in this way or similar

{
  "orbit":"Vesta Test",
  "results": [
              {"material":"how","coord_x":946,"coord_y":963},
              {"material":"how","coord_x":955,"coord_y":933},
              .....
   ]
}

All happens inside a for statement.

Thanks a lot for your help.

Body:
Instead of the

$results = array_merge($json_data['results'], $data_to_insert);

you need to append the data to the results element, you can use

$json_data['results'][] = $data_to_insert;


问:
Filter multiple CSV for text and create new files
I have about 2500 CSV files each around 20MB in terms of file size. I am trying to filter out certain rows from each file and save that to a new file.

So, if i have :

```<code>File 1 :
    Row1
    Row2
    Row3
File 2 :
    Row2
    Row3
and so on..
</code>```

If i filter for all files and select "Row2" as filter text the new folder should have all the files with only rows that match the filter text.

Looking through some forums, I came up with the following that might help me filter the rows, but Im not sure how I can do it recursively, plus I also don't know if this is a fast enough method. Any help is appreciated.

```<code>Get-Content "C:\Path to file" | Where{$_ -match "Rowfiltertext*"} | Out-File "Path to Out file"
</code>```

I'm using windows so I guess Powershell type of solution would be the best here.

The text to be filtered will always be in the first column.

Thanks
Siddhant

答:
Here's two fast ways of searching for a string inside (text) files:

1) using switch

```<code>$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv.txt'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
Get-ChildItem -Path $sourcePath -Filter '*.csv' -File | ForEach-Object {
    # iterate through the lines in the file and output the ones that match the search pattern
    switch -Regex -File $_.FullName {
        $searchPattern { $_ }
    }
} | Set-Content -Path $outputPath  # add -PassThru to also show on screen
</code>```

2) using Select-String

```<code>$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv.txt'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
Get-ChildItem  -Path $sourcePath -Filter '*.csv' -File | ForEach-Object {
    ($_ | Select-String -Pattern $searchPattern).Line
} | Set-Content -Path $outputPath  # add -PassThru to also show on screen
</code>```

In case you want to output a new csv file for every original file,

use:

3) using switch

```<code>$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv'

if (!(Test-Path -Path $outputPath -PathType Container)) {
    $null = New-Item -Path $outputPath -ItemType Directory
}

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
(Get-ChildItem -Path $sourcePath -Filter '*.csv' -File) | ForEach-Object {
    # create a full target filename for the filtered output csv
    $outFile = Join-Path -Path $outputPath -ChildPath ('New_{0}' -f $_.Name)
    # iterate through the lines in the file and output the ones that match the search pattern
    $result = switch -Regex -File $_.FullName {
        $searchPattern { $_ }
    }
    $result | Set-Content -Path $outFile  # add -PassThru to also show on screen
}
</code>```

4) using Select-String

```<code>$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
(Get-ChildItem  -Path $sourcePath -Filter '*.csv' -File) | ForEach-Object {
    # create a full target filename for the filtered output csv
    $outFile = Join-Path -Path $outputPath -ChildPath ('New_{0}' -f $_.Name)
    ($_ | Select-String -Pattern $searchPattern).Line | Set-Content -Path $outFile  # add -PassThru to also show on screen
}
</code>```

Hope that helps

Body:
I have about 2500 CSV files each around 20MB in terms of file size. I am trying to filter out certain rows from each file and save that to a new file.

So, if i have :

File 1 :
    Row1
    Row2
    Row3
File 2 :
    Row2
    Row3
and so on..

If i filter for all files and select "Row2" as filter text the new folder should have all the files with only rows that match the filter text.

Looking through some forums, I came up with the following that might help me filter the rows, but Im not sure how I can do it recursively, plus I also don't know if this is a fast enough method. Any help is appreciated.

Get-Content "C:\Path to file" | Where{$_ -match "Rowfiltertext*"} | Out-File "Path to Out file"

I'm using windows so I guess Powershell type of solution would be the best here.

The text to be filtered will always be in the first column.

Thanks
Siddhant

Body:
Here's two fast ways of searching for a string inside (text) files:

1) using switch

$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv.txt'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
Get-ChildItem -Path $sourcePath -Filter '*.csv' -File | ForEach-Object {
    # iterate through the lines in the file and output the ones that match the search pattern
    switch -Regex -File $_.FullName {
        $searchPattern { $_ }
    }
} | Set-Content -Path $outputPath  # add -PassThru to also show on screen

2) using Select-String

$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv.txt'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
Get-ChildItem  -Path $sourcePath -Filter '*.csv' -File | ForEach-Object {
    ($_ | Select-String -Pattern $searchPattern).Line
} | Set-Content -Path $outputPath  # add -PassThru to also show on screen

In case you want to output a new csv file for every original file,

use:

3) using switch

$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv'

if (!(Test-Path -Path $outputPath -PathType Container)) {
    $null = New-Item -Path $outputPath -ItemType Directory
}

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
(Get-ChildItem -Path $sourcePath -Filter '*.csv' -File) | ForEach-Object {
    # create a full target filename for the filtered output csv
    $outFile = Join-Path -Path $outputPath -ChildPath ('New_{0}' -f $_.Name)
    # iterate through the lines in the file and output the ones that match the search pattern
    $result = switch -Regex -File $_.FullName {
        $searchPattern { $_ }
    }
    $result | Set-Content -Path $outFile  # add -PassThru to also show on screen
}

4) using Select-String

$searchPattern = [regex]::Escape('Rowfiltertext')  # for safety escape regex special characters
$sourcePath    = 'X:\Path\To\The\Csv\Files'
$outputPath    = 'X:\FilteredCsv'

# if you also need to search inside subfolders, append -Recurse to the Get-ChildItem cmdlet
(Get-ChildItem  -Path $sourcePath -Filter '*.csv' -File) | ForEach-Object {
    # create a full target filename for the filtered output csv
    $outFile = Join-Path -Path $outputPath -ChildPath ('New_{0}' -f $_.Name)
    ($_ | Select-String -Pattern $searchPattern).Line | Set-Content -Path $outFile  # add -PassThru to also show on screen
}

Hope that helps


问:
JavaScript - how to encrypt string with only password in 2020?
I want to encrypt/decrypt a string with a human readable password. The encrypted data should be decryptable knowing the password only. What is the recommended tool in 2020?

symmetric encryption in the built-in SubtleCrypto interface require generated key (based on the examples I found), and they also need additional data for decryption (a counter, or iv value).

related SO question is 6 years old

```<code>const data = "Hello World";
const key = "SuperSecret";

const encrypted = encrypt(data, key);
console.log(encrypted);  // gibberish

const decrypted = decrypt(encrypted, key);
console.log(decrypted);  // Hello World
</code>```

答:
Here is an example, to achieve simple encrypt/decrypt

// derive string key
async function deriveKey(password) {
  const algo = {
    name: 'PBKDF2',
    hash: 'SHA-256',
    salt: new TextEncoder().encode('a-unique-salt'),
    iterations: 1000
  }
  return crypto.subtle.deriveKey(
    algo,
    await crypto.subtle.importKey(
      'raw',
      new TextEncoder().encode(password),
      {
        name: algo.name
      },
      false,
      ['deriveKey']
    ),
    {
      name: 'AES-GCM',
      length: 256
    },
    false,
    ['encrypt', 'decrypt']
  )
}

// Encrypt function
async function encrypt(text, password) {
  const algo = {
    name: 'AES-GCM',
    length: 256,
    iv: crypto.getRandomValues(new Uint8Array(12))
  }
  return {
    cipherText: await crypto.subtle.encrypt(
      algo,
      await deriveKey(password),
      new TextEncoder().encode(text)
    ),
    iv: algo.iv
  }
}

// Decrypt function
async function decrypt(encrypted, password) {
  const algo = {
    name: 'AES-GCM',
    length: 256,
    iv: encrypted.iv
  }
  return new TextDecoder().decode(
    await crypto.subtle.decrypt(
      algo,
      await deriveKey(password),
      encrypted.cipherText
    )
  )
}

// example
;(async () => {
  // encrypt
  const encrypted = await encrypt('Secret text', 'password')

  // the cipher text
  console.log(
    String.fromCharCode.apply(null, new Uint8Array(encrypted.cipherText))
  )

  // decrypt it
  const decrypted = await decrypt(encrypted, 'password')
  console.log(decrypted) // Secret text
})()```

Body:
I want to encrypt/decrypt a string with a human readable password. The encrypted data should be decryptable knowing the password only. What is the recommended tool in 2020?

symmetric encryption in the built-in SubtleCrypto interface require generated key (based on the examples I found), and they also need additional data for decryption (a counter, or iv value).

related SO question is 6 years old

const data = "Hello World";
const key = "SuperSecret";

const encrypted = encrypt(data, key);
console.log(encrypted);  // gibberish

const decrypted = decrypt(encrypted, key);
console.log(decrypted);  // Hello World


问:
Creating a maze graph from a text file : Java
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

```<code>A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F
</code>```

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

```<code>package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}
</code>```

Can someone point me in the right direction, please?

答:
Let's concentrate on just setting up 1 maze, and then we can repeat the process for all of them.
I've tried to write a Java-syntax-friendly algorithm.

So, here's our ArrayList variable for the first maze, as I understand it...

```<code>List<String> preNodes, which contains:
{"A,G", "A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};
</code>```

Because the first String has a special meaning, let's segregate it from the rest. (ie. set it as a separate String variable, and remove it from the ArrayList).

```<code>String startAndEnd, which contains: "A,G";
List<String> preNodes, which contains:
{"A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};
</code>```

Now, let's first build all the nodes we need, and then we can link them up.

```<code>//Define container for nodes
HashMap<String, Node> nodes = new HashMap<String, Node>();
//Create a node for each letter
for(String s : preNodes) {
    String nodeName = s.charAt(0) + "";
    nodes.put(nodeName, new Node());
}
//Link them up appropriately
for(String s : preNodes) {
    String[] splitS = s.split(","); //1 letter in each array cell.
    Node current = nodes.get(splitS[0]); //Get the node we're going to link up.
    for(int i=1; i<splitS.length; i++) {
        current.connect(nodes.get(splitS[i]));
    }
}
//Finally, set the start and end Node.
String[] splitStartAndEnd = startAndEnd.split(",");
nodes.get(splitStartAndEnd[0]).isStart = true;
nodes.get(splitStartAndEnd[1]).isEnd = true;
</code>```

This should do it, I think; now "nodes" contains the whole maze, all linked up. I caught a bug in your code, though: your isConnected() function should return false if connections.isEmpty(), not if it's null. It should never be null, because you initialize it in the constructor with a new list.

Body:
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}

Can someone point me in the right direction, please?

Body:
Let's concentrate on just setting up 1 maze, and then we can repeat the process for all of them.
I've tried to write a Java-syntax-friendly algorithm.

So, here's our ArrayList variable for the first maze, as I understand it...

List<String> preNodes, which contains:
{"A,G", "A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};

Because the first String has a special meaning, let's segregate it from the rest. (ie. set it as a separate String variable, and remove it from the ArrayList).

String startAndEnd, which contains: "A,G";
List<String> preNodes, which contains:
{"A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};

Now, let's first build all the nodes we need, and then we can link them up.

//Define container for nodes
HashMap<String, Node> nodes = new HashMap<String, Node>();
//Create a node for each letter
for(String s : preNodes) {
    String nodeName = s.charAt(0) + "";
    nodes.put(nodeName, new Node());
}
//Link them up appropriately
for(String s : preNodes) {
    String[] splitS = s.split(","); //1 letter in each array cell.
    Node current = nodes.get(splitS[0]); //Get the node we're going to link up.
    for(int i=1; i<splitS.length; i++) {
        current.connect(nodes.get(splitS[i]));
    }
}
//Finally, set the start and end Node.
String[] splitStartAndEnd = startAndEnd.split(",");
nodes.get(splitStartAndEnd[0]).isStart = true;
nodes.get(splitStartAndEnd[1]).isEnd = true;

This should do it, I think; now "nodes" contains the whole maze, all linked up. I caught a bug in your code, though: your isConnected() function should return false if connections.isEmpty(), not if it's null. It should never be null, because you initialize it in the constructor with a new list.


答:
It's much clearer to keep your for-loop.

If you really want to make use of a list comprehension, you could do something like this:

l = ["AM" if trip["start"].hour < 12 else "PM" for trip in onebike_datetimes]
am_count = l.count("AM")
trip_counts = {"AM": am_count, "PM": len(l) - am_count}
```

(And you don't need to initialize trip_counts if you use this)

Title: how to turn a for loop with if statement working on datetime df into a list comprehension

Body:
I am trying to  turn the below for loop with if statement into a list comprehension.

# Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1

I tried

[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes]

but I keep getting a syntaxerror

Body:
It's much clearer to keep your for-loop.

If you really want to make use of a list comprehension, you could do something like this:

l = ["AM" if trip["start"].hour < 12 else "PM" for trip in onebike_datetimes]
am_count = l.count("AM")
trip_counts = {"AM": am_count, "PM": len(l) - am_count}

(And you don't need to initialize trip_counts if you use this)