问:
Setting distance Dimension in Or tools for vehicle routing problem
I am trying to solve a vehicle routing problem with 5 drivers for deliveries. I am using haversine and lat-long to calculate the distance matrix. I am new to OR tools, so following the vrp example.

The issues is that the out 0f 5 drivers, only routes are generated for 2 drivers and these routes are very long. I want to generate multiple shorter routes so that all the drivers are utilized. Can please check if I am setting some constraint wrong.

Can someone please explain, how to set "Distance" dimension and SetGlobalSpanCostCoefficient in google OR-tools. Here is the code and output.

```<code>from __future__ import print_function
import pandas as pd
import numpy as np
import googlemaps
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

gmaps = googlemaps.Client(key='API Key')

def calculate_geocodes():
    df = pd.read_csv("banglore_zone.csv")

    df['lat'] = pd.Series(np.repeat(0, df.size), dtype=float)
    df['long'] = pd.Series(np.repeat(0, df.size), dtype=float)

    result = np.zeros([df.size, 2])
    for index, row in df.iterrows():
        # print(row['Address'])
        geocode_result = gmaps.geocode(row['Address'])[0]
        lat = (geocode_result['geometry']['location']['lat'])
        lng = (geocode_result['geometry']['location']['lng'])
        result[index] = lat, lng
        df.lat[index] = lat
        df.long[index] = lng

    print("First step", df)
    coords = df.as_matrix(columns=['lat', 'long'])

    return coords, df

def calculate_distance_matrix(coordinates, gmaps):
    distance_matrix = np.zeros(
        (np.size(coordinates, 0), np.size(coordinates, 0)))  # create an empty matrix for distance between all locations

    for index in range(0, np.size(coordinates, 0)):
        src = coordinates[index]

        for ind in range(0, np.size(coordinates, 0)):
            dst = coordinates[ind]
            distance_matrix[index, ind] = distance(src[0], src[1], dst[0], dst[1])

    return distance_matrix

def distance(lat1, long1, lat2, long2):
    # Note: The formula used in this function is not exact, as it assumes
    # the Earth is a perfect sphere.

    # Mean radius of Earth in miles
    radius_earth = 3959

    # Convert latitude and longitude to
    # spherical coordinates in radians.
    degrees_to_radians = math.pi / 180.0
    phi1 = lat1 * degrees_to_radians
    phi2 = lat2 * degrees_to_radians
    lambda1 = long1 * degrees_to_radians
    lambda2 = long2 * degrees_to_radians
    dphi = phi2 - phi1
    dlambda = lambda2 - lambda1

    a = haversine(dphi) + math.cos(phi1) * math.cos(phi2) * haversine(dlambda)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = radius_earth * c
    return d

def haversine(angle):
    h = math.sin(angle / 2) ** 2
    return h

def create_data_model(distance_matrix, number_of_vehicles, depot):
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = distance_matrix
    print(distance_matrix)

    data['num_vehicles'] = number_of_vehicles
    data['depot'] = depot
    return data

def print_solution(data, manager, routing, solution, address_dataframe):
    """Prints solution on console."""
    max_route_distance = 0

    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        route_distance = 0
        while not routing.IsEnd(index):
            plan_output += ' {} ---> '.format(address_dataframe.iloc[manager.IndexToNode(index), 0])
            previous_index = index
            index = solution.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(
                previous_index, index, vehicle_id)
        plan_output += '{}\n'.format(manager.IndexToNode(index))
        plan_output += 'Distance of the route: {}m\n'.format(route_distance)
        print(plan_output)
        max_route_distance = max(route_distance, max_route_distance)
    print('Maximum of the route distances: {}m'.format(max_route_distance))

def main():
    coordinates, address_dataframe = calculate_geocodes()
    distance_matrix = calculate_distance_matrix(coordinates, gmaps)
    data = create_data_model(distance_matrix, 5, 0)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(
        len(data['distance_matrix']), data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['distance_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        80,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()

    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 120
    search_parameters.log_search = False

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution, address_dataframe)

if __name__ == '__main__':
    main()
</code>```

And the distance matrix and output is -

```<code>>     [[ 0.          0.31543319  3.36774402 ...  8.79765925  8.94261055
>    8.83759758]  [ 0.31543319  0.          3.09418962 ...  8.81074289  8.95034082
>    8.84901702]  [ 3.36774402  3.09418962  0.         ... 10.87348059 10.97329493
>   10.89962072]  ...  [ 8.79765925  8.81074289 10.87348059 ...  0.          0.20726879
>    0.06082994]  [ 8.94261055  8.95034082 10.97329493 ...  0.20726879  0.
>    0.1465572 ]  [ 8.83759758  8.84901702 10.89962072 ...  0.06082994  0.1465572
>    0.        ]] Route for vehicle 0:  3Embed software 10th Cross St, RBI Colony, Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of
> the route: 0m
>
> Route for vehicle 1:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of the route:
> 0m
>
> Route for vehicle 2:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  Sindhi High School,
> Kempapura --->  Hoppers stop Building No.12, Krishnaja Avenue, Near
> Kogilu Cross, International Airport Road, Yelahanka, Bengaluru --->
> Kempegowda International Airport Bengaluru --->  mvit International
> Airport Road, Hunasamaranahalli, Yelahanka, Krishnadeveraya Nagar,
> Bengaluru --->  Canadian International School 4 & 20, Manchenahalli,
> Yelahanka, Bengaluru --->  brick factory RMZ Galleria, Office Block,
> Ground Floor, B.B. Road, Yelahanka --->  Jakkur Aerodrome Bellary
> Road, Post, Yelahanka, Bengaluru, Karnataka --->  Godrej Platinum
> International Airport Road, Hebbal, Bengaluru, Karnataka --->  Vidya
> Niketan School 30, Kempapura Main Road, Kempapura, Hebbal, Bengaluru,
> Karnataka --->  Atria Institute of Technology, 1st Main Rd, Ags
> Colony, Anandnagar, Hebbal, Bengaluru, Karnataka ---> 0 Distance of
> the route: 26m
>
> Route for vehicle 3:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  Caffe cofee day CBI road
> banglore ---> 0 Distance of the route: 0m
>
> Route for vehicle 4:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  RT Nagar Police station
> --->  bus stop mekhri circle banglore --->  Truffles  80 Feet Road, Jaladarsini Layout, Sanjaynagar Banglore --->  BEL circle banglore
> --->  Paragon Outlet Shivapura, Peenya, Bengaluru --->  Taj vivanta Yeshwantpur, Bengaluru --->  Orion Mall A Block, Brigade Gateway, Dr
> Rajkumar Rd, Malleshwaram, Bengaluru --->  brand factory Malleshwaram
> Banglore  --->  Mantri Square Mall, Sampige Road, Malleshwaram,
> Bengaluru, Karnataka --->  Krantivira Sangolli Rayanna Bengaluru, M.G.
> Railway Colony, Majestic, Bengaluru --->  UB city banglore --->
> Brigade road banglore --->  MG Road metro station Banglore --->
> commercial street bangalore --->  Infantry Road, Beside Prestige
> Building, Tasker Town, Shivaji Nagar, Bengaluru, Karnataka --->
> Garuda Mall Magrath Rd, Ashok Nagar, Bengaluru --->  Brand Factory -
> Home Town Above HomeTown, Vanshee Towers, Survey No.92/4 3rd and 4th
> Floors, Outer Ring Rd, Marathahalli, Bengaluru --->  KLM Shopping
> Mall, Marathahalli Bridge Marathahalli  --->  Favourite Shop HAL Old
> Airport Rd, Subbaiah Reddy Colony, Marathahalli Village, Marathahalli,
> Bengaluru --->  Max RPR Plaza, Varthur Rd, Marathahalli, Bengaluru
> --->  Pick 'n' Move Shop No. 102, Ground Floor, Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru --->  Lotto Shoes 45/2,
> Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru, Karnataka
> --->  The Raymond Shop Opp. Mga Hospital, Marathalli Main Road Near Ring Road Junction, Bengaluru, Karnataka --->  chinnaswamy stadium
> banglore --->  fun cinemas cunningham road Banglore --->  Cant station
> banglore --->  Radhakrishna Theatre 25, 1st Main Rd, Mattdahally, RT
> Nagar, Bengaluru --->  Presidency School Near R T Nagar, HMT Layout,
> Bengaluru, Karnataka ---> 0 Distance of the route: 20m
>
> Maximum of the route distances: 26m
</code>```

答:
You should reduce vehicle maximum travel distance. currently you set it to 80.
and your routes distances are 20 and 26.</p>

```<code>routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        80,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
</code>```

Body:
I am trying to solve a vehicle routing problem with 5 drivers for deliveries. I am using haversine and lat-long to calculate the distance matrix. I am new to OR tools, so following the vrp example.

The issues is that the out 0f 5 drivers, only routes are generated for 2 drivers and these routes are very long. I want to generate multiple shorter routes so that all the drivers are utilized. Can please check if I am setting some constraint wrong.

Can someone please explain, how to set "Distance" dimension and SetGlobalSpanCostCoefficient in google OR-tools. Here is the code and output.

from __future__ import print_function
import pandas as pd
import numpy as np
import googlemaps
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

gmaps = googlemaps.Client(key='API Key')

def calculate_geocodes():
    df = pd.read_csv("banglore_zone.csv")

    df['lat'] = pd.Series(np.repeat(0, df.size), dtype=float)
    df['long'] = pd.Series(np.repeat(0, df.size), dtype=float)

    result = np.zeros([df.size, 2])
    for index, row in df.iterrows():
        # print(row['Address'])
        geocode_result = gmaps.geocode(row['Address'])[0]
        lat = (geocode_result['geometry']['location']['lat'])
        lng = (geocode_result['geometry']['location']['lng'])
        result[index] = lat, lng
        df.lat[index] = lat
        df.long[index] = lng

    print("First step", df)
    coords = df.as_matrix(columns=['lat', 'long'])

    return coords, df

def calculate_distance_matrix(coordinates, gmaps):
    distance_matrix = np.zeros(
        (np.size(coordinates, 0), np.size(coordinates, 0)))  # create an empty matrix for distance between all locations

    for index in range(0, np.size(coordinates, 0)):
        src = coordinates[index]

        for ind in range(0, np.size(coordinates, 0)):
            dst = coordinates[ind]
            distance_matrix[index, ind] = distance(src[0], src[1], dst[0], dst[1])

    return distance_matrix

def distance(lat1, long1, lat2, long2):
    # Note: The formula used in this function is not exact, as it assumes
    # the Earth is a perfect sphere.

    # Mean radius of Earth in miles
    radius_earth = 3959

    # Convert latitude and longitude to
    # spherical coordinates in radians.
    degrees_to_radians = math.pi / 180.0
    phi1 = lat1 * degrees_to_radians
    phi2 = lat2 * degrees_to_radians
    lambda1 = long1 * degrees_to_radians
    lambda2 = long2 * degrees_to_radians
    dphi = phi2 - phi1
    dlambda = lambda2 - lambda1

    a = haversine(dphi) + math.cos(phi1) * math.cos(phi2) * haversine(dlambda)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = radius_earth * c
    return d

def haversine(angle):
    h = math.sin(angle / 2) ** 2
    return h

def create_data_model(distance_matrix, number_of_vehicles, depot):
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = distance_matrix
    print(distance_matrix)

    data['num_vehicles'] = number_of_vehicles
    data['depot'] = depot
    return data

def print_solution(data, manager, routing, solution, address_dataframe):
    """Prints solution on console."""
    max_route_distance = 0

    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        route_distance = 0
        while not routing.IsEnd(index):
            plan_output += ' {} ---> '.format(address_dataframe.iloc[manager.IndexToNode(index), 0])
            previous_index = index
            index = solution.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(
                previous_index, index, vehicle_id)
        plan_output += '{}\n'.format(manager.IndexToNode(index))
        plan_output += 'Distance of the route: {}m\n'.format(route_distance)
        print(plan_output)
        max_route_distance = max(route_distance, max_route_distance)
    print('Maximum of the route distances: {}m'.format(max_route_distance))

def main():
    coordinates, address_dataframe = calculate_geocodes()
    distance_matrix = calculate_distance_matrix(coordinates, gmaps)
    data = create_data_model(distance_matrix, 5, 0)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(
        len(data['distance_matrix']), data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['distance_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        80,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()

    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 120
    search_parameters.log_search = False

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution, address_dataframe)

if __name__ == '__main__':
    main()

And the distance matrix and output is -

>     [[ 0.          0.31543319  3.36774402 ...  8.79765925  8.94261055
>    8.83759758]  [ 0.31543319  0.          3.09418962 ...  8.81074289  8.95034082
>    8.84901702]  [ 3.36774402  3.09418962  0.         ... 10.87348059 10.97329493
>   10.89962072]  ...  [ 8.79765925  8.81074289 10.87348059 ...  0.          0.20726879
>    0.06082994]  [ 8.94261055  8.95034082 10.97329493 ...  0.20726879  0.
>    0.1465572 ]  [ 8.83759758  8.84901702 10.89962072 ...  0.06082994  0.1465572
>    0.        ]] Route for vehicle 0:  3Embed software 10th Cross St, RBI Colony, Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of
> the route: 0m
>
> Route for vehicle 1:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of the route:
> 0m
>
> Route for vehicle 2:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  Sindhi High School,
> Kempapura --->  Hoppers stop Building No.12, Krishnaja Avenue, Near
> Kogilu Cross, International Airport Road, Yelahanka, Bengaluru --->
> Kempegowda International Airport Bengaluru --->  mvit International
> Airport Road, Hunasamaranahalli, Yelahanka, Krishnadeveraya Nagar,
> Bengaluru --->  Canadian International School 4 & 20, Manchenahalli,
> Yelahanka, Bengaluru --->  brick factory RMZ Galleria, Office Block,
> Ground Floor, B.B. Road, Yelahanka --->  Jakkur Aerodrome Bellary
> Road, Post, Yelahanka, Bengaluru, Karnataka --->  Godrej Platinum
> International Airport Road, Hebbal, Bengaluru, Karnataka --->  Vidya
> Niketan School 30, Kempapura Main Road, Kempapura, Hebbal, Bengaluru,
> Karnataka --->  Atria Institute of Technology, 1st Main Rd, Ags
> Colony, Anandnagar, Hebbal, Bengaluru, Karnataka ---> 0 Distance of
> the route: 26m
>
> Route for vehicle 3:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  Caffe cofee day CBI road
> banglore ---> 0 Distance of the route: 0m
>
> Route for vehicle 4:  3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 --->  RT Nagar Police station
> --->  bus stop mekhri circle banglore --->  Truffles  80 Feet Road, Jaladarsini Layout, Sanjaynagar Banglore --->  BEL circle banglore
> --->  Paragon Outlet Shivapura, Peenya, Bengaluru --->  Taj vivanta Yeshwantpur, Bengaluru --->  Orion Mall A Block, Brigade Gateway, Dr
> Rajkumar Rd, Malleshwaram, Bengaluru --->  brand factory Malleshwaram
> Banglore  --->  Mantri Square Mall, Sampige Road, Malleshwaram,
> Bengaluru, Karnataka --->  Krantivira Sangolli Rayanna Bengaluru, M.G.
> Railway Colony, Majestic, Bengaluru --->  UB city banglore --->
> Brigade road banglore --->  MG Road metro station Banglore --->
> commercial street bangalore --->  Infantry Road, Beside Prestige
> Building, Tasker Town, Shivaji Nagar, Bengaluru, Karnataka --->
> Garuda Mall Magrath Rd, Ashok Nagar, Bengaluru --->  Brand Factory -
> Home Town Above HomeTown, Vanshee Towers, Survey No.92/4 3rd and 4th
> Floors, Outer Ring Rd, Marathahalli, Bengaluru --->  KLM Shopping
> Mall, Marathahalli Bridge Marathahalli  --->  Favourite Shop HAL Old
> Airport Rd, Subbaiah Reddy Colony, Marathahalli Village, Marathahalli,
> Bengaluru --->  Max RPR Plaza, Varthur Rd, Marathahalli, Bengaluru
> --->  Pick 'n' Move Shop No. 102, Ground Floor, Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru --->  Lotto Shoes 45/2,
> Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru, Karnataka
> --->  The Raymond Shop Opp. Mga Hospital, Marathalli Main Road Near Ring Road Junction, Bengaluru, Karnataka --->  chinnaswamy stadium
> banglore --->  fun cinemas cunningham road Banglore --->  Cant station
> banglore --->  Radhakrishna Theatre 25, 1st Main Rd, Mattdahally, RT
> Nagar, Bengaluru --->  Presidency School Near R T Nagar, HMT Layout,
> Bengaluru, Karnataka ---> 0 Distance of the route: 20m
>
> Maximum of the route distances: 26m

Body:
You should reduce vehicle maximum travel distance. currently you set it to 80.
and your routes distances are 20 and 26.

routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        80,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)


来源: stackexchange

问:
VB.NET 2005, Serial port, dispose problem, Windows CE
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

```<code>port.close()
port.dispose()
</code>```

And If I add this:

```<code>System.GC.collect()
</code>```

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?

答:
How long are you waiting between closing it and opening it? According to MSDN:

The best practice for any application
  is to wait for some amount of time
  after calling the Close method before
  attempting to call the Open method, as
  the port may not be closed instantly.

ContentLicense: CC BY-SA 3.0

Body:
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

port.close()
port.dispose()

And If I add this:

System.GC.collect()

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?


问:
How to convert MultipartFile( image ) to DataSource object
I have a Java Spring MVC web application.

In my Controller, I am getting a image that comes from a form as MultipartFile.
I need convert this MultipartFile to a javax.activation.DataSource.

答:
Try this.</p>

```<code>// add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this.

// add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());


问:
Traverse a path to reach a resource in diffrent directory

What would be the exact path to get my header-logo.png in header.vue file.

In header.vue file I tried background-image: url('./../resources/images/header-logo.png') or  background-image: url('./.././resources/images/header-logo.png') or some other options as well but it is not able to locate to the image.

If I can get explanation as well then it would be more helpful.

答:
```<code>background-image: url('../.././resources/images/header-logo.png')
</code>```

Should work, also the transpilation will map it so no need to point to your dis file.
Remember ./ is at the same level, where ../ takes you one up, you need to go up to src/ then up to account-app then into account-app/resources....

Body:
background-image: url('../.././resources/images/header-logo.png')

Should work, also the transpilation will map it so no need to point to your dis file.
Remember ./ is at the same level, where ../ takes you one up, you need to go up to src/ then up to account-app then into account-app/resources....


问:
Go to the next page
I have a problem regarding displaying the next page on a Website.
I use jQuery and want to Display the next Page if the Enter key is pressed?
How can I accomplish that.
The code below shows already what I have written.
Is there any method that will do fine?</p>

```<code><script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<script>

    $(document).on("keypress", "input", function(e){

        if(e.which == 13){

        }

    });

</script>
</code>```

答:
```<code>           window.location.replace("http://stackoverflow.com"); or

           window.location.href = "http://stackoverflow.com"; or

           window.open(url, '_blank');
</code>```

Title: Go to the next page


问:
How to extract similar element from a vector?
I have a vector which have following three strings

```<code>test <- c("www.example.com/topic/university-admission",
          "www.example.com/topic/school-admission",
          "www.example.com/college-admission")
</code>```

I want to extract all the element which have pattern like this "www.example.com/topic/"

One way is just looking at vector and extract as per the index location of that element.
But this will be challenging if vector has length of say 100.

Is there any way to do this using string pattern matching?

答:
```<code>test[startsWith(x = test, "www.example.com/topic/")]
# [1] "www.example.com/topic/university-admission" "www.example.com/topic/school-admission"
</code>```

Body:
I have a vector which have following three strings

test <- c("www.example.com/topic/university-admission",
          "www.example.com/topic/school-admission",
          "www.example.com/college-admission")

I want to extract all the element which have pattern like this "www.example.com/topic/"

One way is just looking at vector and extract as per the index location of that element.
But this will be challenging if vector has length of say 100.

Is there any way to do this using string pattern matching?


问:
SQLite datetime gives unreadable 7+ digit month and day
When I run the following query in my SQLite database, intended to make an unixtime datetime into a readable format:

```<code>select datetime('1483228802') from mytable limit 1;
</code>```

I get the following result:

```<code>4056230-49125276-18 12:00:00
</code>```

Clearly something is wrong. The day and month is unreadable, and the year and time is wrong as this python code to convert this unixtime show:

```<code>from datetime import datetime
ts = int("1483228802")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

>2017-01-01 00:00:02
</code>```

答:
You need to use the 'unixepoch' modifier. Without that the number is interpreted as Julian days.

```<code>SELECT datetime(1483228802, 'unixepoch');
</code>```

db<>fiddle

From "Date And Time Functions":

The "unixepoch" modifier (11) (...) causes the DDDDDDDDDD to be interpreted not as a Julian day number as it normally would be, but as Unix Time (...)

Body:
When I run the following query in my SQLite database, intended to make an unixtime datetime into a readable format:

select datetime('1483228802') from mytable limit 1;

I get the following result:

4056230-49125276-18 12:00:00

Clearly something is wrong. The day and month is unreadable, and the year and time is wrong as this python code to convert this unixtime show:

from datetime import datetime
ts = int("1483228802")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

>2017-01-01 00:00:02

Body:
You need to use the 'unixepoch' modifier. Without that the number is interpreted as Julian days.

SELECT datetime(1483228802, 'unixepoch');

db<>fiddle

From "Date And Time Functions":

The "unixepoch" modifier (11) (...) causes the DDDDDDDDDD to be interpreted not as a Julian day number as it normally would be, but as Unix Time (...)


问:
Reproducibility and performance in PyTorch
The documentation states:

Deterministic mode can have a performance impact, depending on your model.

My question is, what is meant by performance here. Processing speed or model quality (i.e. minimal loss)? In other words, when setting manual seeds and making the model perform in a deterministic way, does that cause longer training time until minimal loss is found, or is that minimal loss worse than when the model is non-deterministic?

For completeness' sake, I manually make the model deterministic by setting all of these properties:

```<code>def set_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(seed)
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
</code>```

答:
Performance refers to the run time; CuDNN has several ways of implementations,  when cudnn.deterministic is set to true, you're telling CuDNN that you only need the deterministic implementations (or what we believe they are). In a nutshell, when you are doing this, you should expect the same results on the CPU or the GPU on the same system when feeding the same inputs. Why would it affect the performance? CuDNN uses heuristics for the choice of the implementation. So, it actually depends on your model how CuDNN will behave; choosing it to be deterministic may affect the runtime because their could have been, let's say, faster way of choosing them at the same point of running.

Concerning your snippet, I do the exact seeding, it has been working good (in terms of reproducibility) for 100+ DL experiments.

Body:
The documentation states:

Deterministic mode can have a performance impact, depending on your model.

My question is, what is meant by performance here. Processing speed or model quality (i.e. minimal loss)? In other words, when setting manual seeds and making the model perform in a deterministic way, does that cause longer training time until minimal loss is found, or is that minimal loss worse than when the model is non-deterministic?

For completeness' sake, I manually make the model deterministic by setting all of these properties:

def set_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(seed)
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)


问:
Error when debug in android studio virtual device
when use debug in Android Emulator, i get the error:

java.lang.RuntimeException: java.lang.RuntimeException:
  java.io.FileNotFoundException:
  D:\Android\androiddtudio_project\vitrin-android\app\build\intermediates\instant_run_split_apk_resources\debug\instantRunSplitApkResourcesDebug\out\slice_6\resources_ap
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
    at
  java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)    at
  com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:149)
    at
  com.android.build.gradle.internal.transforms.InstantRunSliceSplitApkBuilder.transform(InstantRunSliceSplitApkBuilder.java:246)
    at
  com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at
  com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at
  com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.GeneratedMethodAccessor85.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)     at
  org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:47)
    at
  org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
    at
  org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.run(ExecuteActionsTaskExecuter.java:284)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
    at
  org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:273)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:258)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:67)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:145)
    at
  org.gradle.internal.execution.impl.steps.ExecuteStep.execute(ExecuteStep.java:49)
    at
  org.gradle.internal.execution.impl.steps.CancelExecutionStep.execute(CancelExecutionStep.java:34)
    at
  org.gradle.internal.execution.impl.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:69)
    at
  org.gradle.internal.execution.impl.steps.TimeoutStep.execute(TimeoutStep.java:49)
    at
  org.gradle.internal.execution.impl.steps.CatchExceptionStep.execute(CatchExceptionStep.java:33)
    at
  org.gradle.internal.execution.impl.steps.CreateOutputsStep.execute(CreateOutputsStep.java:50)
    at
  org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:43)
    at
  org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:29)
    at
  org.gradle.internal.execution.impl.steps.CacheStep.executeWithoutCache(CacheStep.java:134)
    at
  org.gradle.internal.execution.impl.steps.CacheStep.lambda$execute$3(CacheStep.java:83)
    at java.util.Optional.orElseGet(Optional.java:267)  at
  org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:82)
    at
  org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:36)
    at
  org.gradle.internal.execution.impl.steps.PrepareCachingStep.execute(PrepareCachingStep.java:33)
    at
  org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:38)
    at
  org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:23)
    at
  org.gradle.internal.execution.impl.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at
  org.gradle.internal.execution.impl.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)    at
  org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
    at
  org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
    at
  org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:34)
    at
  org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:91)
    at
  org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
    at
  org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:57)
    at
  org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:119)
    at
  org.gradle.api.internal.tasks.execution.ResolvePreviousStateExecuter.execute(ResolvePreviousStateExecuter.java:43)
    at
  org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
    at
  org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
    at
  org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:94)
    at
  org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:56)
    at
  org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:55)
    at
  org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at
  org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:67)
    at
  org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at
  org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:315)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:305)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
    at
  org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:101)
    at
  org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at
  org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at
  org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at
  org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at
  org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at
  org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at
  org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at
  org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at
  org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at
  org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at
  org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at
  org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at
  org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at
  org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at
  org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745) Caused by:
  java.lang.RuntimeException: java.io.FileNotFoundException:
  D:\Android\androiddtudio_project\vitrin-android\app\build\intermediates\instant_run_split_apk_resources\debug\instantRunSplitApkResourcesDebug\out\slice_6\resources_ap
    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1431)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at
  java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at
  java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at
  java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
  Caused by: java.io.FileNotFoundException:
  D:\Android\androiddtudio_project\vitrin-android\app\build\intermediates\instant_run_split_apk_resources\debug\instantRunSplitApkResourcesDebug\out\slice_6\resources_ap
    at
  com.android.build.gradle.internal.transforms.InstantRunSliceSplitApkBuilder.lambda$null$1(InstantRunSliceSplitApkBuilder.java:233)
    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
    ... 4 more

But when use phone, there is no problem.
i use clean project and rebuild project, but it did not work

答:
I once encountered this bug, might caused by variant problems. One of them is Instant Run.

I'll try to turn it off when I trigger this bug :

Double click Shift for quick search, type instant run

Select Instant Run (preference), it will open preference settings for you

There might be a check Enable Instant Run to hot swap..., uncheck it and try.

May or may not work, please let me know if it works.


问:
back button browser causes go to home page
I would like to understand more about how to capture if a user click on the back button of the browser, and what are the basic tecniques to handle it.

As an example of this do you know how to redirect (for instance) to the user to the home page if the back button is pressed?

答:
You can add a function to document onKeyPress:

```<code>document.onkeypress = myKeyPressHandler;
// NOTICE: IS NOT a good idea to change the behabiour of backspace
function myKeyPressHandler() {
    if (window.event && window.event.keyCode == 8) {
         // Handle backspace
         // I. E. Go to the home page
         window.home(); //
    }
}
</code>```

Actually changing the default beahabiour of backspace is not a good practice and you should avoid doing it unless you have very good reason or you will confuse your users.

Body:
You can add a function to document onKeyPress:

document.onkeypress = myKeyPressHandler;
// NOTICE: IS NOT a good idea to change the behabiour of backspace
function myKeyPressHandler() {
    if (window.event && window.event.keyCode == 8) {
         // Handle backspace
         // I. E. Go to the home page
         window.home(); //
    }
}

Actually changing the default beahabiour of backspace is not a good practice and you should avoid doing it unless you have very good reason or you will confuse your users.


问:
clear cached TFS client credentials
Please help me to clear TFS cached credentials using c# code. I'm using TFS API to access source code hosted by the Dev ops TFS server at https://dev.azure.com

sometimes (after domain password is changed) it raises 401 error when access the source code server. Please find code sample used to connect below:

```<code>    var u = "https://dev.azure.com/orgid";

    var vssCred = new VssClientCredentials();
    if (cacheCred)
        vssCred.Storage = new VssClientCredentialStorage(); // tried with storage and without

    Logger.Debug("getting vsts collection for url:{0}", u);
    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, vssCred);
    try
    {
        Logger.Debug("authenticating");

        tpc.Authenticate();
        tpc.GetService<VersionControlServer>();
</code>```

it uses Microsoft.TeamFoundationServer.ExtendedClient.15.131.1 and Microsoft.TeamFoundationServer.Client.15.131.1 packages.

I've tried to clear cached credentials using the code like below:

```<code>IEnumerable<string> ClearCachedTokens(VssCredentials cred, Uri address)
{
    if (cred == null) return null;
    var res = new Collection<string>();
    foreach (VssCredentialsType enumValue in Enum.GetValues(typeof(VssCredentialsType)))
        try
        {
            var token = cred.Storage.RetrieveToken(address, enumValue);
            if (token != null)
            {
                var tokenData = string.Join(";", token.Properties.Select(_ => string.Format("{0}={1}", _.Key, _.Value)));
                Logger.Debug("got token {0} {1}", enumValue, tokenData);
                cred.Storage.RemoveToken(address, token);
                res.Add(address.ToString());
            }
        }
        catch (Exception ec)
        {
            Logger.Warn("can't clear token type:{0} error:{1}", enumValue, ec.Message);
        }
    return res;
}
</code>```

but it does not return any entry and the error still persist.

However error is gone when I delete %appdata%Local\Microsoft\Team Foundation\7.0\Cache content and run tf.exe get command. It asks me for login and password and then 401 error is not shown any more when tpc.Authenticate(); is executed.

How can I clear cached credentials in the Cache folder using the TeamFoundationServer.Client or TeamFoundationServer.ExtendedClient API?

答: The credential might have been saved in the Credential Manager store (Control Panel\All Control Panel Items\Credential Manager) in the Generic Credentials group.

Title: clear cached TFS client credentials

Body:
Please help me to clear TFS cached credentials using c# code. I'm using TFS API to access source code hosted by the Dev ops TFS server at https://dev.azure.com

sometimes (after domain password is changed) it raises 401 error when access the source code server. Please find code sample used to connect below:

    var u = "https://dev.azure.com/orgid";

    var vssCred = new VssClientCredentials();
    if (cacheCred)
        vssCred.Storage = new VssClientCredentialStorage(); // tried with storage and without

    Logger.Debug("getting vsts collection for url:{0}", u);
    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, vssCred);
    try
    {
        Logger.Debug("authenticating");

        tpc.Authenticate();
        tpc.GetService<VersionControlServer>();

it uses Microsoft.TeamFoundationServer.ExtendedClient.15.131.1 and Microsoft.TeamFoundationServer.Client.15.131.1 packages.

I've tried to clear cached credentials using the code like below:

IEnumerable<string> ClearCachedTokens(VssCredentials cred, Uri address)
{
    if (cred == null) return null;
    var res = new Collection<string>();
    foreach (VssCredentialsType enumValue in Enum.GetValues(typeof(VssCredentialsType)))
        try
        {
            var token = cred.Storage.RetrieveToken(address, enumValue);
            if (token != null)
            {
                var tokenData = string.Join(";", token.Properties.Select(_ => string.Format("{0}={1}", _.Key, _.Value)));
                Logger.Debug("got token {0} {1}", enumValue, tokenData);
                cred.Storage.RemoveToken(address, token);
                res.Add(address.ToString());
            }
        }
        catch (Exception ec)
        {
            Logger.Warn("can't clear token type:{0} error:{1}", enumValue, ec.Message);
        }
    return res;
}

but it does not return any entry and the error still persist.

However error is gone when I delete %appdata%Local\Microsoft\Team Foundation\7.0\Cache content and run tf.exe get command. It asks me for login and password and then 401 error is not shown any more when tpc.Authenticate(); is executed.

How can I clear cached credentials in the Cache folder using the TeamFoundationServer.Client or TeamFoundationServer.ExtendedClient API?


问:
How to check if a List<List<int>> contains a List<int>
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

```<code>List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();
</code>```

I have already tried

```<code>MaterList.Contains, MasterList.Any
</code>```

but nothing is helping

e.g.

```<code>MasterList(1)=1,2,3
MasterList(2)=4,5
</code>```

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

答:
You can compare two list for equality like this:

```<code>bool AreListsIdentical(List<int> lhs, List<int> rhs)
{
    if(lhs.Count != rhs.Count) return false;

    return lhs.Zip(rhs, (l,r) => l == r).All(value => value);
}
</code>```

Now, using this function you can use the Linq functions to search for a matching list:

```<code>List<List<int>> masterList = new List<List<int>>();
List<int> childList = new List<int>(){1, 2, 3};
masterList.Add(childList);

var listToSearchFor = new List<int>{1,2,3};
masterList.Any(list => AreListsIdentical(list, listToSearchFor));
</code>```

Body:
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();

I have already tried

MaterList.Contains, MasterList.Any

but nothing is helping

e.g.

MasterList(1)=1,2,3
MasterList(2)=4,5

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

Body:
You can compare two list for equality like this:

bool AreListsIdentical(List<int> lhs, List<int> rhs)
{
    if(lhs.Count != rhs.Count) return false;

    return lhs.Zip(rhs, (l,r) => l == r).All(value => value);
}

Now, using this function you can use the Linq functions to search for a matching list:

List<List<int>> masterList = new List<List<int>>();
List<int> childList = new List<int>(){1, 2, 3};
masterList.Add(childList);

var listToSearchFor = new List<int>{1,2,3};
masterList.Any(list => AreListsIdentical(list, listToSearchFor));


问:
Can any one explain me how the size get allocated in the following case?
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

```<code>struct node
{
 int data;
 struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 16.

```<code>struct node
{
 int data;
};
</code>```

sizeof(struct node) it gives an output as 4.

```<code>struct node
{
struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 8.

```<code>struct node
{
int data;
struct node *next;
}*link;
</code>```

sizeof(link) is always 8, even if i add few more elements to structure.

答:
On your specific platform, it looks like an int has size 4 and a pointer has size 8.  It also looks like it wants to align pointers on an 8-byte boundary.

So if struct node just contains an int, then the its size is 4.  If it just contains a pointer, its size is 8.  If it contains both an int and a pointer, then it needs 12 bytes, but in order to maintain the alignment of the pointer, it pads the structure to a multiple of 8, resulting in a size of 16.

In your final example, you have link defined as a pointer to a struct node.  In this case, it doesn't matter what a struct node contains.  Since link is just a pointer, its size will always be 8.

Again, note that this is just a best guess for your platform.  None of this is guaranteed, and it can vary from one platform to another.

Body:
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

struct node
{
 int data;
 struct node *next;
};

sizeof(struct node) it gives an output as 16.

struct node
{
 int data;
};

sizeof(struct node) it gives an output as 4.

struct node
{
struct node *next;
};

sizeof(struct node) it gives an output as 8.

struct node
{
int data;
struct node *next;
}*link;

sizeof(link) is always 8, even if i add few more elements to structure.


问:
AWS Data Pipeline can't validate S3 Access [permission warning]
I am doing an evaluation of AWS database services to pick the most effective one, the objective is to load data from a json file from an S3 bucket into Redshift every 5 minutes.

I am currently trying to use AWS Data Pipeline for the automation of ETL. I have been following this AWS tutorial "Copy Data to Amazon Redshift Using the AWS Data Pipeline Console", all simple and clear.

https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-copydata-redshift-create.html

I set up a cluster on Redshift and a bucket on S3, created all the roles and policies required with all the permissions needed.

Now after creating the pipeline, and pressing Activate a warning comes up saying

Errors/Warnings:

```<code>Object:Ec2Instance
WARNING: Could not validate S3 Access for role. Please ensure role ('DataPipelineDefaultRole') has s3:Get*, s3:List*, s3:Put* and sts:AssumeRole permissions for DataPipeline.
</code>```

Now I am sure that my role and resource role have s3:Get*, s3:List*, s3:Put* and sts:AssumeRole

In fact they both have FullAccess to basically all the services I need.

DataPipelineDefaultRole policy:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "VisualEditor0",
        "Effect": "Allow",
        "Action": "iam:CreateServiceLinkedRole",
        "Resource": "*",
        "Condition": {
            "StringLike": {
                "iam:AWSServiceName": [
                    "elasticmapreduce.amazonaws.com",
                    "spot.amazonaws.com"
                ]
            }
        }
    },
    {
        "Sid": "VisualEditor1",
        "Effect": "Allow",
        "Action": [
            "ec2:AuthorizeSecurityGroupIngress",
            "sdb:Select*",
            "sqs:ReceiveMessage",
            "s3:Get*",
            "sqs:GetQueue*",
            "s3:CreateBucket",
            "sns:Unsubscribe",
            "s3:List*",
            "datapipeline:EvaluateExpression",
            "ec2:StartInstances",
            "dynamodb:DescribeTable",
            "sqs:Delete*",
            "iam:ListAttachedRolePolicies",
            "ec2:RevokeSecurityGroupEgress",
            "dynamodb:GetItem",
            "sns:Subscribe",
            "iam:ListRolePolicies",
            "s3:DeleteObject",
            "sdb:BatchPutAttributes",
            "iam:GetRole",
            "dynamodb:BatchGetItem",
            "redshift:DescribeClusterSecurityGroups",
            "ec2:CreateTags",
            "ec2:DeleteNetworkInterface",
            "ec2:RunInstances",
            "dynamodb:Scan",
            "rds:DescribeDBSecurityGroups",
            "ec2:StopInstances",
            "ec2:CreateNetworkInterface",
            "ec2:CancelSpotInstanceRequests",
            "cloudwatch:*",
            "sqs:PurgeQueue",
            "iam:GetRolePolicy",
            "dynamodb:UpdateTable",
            "ec2:RequestSpotInstances",
            "ec2:DeleteTags",
            "sns:ListTopics",
            "ec2:ModifyImageAttribute",
            "iam:PassRole",
            "sns:Publish",
            "ec2:DescribeNetworkInterfaces",
            "ec2:CreateSecurityGroup",
            "rds:DescribeDBInstances",
            "ec2:ModifyInstanceAttribute",
            "ec2:AuthorizeSecurityGroupEgress",
            "ec2:DetachNetworkInterface",
            "ec2:TerminateInstances",
            "iam:GetInstanceProfile",
            "sns:GetTopicAttributes",
            "datapipeline:DescribeObjects",
            "dynamodb:Query",
            "iam:ListInstanceProfiles",
            "ec2:Describe*",
            "ec2:DeleteSecurityGroup",
            "redshift:DescribeClusters",
            "sqs:CreateQueue",
            "elasticmapreduce:*",
            "s3:Put*"
        ],
        "Resource": "*"
    },
    {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": [
            "iam:PassRole",
            "s3:Get*",
            "s3:List*",
            "s3:Put*",
            "sts:AssumeRole"
        ],
        "Resource": [
            "arn:aws:iam::*:role/DataPipelineDefaultResourceRole",
            "arn:aws:iam::*:role/DataPipelineDefaultRole",
            "arn:aws:s3:::*/*"
        ]
    },
    {
        "Sid": "VisualEditor3",
        "Effect": "Allow",
        "Action": [
            "s3:Get*",
            "s3:List*",
            "s3:Put*"
        ],
        "Resource": "arn:aws:s3:::*"
    },
    {
        "Sid": "VisualEditor4",
        "Effect": "Allow",
        "Action": [
            "s3:Get*",
            "s3:List*",
            "s3:Put*"
        ],
        "Resource": "*"
    }
]
}
</code>```

DataPipelineDefaultResourceRole policy:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "cloudwatch:*",
            "datapipeline:*",
            "dynamodb:*",
            "ec2:Describe*",
            "elasticmapreduce:AddJobFlowSteps",
            "elasticmapreduce:Describe*",
            "elasticmapreduce:ListInstance*",
            "rds:Describe*",
            "redshift:DescribeClusters",
            "redshift:DescribeClusterSecurityGroups",
            "s3:*",
            "sdb:*",
            "sns:*",
            "sqs:*"
        ],
        "Resource": [
            "*"
        ]
    }
]
}
</code>```

I Have been looking into the issue for over a week, tried all the existing solutions, updated the Trust Relationship, recreated the Roles, kept the default roles, let Data Pipeline create new ones and checked the Security Group, still having the same issue.

After activating the pipeline and check the log Uri, I do find 2 folders Ec2Instance and RedshiftLoadActivity, in the Redshift log file there are only 2 lines, the other has more [INFO] describing the downloading of the jar and S3 file for the TaskRunner.

Among the logs There are [INFO] and these [WARN]:

Ec2Instance:

```<code>private.com.amazonaws.services.s3.internal.S3V4AuthErrorRetryStrategy: Attempting to re-send the request to mylogbucket.s3.eu-central-1.amazonaws.com with AWS V4 authentication. To avoid this warning in the future, please use region-specific endpoint to access buckets located in regions that require V4 signing.
</code>```

RedshiftLoadActivity:

```<code>private.com.amazonaws.services.s3.internal.S3V4AuthErrorRetryStrategy: Attempting to re-send the request to mylogbucket.s3.eu-central-1.amazonaws.com with AWS V4 authentication. To avoid this warning in the future, please use region-specific endpoint to access buckets located in regions that require V4 signing.
</code>```

The issue should be the roles and policies, yet I made sure Redshift and S3 bucket were not the problem since I tried using a COPY command on the Query Editor and it loaded the data as expected.

I am currently still stuck in that error and would love some suggestions to how I could possibly fix this problem.

548 [ERROR]
  (TaskRunnerService-resource:df-0539055_@Ec2Instance_2019-05-30T13:38:35-0)
  amazonaws.datapipeline.database.ConnectionFactory: Unable to establish
  connection to
  jdbc:postgresql://redshift-cluster-1.coykb9.eu-central-1.redshift.amazonaws.com:5439/db
  Connection refused. Check that the hostname and port are correct and
  that the postmaster is accepting TCP/IP connections

答:
Data pipeline uses EMR to spawn EC2 instances and complete the submitted task.

Check EC2 instance profile and EMR role of the EMR spawned by data pipeline.
Attach S3 access policy to EC2 instance profile role of EMR.

By default EC2 instance profile is DataPipelineDefaultResourceRole

For fixing

Error Unable to establish connection to
  jdbc:postgresql://redshift-cluster-1.coykb9.eu-central-1.redshift.amazonaws.com:5439/db
  Connection refused

Update your redshift security group Inbound rules to allow connection from 0.0.0.0/0. This means any machine over internet is allowed to connect using credentials.

Body:
I am doing an evaluation of AWS database services to pick the most effective one, the objective is to load data from a json file from an S3 bucket into Redshift every 5 minutes.

I am currently trying to use AWS Data Pipeline for the automation of ETL. I have been following this AWS tutorial "Copy Data to Amazon Redshift Using the AWS Data Pipeline Console", all simple and clear.

https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-copydata-redshift-create.html

I set up a cluster on Redshift and a bucket on S3, created all the roles and policies required with all the permissions needed.

Now after creating the pipeline, and pressing Activate a warning comes up saying

Errors/Warnings:

Object:Ec2Instance
WARNING: Could not validate S3 Access for role. Please ensure role ('DataPipelineDefaultRole') has s3:Get*, s3:List*, s3:Put* and sts:AssumeRole permissions for DataPipeline.

Now I am sure that my role and resource role have s3:Get*, s3:List*, s3:Put* and sts:AssumeRole

In fact they both have FullAccess to basically all the services I need.

DataPipelineDefaultRole policy:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "VisualEditor0",
        "Effect": "Allow",
        "Action": "iam:CreateServiceLinkedRole",
        "Resource": "*",
        "Condition": {
            "StringLike": {
                "iam:AWSServiceName": [
                    "elasticmapreduce.amazonaws.com",
                    "spot.amazonaws.com"
                ]
            }
        }
    },
    {
        "Sid": "VisualEditor1",
        "Effect": "Allow",
        "Action": [
            "ec2:AuthorizeSecurityGroupIngress",
            "sdb:Select*",
            "sqs:ReceiveMessage",
            "s3:Get*",
            "sqs:GetQueue*",
            "s3:CreateBucket",
            "sns:Unsubscribe",
            "s3:List*",
            "datapipeline:EvaluateExpression",
            "ec2:StartInstances",
            "dynamodb:DescribeTable",
            "sqs:Delete*",
            "iam:ListAttachedRolePolicies",
            "ec2:RevokeSecurityGroupEgress",
            "dynamodb:GetItem",
            "sns:Subscribe",
            "iam:ListRolePolicies",
            "s3:DeleteObject",
            "sdb:BatchPutAttributes",
            "iam:GetRole",
            "dynamodb:BatchGetItem",
            "redshift:DescribeClusterSecurityGroups",
            "ec2:CreateTags",
            "ec2:DeleteNetworkInterface",
            "ec2:RunInstances",
            "dynamodb:Scan",
            "rds:DescribeDBSecurityGroups",
            "ec2:StopInstances",
            "ec2:CreateNetworkInterface",
            "ec2:CancelSpotInstanceRequests",
            "cloudwatch:*",
            "sqs:PurgeQueue",
            "iam:GetRolePolicy",
            "dynamodb:UpdateTable",
            "ec2:RequestSpotInstances",
            "ec2:DeleteTags",
            "sns:ListTopics",
            "ec2:ModifyImageAttribute",
            "iam:PassRole",
            "sns:Publish",
            "ec2:DescribeNetworkInterfaces",
            "ec2:CreateSecurityGroup",
            "rds:DescribeDBInstances",
            "ec2:ModifyInstanceAttribute",
            "ec2:AuthorizeSecurityGroupEgress",
            "ec2:DetachNetworkInterface",
            "ec2:TerminateInstances",
            "iam:GetInstanceProfile",
            "sns:GetTopicAttributes",
            "datapipeline:DescribeObjects",
            "dynamodb:Query",
            "iam:ListInstanceProfiles",
            "ec2:Describe*",
            "ec2:DeleteSecurityGroup",
            "redshift:DescribeClusters",
            "sqs:CreateQueue",
            "elasticmapreduce:*",
            "s3:Put*"
        ],
        "Resource": "*"
    },
    {
        "Sid": "VisualEditor2",
        "Effect": "Allow",
        "Action": [
            "iam:PassRole",
            "s3:Get*",
            "s3:List*",
            "s3:Put*",
            "sts:AssumeRole"
        ],
        "Resource": [
            "arn:aws:iam::*:role/DataPipelineDefaultResourceRole",
            "arn:aws:iam::*:role/DataPipelineDefaultRole",
            "arn:aws:s3:::*/*"
        ]
    },
    {
        "Sid": "VisualEditor3",
        "Effect": "Allow",
        "Action": [
            "s3:Get*",
            "s3:List*",
            "s3:Put*"
        ],
        "Resource": "arn:aws:s3:::*"
    },
    {
        "Sid": "VisualEditor4",
        "Effect": "Allow",
        "Action": [
            "s3:Get*",
            "s3:List*",
            "s3:Put*"
        ],
        "Resource": "*"
    }
]
}

DataPipelineDefaultResourceRole policy:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "cloudwatch:*",
            "datapipeline:*",
            "dynamodb:*",
            "ec2:Describe*",
            "elasticmapreduce:AddJobFlowSteps",
            "elasticmapreduce:Describe*",
            "elasticmapreduce:ListInstance*",
            "rds:Describe*",
            "redshift:DescribeClusters",
            "redshift:DescribeClusterSecurityGroups",
            "s3:*",
            "sdb:*",
            "sns:*",
            "sqs:*"
        ],
        "Resource": [
            "*"
        ]
    }
]
}

I Have been looking into the issue for over a week, tried all the existing solutions, updated the Trust Relationship, recreated the Roles, kept the default roles, let Data Pipeline create new ones and checked the Security Group, still having the same issue.

After activating the pipeline and check the log Uri, I do find 2 folders Ec2Instance and RedshiftLoadActivity, in the Redshift log file there are only 2 lines, the other has more [INFO] describing the downloading of the jar and S3 file for the TaskRunner.

Among the logs There are [INFO] and these [WARN]:

Ec2Instance:

private.com.amazonaws.services.s3.internal.S3V4AuthErrorRetryStrategy: Attempting to re-send the request to mylogbucket.s3.eu-central-1.amazonaws.com with AWS V4 authentication. To avoid this warning in the future, please use region-specific endpoint to access buckets located in regions that require V4 signing.

RedshiftLoadActivity:

private.com.amazonaws.services.s3.internal.S3V4AuthErrorRetryStrategy: Attempting to re-send the request to mylogbucket.s3.eu-central-1.amazonaws.com with AWS V4 authentication. To avoid this warning in the future, please use region-specific endpoint to access buckets located in regions that require V4 signing.

The issue should be the roles and policies, yet I made sure Redshift and S3 bucket were not the problem since I tried using a COPY command on the Query Editor and it loaded the data as expected.

I am currently still stuck in that error and would love some suggestions to how I could possibly fix this problem.

548 [ERROR]
  (TaskRunnerService-resource:df-0539055_@Ec2Instance_2019-05-30T13:38:35-0)
  amazonaws.datapipeline.database.ConnectionFactory: Unable to establish
  connection to
  jdbc:postgresql://redshift-cluster-1.coykb9.eu-central-1.redshift.amazonaws.com:5439/db
  Connection refused. Check that the hostname and port are correct and
  that the postmaster is accepting TCP/IP connections


问:
How to send or passing state from siblings to siblings in react native?
I create an Boilerplate in react native. when i have parent and have to childs components and I want pasing state from child 1 to child 2

I've try send to parent then children2 but not working

This my Code
Parent

```<code>class WashingPackageMotor extends Component {
render() {
    return (
      <View style={styles.containerMain}>
        <Grid scrollable>
          <Section>
            <Block size="100%">
              <ComponentWashingPackage />
            </Block>
          </Section>
          <Section>
            <Block size="100%">
              <ComponentList />
            </Block>
          </Section>
        </Grid>
        <Grid>
          <Section>
            <Block size="100%">
              <ComponentBottom />
            </Block>
          </Section>
        </Grid>
      </View>
}
    );
  }
}

</code>```

Child 1 (Sibling one)

```<code>export default class ComponentList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            value: 0,
            amount: 0,
            v0: 0,
            v1: 0,
            collapsed: false
            // v5: 0,
            // v6: 0
        }
        this.amount = 0
    }
..........
..........
}

</code>```

Child 2 (Sibling two)

```<code>class ComponentBottom extends Component {
  render() {
    return (
      <Grid>
        <View style={styles.bottomView}>
          <View style={{ borderBottomColor: '#EEEEEE', borderBottomWidth:0.5}}/>
          <Section>
            <Block size="60%">
              <Text style={styles.textHarga}>Total Harga</Text>
              <Text style={styles.textPrice}>Rp 180.000</Text>
            </Block>
            <Block size="40%">
              <ButtonProcessDisabled onPress={() => this.props.navigation.navigate('OrderConfirmation')}/>
            </Block>
          </Section>
        </View>
      </Grid>
    )
  }
}
</code>```

And how to send state from Child 1 (Sibling 1) to Child 2 (Sibling2)

答:
Steps to get the functionality you wish (not suggested though rather use redux or context):

Parent:

```<code>class WashingPackageMotor extends Component {
    constructor(props) {
        super(props);
        this.state = {
            amount: "",
        }
    }

    update(amount) {
        this.setState({amount});
    }

    render() {
        return (
          <View style={styles.containerMain}>
            <Grid scrollable>
              <Section>
                <Block size="100%">
                  <ComponentWashingPackage />
                </Block>
              </Section>
              <Section>
                <Block size="100%">
                  <ComponentList
                     amount={this.state.amount}
                     updateAmount={amount => this.update(amount)}
                  />
                </Block>
              </Section>
            </Grid>
            <Grid>
              <Section>
                <Block size="100%">
                  <ComponentBottom
                    amount={this.state.amount}
                  />
                </Block>
              </Section>
            </Grid>
          </View>
    }
        );
      }
    }
</code>```

Child1:

whenever you want to update the state just call the function this.props.updateAmount(valueHere);

```<code>export default class ComponentList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            value: 0,
            amount: this.props.amount,
            v0: 0,
            v1: 0,
            collapsed: false
            // v5: 0,
            // v6: 0
        }
        this.amount = 0
    }
..........
..........
}
</code>```

child 2:

```<code>class ComponentBottom extends Component {
  constructor(props) {
    super(props);
    this.state = {
      amount: this.props.amount,
    };
  }
  render() {
    return (
      <Grid>
        <View style={styles.bottomView}>
          <View style={{ borderBottomColor: '#EEEEEE', borderBottomWidth:0.5}}/>
          <Section>
            <Block size="60%">
              <Text style={styles.textHarga}>Total Harga</Text>
              <Text style={styles.textPrice}>Rp 180.000</Text>
            </Block>
            <Block size="40%">
              <ButtonProcessDisabled onPress={() => this.props.navigation.navigate('OrderConfirmation')}/>
            </Block>
          </Section>
        </View>
      </Grid>
    )
  }
}
</code>```

NOTE: You will need to use componentWillReceiveProps() for react version older than 16.3 and for above you will need to use getDerivedStateFromProps to update the state based on the updated props.

Body:
I create an Boilerplate in react native. when i have parent and have to childs components and I want pasing state from child 1 to child 2

I've try send to parent then children2 but not working

This my Code
Parent

class WashingPackageMotor extends Component {
render() {
    return (
      <View style={styles.containerMain}>
        <Grid scrollable>

            <Block size="100%">
              <ComponentWashingPackage />
            </Block>

            <Block size="100%">
              <ComponentList />
            </Block>

        </Grid>
        <Grid>

            <Block size="100%">
              <ComponentBottom />
            </Block>

        </Grid>
      </View>
}
    );
  }
}

Child 1 (Sibling one)

export default class ComponentList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            value: 0,
            amount: 0,
            v0: 0,
            v1: 0,
            collapsed: false
            // v5: 0,
            // v6: 0
        }
        this.amount = 0
    }
..........
..........
}

Child 2 (Sibling two)

class ComponentBottom extends Component {
  render() {
    return (
      <Grid>
        <View style={styles.bottomView}>
          <View style={{ borderBottomColor: '#EEEEEE', borderBottomWidth:0.5}}/>

            <Block size="60%">
              <Text style={styles.textHarga}>Total Harga</Text>
              <Text style={styles.textPrice}>Rp 180.000</Text>
            </Block>
            <Block size="40%">
              <ButtonProcessDisabled onPress={() => this.props.navigation.navigate('OrderConfirmation')}/>
            </Block>

        </View>
      </Grid>
    )
  }
}

And how to send state from Child 1 (Sibling 1) to Child 2 (Sibling2)

Body:
Steps to get the functionality you wish (not suggested though rather use redux or context):

Parent:

class WashingPackageMotor extends Component {
    constructor(props) {
        super(props);
        this.state = {
            amount: "",
        }
    }

    update(amount) {
        this.setState({amount});
    }

    render() {
        return (
          <View style={styles.containerMain}>
            <Grid scrollable>
              <Section>
                <Block size="100%">
                  <ComponentWashingPackage />
                </Block>
              </Section>
              <Section>
                <Block size="100%">
                  <ComponentList
                     amount={this.state.amount}
                     updateAmount={amount => this.update(amount)}
                  />
                </Block>
              </Section>
            </Grid>
            <Grid>
              <Section>
                <Block size="100%">
                  <ComponentBottom
                    amount={this.state.amount}
                  />
                </Block>
              </Section>
            </Grid>
          </View>
    }
        );
      }
    }

Child1:

whenever you want to update the state just call the function this.props.updateAmount(valueHere);

export default class ComponentList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            value: 0,
            amount: this.props.amount,
            v0: 0,
            v1: 0,
            collapsed: false
            // v5: 0,
            // v6: 0
        }
        this.amount = 0
    }
..........
..........
}

child 2:

class ComponentBottom extends Component {
  constructor(props) {
    super(props);
    this.state = {
      amount: this.props.amount,
    };
  }
  render() {
    return (
      <Grid>
        <View style={styles.bottomView}>
          <View style={{ borderBottomColor: '#EEEEEE', borderBottomWidth:0.5}}/>
          <Section>
            <Block size="60%">
              <Text style={styles.textHarga}>Total Harga</Text>
              <Text style={styles.textPrice}>Rp 180.000</Text>
            </Block>
            <Block size="40%">
              <ButtonProcessDisabled onPress={() => this.props.navigation.navigate('OrderConfirmation')}/>
            </Block>
          </Section>
        </View>
      </Grid>
    )
  }
}

NOTE: You will need to use componentWillReceiveProps() for react version older than 16.3 and for above you will need to use getDerivedStateFromProps to update the state based on the updated props.


问:
How to verify that exception was thrown by mock method?
How to verify that exception was thrown by mock method in code below?

It simply throw exception on checking method without ending verify.

```<code>// import mockito

...

@Test
public void someTest() throws Exception {
    // reset and setup mock
    reset(mock);
    when(mock.getObj(Matchers.anyLong()))
        .thenReturn(new Obj());
    when(mock.save(any(Obj.class)))
        .thenThrow(new RuntimeException("Error!"));
    // work where mock is used (it throws no exceptions)
    work();
    // verify that exception on mock.save() was thrown
    // ! PROBLEM HERE: exception throws right here and verify doesn't end
    verify(mock, times(1)).save(any(Obj.class));
}
</code>```

UPD

work() - only sends message to Kafka-consumer (which is being tested) which works on embedded Kafka-server.

mock - mocks some object in consumer logic.

In this case, checking out the exception is an ADDITIONAL check for checking a certain branch of the consumer algorithm (other asserts not important (deleted): they checks that message was worked).

答:
I assume that "work" is throwing the RuntimeException?

If so, you could surround your work() method with a try catch, for example...

```<code>try {
    work();
    Assert.fail("Did not catch expected exception!");
} catch(RuntimeException ex) {
    // Expected
}

verify(mock, times(1)).save(any(Obj.class));
</code>```

If not, you may need to post the code under the test to let us see what is happening...

EDIT: Still not 100% sure what you mean, this test passes for me...

```<code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class Stack {
    @Mock
    private Mocked mock;

    @Test
    public void someTest() throws Exception {
        reset(mock);
        when(mock.getObj(Matchers.anyLong()))
                .thenReturn(new Obj());
        when(mock.save(any(Obj.class)))
                .thenThrow(new RuntimeException("Error!"));
        work();
        verify(mock, times(1)).save(any(Obj.class));
    }

    private void work() {
        Obj obj = mock.getObj(1234L);

        try {
            mock.save(obj);
        } catch(Exception ex) {
            // Bad things happened
        }
    }

    private interface Mocked {
        Obj getObj(long l);

        Obj save(Obj obj);
    }

    public static class Obj {

    }
}
</code>```

Body:
How to verify that exception was thrown by mock method in code below?

It simply throw exception on checking method without ending verify.

// import mockito

...

@Test
public void someTest() throws Exception {
    // reset and setup mock
    reset(mock);
    when(mock.getObj(Matchers.anyLong()))
        .thenReturn(new Obj());
    when(mock.save(any(Obj.class)))
        .thenThrow(new RuntimeException("Error!"));
    // work where mock is used (it throws no exceptions)
    work();
    // verify that exception on mock.save() was thrown
    // ! PROBLEM HERE: exception throws right here and verify doesn't end
    verify(mock, times(1)).save(any(Obj.class));
}

UPD

work() - only sends message to Kafka-consumer (which is being tested) which works on embedded Kafka-server.

mock - mocks some object in consumer logic.

In this case, checking out the exception is an ADDITIONAL check for checking a certain branch of the consumer algorithm (other asserts not important (deleted): they checks that message was worked).

Body:
I assume that "work" is throwing the RuntimeException?

If so, you could surround your work() method with a try catch, for example...

try {
    work();
    Assert.fail("Did not catch expected exception!");
} catch(RuntimeException ex) {
    // Expected
}

verify(mock, times(1)).save(any(Obj.class));

If not, you may need to post the code under the test to let us see what is happening...

EDIT: Still not 100% sure what you mean, this test passes for me...

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class Stack {
    @Mock
    private Mocked mock;

    @Test
    public void someTest() throws Exception {
        reset(mock);
        when(mock.getObj(Matchers.anyLong()))
                .thenReturn(new Obj());
        when(mock.save(any(Obj.class)))
                .thenThrow(new RuntimeException("Error!"));
        work();
        verify(mock, times(1)).save(any(Obj.class));
    }

    private void work() {
        Obj obj = mock.getObj(1234L);

        try {
            mock.save(obj);
        } catch(Exception ex) {
            // Bad things happened
        }
    }

    private interface Mocked {
        Obj getObj(long l);

        Obj save(Obj obj);
    }

    public static class Obj {

    }
}


问:
is there a way to modify part of file but keep reading the whole file
i have an input file for code system, the file contains symbols, integers, texts and float numbers.
and i have another file contains 2 columns.
no specific pattern for the file. some part are only text, other like array, other like columns.
my concern is i want to modify specific columns. i already have a code module to modify the columns. its reading from another file and change the values in another file.

the problem is, it is just reading the specific columns. it ignores the data before or after.

the data in file 1 like this:

```<code>       ag-109 4.778E-08
       am-241 3.525E-08
       am-243 1.157E-11
       cs-133 3.820E-06
       eu-151 1.546E-08
       eu-153 1.086E-07
       gd-155 1.018E-08
       mo-95 3.650E-06
       nd-143 3.300E-06
</code>```

the data looks like this in file 2:

```<code>        csas6
        gbc-32-keno6
        ce_v7_endf
        read composition
        ........
        (some text and numbers)
        .......
        h-1         10  0 0.0667    293   end
        zr          11  0  0.0432   293   end
        u-234       101 0 7.471e-06 293   end   #  the columns
        u-235       101 0 0.0005265 293   end   #  that i want
        u-236       101 0 0.0001285 293   end   # to change from
        u-238       101 0 0.02278   293   end   # another file
        np-237      101 0 1.018e-05 293   end
        pu-238      101 0 2.262e-06 293   end
        pu-239      101 0 0.000147  293   end
        pu-240      101 0 4.138e-05 293   end
        pu-241      101 0 2.028e-05 293   end
</code>```

columns are like 500 lines after that, its different columns i don't want to change it, then a text and arrays.

i already have another file with two columns, to change the column 1 and 4 from the above file.

Thanks to @Serge he helped for this module, it works for changing. but if there is text before the columns it does not work.

i want to stop changing when column 2 become '201'

after that i want to continue reading the file and save it in another file after modifying.

how i can modify the file and save the whole file after changing.

```<code>with open('file2') as f2, open('file1') as f1, open('out.txt','w') as fout:
    sep = re.compile(r'\s+')    # compile the separator for re
    while True:
        # read a line from each file
        try:
            line1 = next(f1)
            line2 = next(f2)
        except StopIteration:
            break                # stop processing on end of any file

        # split lines in fields
        fields1 = sep.split(line1.strip())
        fields2 = sep.split(line2.strip())

        if fields2[1] == '201':
            break                # stop processing if past 101

        # replace fields and write a line on the output file
        fields2[0] = fields1[0]
        fields2[3] = fields1[1]
        fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))
</code>```

the expected results should be similar to this:

```<code>        csas6
        gbc-32-keno6
        ce_v7_endf
        read composition
        ........
        (some text and numbers)
        .......
        ag-109      101 0 4.778E-08 293   end
        am-241      101 0 3.525E-08 293   end
        am-243      101 0 1.157E-11 293   end
        cs-133      101 0 3.820E-06 293   end
        eu-151      101 0 1.546E-08 293   end
        eu-153      101 0 1.086E-07 293   end
        gd-155      101 0 1.018E-08  293   end
        mo-95       101 0 3.650E-06 293   end
        nd-143      101 0 3.300E-06 293   end
        ............ #( another columns stops when column 2 ='201'
        ...............
        # mixture of text, arrays numbers....
</code>```

答:
Add another while cycle without if condition in the end, to iterate to end file,
smth like this:</p>

```<code>with open('file2') as f2, open('file1') as f1, open('out.txt', 'w') as fout:
sep = re.compile(r'\s+')    # compile the separator for re
while True:
    # read a line from each file
    try:
        line1 = next(f1)
        line2 = next(f2)
    except StopIteration:
        break                # stop processing on end of any file

    # split lines in fields
    fields1 = sep.split(line1.strip())
    fields2 = sep.split(line2.strip())

    if fields2[1] == '201':
        break                # stop processing if past 101

    # replace fields and write a line on the output file
    fields2[0] = fields1[0]
    fields2[3] = fields1[1]
    fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))
while True:
    # read a line from each file
    try:
        line1 = next(f1)
        line2 = next(f2)
    except StopIteration:
        break                # stop processing on end of any file

    # split lines in fields
    fields1 = sep.split(line1.strip())
    fields2 = sep.split(line2.strip())

    # if fields2[1] == '201':
    #     break                # stop processing if past 101

    # replace fields and write a line on the output file
    fields2[0] = fields1[0]
    fields2[3] = fields1[1]
    fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))
</code>```

Body:
i have an input file for code system, the file contains symbols, integers, texts and float numbers.
and i have another file contains 2 columns.
no specific pattern for the file. some part are only text, other like array, other like columns.
my concern is i want to modify specific columns. i already have a code module to modify the columns. its reading from another file and change the values in another file.

the problem is, it is just reading the specific columns. it ignores the data before or after.

the data in file 1 like this:

       ag-109 4.778E-08
       am-241 3.525E-08
       am-243 1.157E-11
       cs-133 3.820E-06
       eu-151 1.546E-08
       eu-153 1.086E-07
       gd-155 1.018E-08
       mo-95 3.650E-06
       nd-143 3.300E-06

the data looks like this in file 2:

        csas6
        gbc-32-keno6
        ce_v7_endf
        read composition
        ........
        (some text and numbers)
        .......
        h-1         10  0 0.0667    293   end
        zr          11  0  0.0432   293   end
        u-234       101 0 7.471e-06 293   end   #  the columns
        u-235       101 0 0.0005265 293   end   #  that i want
        u-236       101 0 0.0001285 293   end   # to change from
        u-238       101 0 0.02278   293   end   # another file
        np-237      101 0 1.018e-05 293   end
        pu-238      101 0 2.262e-06 293   end
        pu-239      101 0 0.000147  293   end
        pu-240      101 0 4.138e-05 293   end
        pu-241      101 0 2.028e-05 293   end

columns are like 500 lines after that, its different columns i don't want to change it, then a text and arrays.

i already have another file with two columns, to change the column 1 and 4 from the above file.

Thanks to @Serge he helped for this module, it works for changing. but if there is text before the columns it does not work.

i want to stop changing when column 2 become '201'

after that i want to continue reading the file and save it in another file after modifying.

how i can modify the file and save the whole file after changing.

with open('file2') as f2, open('file1') as f1, open('out.txt','w') as fout:
    sep = re.compile(r'\s+')    # compile the separator for re
    while True:
        # read a line from each file
        try:
            line1 = next(f1)
            line2 = next(f2)
        except StopIteration:
            break                # stop processing on end of any file

        # split lines in fields
        fields1 = sep.split(line1.strip())
        fields2 = sep.split(line2.strip())

        if fields2[1] == '201':
            break                # stop processing if past 101

        # replace fields and write a line on the output file
        fields2[0] = fields1[0]
        fields2[3] = fields1[1]
        fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))

the expected results should be similar to this:

        csas6
        gbc-32-keno6
        ce_v7_endf
        read composition
        ........
        (some text and numbers)
        .......
        ag-109      101 0 4.778E-08 293   end
        am-241      101 0 3.525E-08 293   end
        am-243      101 0 1.157E-11 293   end
        cs-133      101 0 3.820E-06 293   end
        eu-151      101 0 1.546E-08 293   end
        eu-153      101 0 1.086E-07 293   end
        gd-155      101 0 1.018E-08  293   end
        mo-95       101 0 3.650E-06 293   end
        nd-143      101 0 3.300E-06 293   end
        ............ #( another columns stops when column 2 ='201'
        ...............
        # mixture of text, arrays numbers....

Body:
Add another while cycle without if condition in the end, to iterate to end file,
smth like this:

with open('file2') as f2, open('file1') as f1, open('out.txt', 'w') as fout:
sep = re.compile(r'\s+')    # compile the separator for re
while True:
    # read a line from each file
    try:
        line1 = next(f1)
        line2 = next(f2)
    except StopIteration:
        break                # stop processing on end of any file

    # split lines in fields
    fields1 = sep.split(line1.strip())
    fields2 = sep.split(line2.strip())

    if fields2[1] == '201':
        break                # stop processing if past 101

    # replace fields and write a line on the output file
    fields2[0] = fields1[0]
    fields2[3] = fields1[1]
    fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))
while True:
    # read a line from each file
    try:
        line1 = next(f1)
        line2 = next(f2)
    except StopIteration:
        break                # stop processing on end of any file

    # split lines in fields
    fields1 = sep.split(line1.strip())
    fields2 = sep.split(line2.strip())

    # if fields2[1] == '201':
    #     break                # stop processing if past 101

    # replace fields and write a line on the output file
    fields2[0] = fields1[0]
    fields2[3] = fields1[1]
    fout.write(' {}      {}  {}  {}  {}   {} \n'.format(*fields2))


问:
UrlRewriter.net exclusive regex rules
I am trying to add some rewrite rules using UrlRewriter.net to my ASP.NET web app. The problem is that I am a Regex newbie, and provided examples are pretty elementary.

My question is: how do I differentiate urls which contain GET query parameters?

I.e., if I add this rule:

```<code><rewrite url="~/([.+])" to="~/$1.aspx" />
</code>```

It will rewrite www.example.com/products to www.example.com/products.aspx, but it will also rewrite www.example.com/products?id=1 to www.example.com/products?id=1.aspx.

Problem actually only happens when using a login control, since it creates an url similar to www.example.com/login?returnUrl=/members, and I am not sure how to rewrite it.

What I would like is:

to rewrite www.ex.com/test to www.ex.com/test.aspx, and

to rewrite www.ex.com/test?page=dummy to www.ex.com/test.aspx?page=dummy.aspx

Thanks a lot!

[edit] And btw I still haven't figured how to turn on console debugging for UrlRewriter. I have added the "register logger" section to the config file, but VS output windows shows nothing. That would be helpful, also.

答:
Use the following regex for the match:

```"~/([^\?]+)(.*)?"```

This way you match everything until the question mark - one or more chars that aren't a question mark.

Then $1 holds the path part, and $2 everything from the "?" until the end of the URL.

Notice the question mark after the second grouping parentheses - this means that you don't require that part, so www.ex.com/test will also work.

Title: UrlRewriter.net exclusive regex rules

Body:
I am trying to add some rewrite rules using UrlRewriter.net to my ASP.NET web app. The problem is that I am a Regex newbie, and provided examples are pretty elementary.

My question is: how do I differentiate urls which contain GET query parameters?

I.e., if I add this rule:

<rewrite url="~/([.+])" to="~/$1.aspx" />

It will rewrite www.example.com/products to www.example.com/products.aspx, but it will also rewrite www.example.com/products?id=1 to www.example.com/products?id=1.aspx.

Problem actually only happens when using a login control, since it creates an url similar to www.example.com/login?returnUrl=/members, and I am not sure how to rewrite it.

What I would like is:

to rewrite www.ex.com/test to www.ex.com/test.aspx, and

to rewrite www.ex.com/test?page=dummy to www.ex.com/test.aspx?page=dummy.aspx

Thanks a lot!

[edit] And btw I still haven't figured how to turn on console debugging for UrlRewriter. I have added the "register logger" section to the config file, but VS output windows shows nothing. That would be helpful, also.

Body:
Use the following regex for the match:

"~/([^\?]+)(.*)?"

This way you match everything until the question mark - one or more chars that aren't a question mark.

Then $1 holds the path part, and $2 everything from the "?" until the end of the URL.

Notice the question mark after the second grouping parentheses - this means that you don't require that part, so www.ex.com/test will also work.