问:
Replace Cookie Authentication Handler Scheme Options at Runtime
If I add cookie authentication to my ASP.Net core application with cookie authentication options using the native dependency injection container. How then can I replace the authentication options at run-time, after startup? For example, if I want to change the cookie expiration while the app is running. I cannot figure out how to replace both the authentication handler with its options in order to affect the change.

Code at startup to add authentication:

```<code>public static IServiceCollection ConfigureOAuth(this IServiceCollection services)
{
    var appSettings = services.BuildServiceProvider().GetService<IOptions<AppSettings>>();

    return services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
    {
        o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
    })
    .Services;
}
</code>```

Code at run-time to replace authentication:

```<code>/// <summary>
/// Replace authentication options with new ones read from configuration.
/// 1). Remove old services
/// 2.) Reload the configuration
/// 3.) Add the authentication scheme with options read from the latest configuration
/// </summary>
private static void ReplaceServices(IServiceCollection services, IHostingEnvironment env)
{
    ClearServices(services);

    services.Configure<AppSettings>(StartupConfiguration.BuildConfigurationRoot(env).GetSection("App"));

    var provider = services.BuildServiceProvider();
    var appSettings = provider.GetService<IOptions<AppSettings>>();

    services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
    services.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
    {
        o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
    });
}

/// <summary>
/// Clear stale dependencies: application settings configured from appsettings.json,
/// authentication options and cookie authentication handler and options
/// </summary>
private static void ClearServices(IServiceCollection services)
{
    var staleTypes = new List<Type>
    {
        typeof(IConfigureOptions<AppSettings>),
        typeof(IConfigureOptions<AuthenticationOptions>),
        typeof(IPostConfigureOptions<CookieAuthenticationOptions>),
        typeof(IConfigureOptions<CookieAuthenticationOptions>),
        typeof(CookieAuthenticationHandler)
    };

    foreach (var staleType in staleTypes)
    {
        var staleService = services.FirstOrDefault(s => s.ServiceType.Equals(staleType));
        services.Remove(staleService);
    }
}
</code>```

答:
Asp.net core native configuration reloading can be a bit flaky. If services depend on application settings that change at run-time, you don't have to inject those settings as IOptions at startup. An alternative way would be to write your settings provider which reloads a cached copy of the settings when an event notification is received from file system watcher. This approach eliminates the need to make configuration a DI service and you no longer need to depend on the reload token. The flow would go as follows:

Create a configuration provider service that encapsulates reading and storing of the apps settings. On init, it reads appsettings.json and caches an instance of IConfigurationRoot

Create another service to encapsulate watching the file system for changes to the app settings. If it changed, notify the configuration provider using a simple pub/sub pattern with a FileChangeEvent. The config provider can update the config root and then trigger a ConfigChangeEvent once the config is refreshed.

Any services they rely on live configuration, such as authentication options, can subscribe to the ConfigChangeEvent and update its settings based on what section it needs from the config root.

The key here is creating an options service that an authentication handler can successfully use and always has the live value. To do this, you need to implement an IOptionsMonitor.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddSingleton<IOptionsMonitor<CookieAuthenticationOptions>, CookieAuthenticationConfigurator>()
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
}
</code>```

The IOptionsMonitor implemenation:

```<code>{
    internal class CookieAuthenticationConfigurator : IOptionsMonitor<CookieAuthenticationOptions>
    {
        private readonly FileConfigurationBuilder ConfigProvider;
        private readonly IHostingEnvironment Environment;
        private readonly IDataProtectionProvider DataProtectionProvider;
        private readonly IMessageHub Hub;

        public CookieAuthenticationConfigurator(FileConfigurationBuilder configProvider, IDataProtectionProvider dataProtectionProvider, IMessageHub hub, IHostingEnvironment environment)
        {
            ConfigProvider = configProvider;
            Environment = environment;
            DataProtectionProvider = dataProtectionProvider;
            Hub = hub;
            Initialize();
        }

        private void Initialize()
        {
            Hub.Subscribe<ConfigurationChangeEvent>(_ =>
            {
                Build();
            });

            Build();
        }

        private void Build()
        {
            var hostOptions = ConfigProvider.Get<HostOptions>("HostOptions");
            options = new CookieAuthenticationOptions
            {
                ExpireTimeSpan = TimeSpan.FromHours(hostOptions.SessionLifespanHours)
            };
        }

        private CookieAuthenticationOptions options;

        public CookieAuthenticationOptions CurrentValue => options;

        public CookieAuthenticationOptions Get(string name)
        {
            PostConfigureCookieAuthenticationOptions op = new PostConfigureCookieAuthenticationOptions(DataProtectionProvider);
            op.PostConfigure(name, options);
            return options;
        }

        public IDisposable OnChange(Action<CookieAuthenticationOptions, string> listener)
        {
            throw new NotImplementedException();
        }
    }
}
</code>```

Body:
If I add cookie authentication to my ASP.Net core application with cookie authentication options using the native dependency injection container. How then can I replace the authentication options at run-time, after startup? For example, if I want to change the cookie expiration while the app is running. I cannot figure out how to replace both the authentication handler with its options in order to affect the change.

Code at startup to add authentication:

public static IServiceCollection ConfigureOAuth(this IServiceCollection services)
{
    var appSettings = services.BuildServiceProvider().GetService<IOptions<AppSettings>>();

    return services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
    {
        o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
    })
    .Services;
}

Code at run-time to replace authentication:

///
/// Replace authentication options with new ones read from configuration.
/// 1). Remove old services
/// 2.) Reload the configuration
/// 3.) Add the authentication scheme with options read from the latest configuration
///
private static void ReplaceServices(IServiceCollection services, IHostingEnvironment env)
{
    ClearServices(services);

    services.Configure<AppSettings>(StartupConfiguration.BuildConfigurationRoot(env).GetSection("App"));

    var provider = services.BuildServiceProvider();
    var appSettings = provider.GetService<IOptions<AppSettings>>();

    services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
    services.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
    {
        o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
    });
}

///
/// Clear stale dependencies: application settings configured from appsettings.json,
/// authentication options and cookie authentication handler and options
///
private static void ClearServices(IServiceCollection services)
{
    var staleTypes = new List<Type>
    {
        typeof(IConfigureOptions<AppSettings>),
        typeof(IConfigureOptions<AuthenticationOptions>),
        typeof(IPostConfigureOptions<CookieAuthenticationOptions>),
        typeof(IConfigureOptions<CookieAuthenticationOptions>),
        typeof(CookieAuthenticationHandler)
    };

    foreach (var staleType in staleTypes)
    {
        var staleService = services.FirstOrDefault(s => s.ServiceType.Equals(staleType));
        services.Remove(staleService);
    }
}

Body:
Asp.net core native configuration reloading can be a bit flaky. If services depend on application settings that change at run-time, you don't have to inject those settings as IOptions at startup. An alternative way would be to write your settings provider which reloads a cached copy of the settings when an event notification is received from file system watcher. This approach eliminates the need to make configuration a DI service and you no longer need to depend on the reload token. The flow would go as follows:

Create a configuration provider service that encapsulates reading and storing of the apps settings. On init, it reads appsettings.json and caches an instance of IConfigurationRoot

Create another service to encapsulate watching the file system for changes to the app settings. If it changed, notify the configuration provider using a simple pub/sub pattern with a FileChangeEvent. The config provider can update the config root and then trigger a ConfigChangeEvent once the config is refreshed.

Any services they rely on live configuration, such as authentication options, can subscribe to the ConfigChangeEvent and update its settings based on what section it needs from the config root.

The key here is creating an options service that an authentication handler can successfully use and always has the live value. To do this, you need to implement an IOptionsMonitor.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddSingleton<IOptionsMonitor<CookieAuthenticationOptions>, CookieAuthenticationConfigurator>()
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
}

The IOptionsMonitor implemenation:

{
    internal class CookieAuthenticationConfigurator : IOptionsMonitor<CookieAuthenticationOptions>
    {
        private readonly FileConfigurationBuilder ConfigProvider;
        private readonly IHostingEnvironment Environment;
        private readonly IDataProtectionProvider DataProtectionProvider;
        private readonly IMessageHub Hub;

        public CookieAuthenticationConfigurator(FileConfigurationBuilder configProvider, IDataProtectionProvider dataProtectionProvider, IMessageHub hub, IHostingEnvironment environment)
        {
            ConfigProvider = configProvider;
            Environment = environment;
            DataProtectionProvider = dataProtectionProvider;
            Hub = hub;
            Initialize();
        }

        private void Initialize()
        {
            Hub.Subscribe<ConfigurationChangeEvent>(_ =>
            {
                Build();
            });

            Build();
        }

        private void Build()
        {
            var hostOptions = ConfigProvider.Get<HostOptions>("HostOptions");
            options = new CookieAuthenticationOptions
            {
                ExpireTimeSpan = TimeSpan.FromHours(hostOptions.SessionLifespanHours)
            };
        }

        private CookieAuthenticationOptions options;

        public CookieAuthenticationOptions CurrentValue => options;

        public CookieAuthenticationOptions Get(string name)
        {
            PostConfigureCookieAuthenticationOptions op = new PostConfigureCookieAuthenticationOptions(DataProtectionProvider);
            op.PostConfigure(name, options);
            return options;
        }

        public IDisposable OnChange(Action<CookieAuthenticationOptions, string> listener)
        {
            throw new NotImplementedException();
        }
    }
}


来源: stackexchange

问:
Get screen width and height in Android
How can I get the screen width and height and use this value in:</p>

```<code>@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
        game.findViewById(R.id.flag).getHeight());
}
</code>```

答:
Full way to do it, that returns the true resolution (including when the user has changed the resolution) is to use "getRealSize".

I've noticed that all other available functions, including the ones the docs say to use instead of this - have some cases that the result is smaller.

Here's the code to do it:

```<code>            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point size = new Point();
            wm.getDefaultDisplay().getRealSize(size);
            final int width = size.x, height = size.y;
</code>```

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

```<code>/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val config = context.resources.configuration
    val rotation = windowManager.defaultDisplay.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Configuration.ORIENTATION_LANDSCAPE
    else
        Configuration.ORIENTATION_PORTRAIT
}

/**
 * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
    val screenNaturalOrientation = getScreenNaturalOrientation(context)
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val point = Point()
    wm.defaultDisplay.getRealSize(point)
    val currentOrientation = context.resources.configuration.orientation
    if (currentOrientation == screenNaturalOrientation)
        return point
    else return Point(point.y, point.x)
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get screen width and height in Android

Body:
How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
        game.findViewById(R.id.flag).getHeight());
}

Body:
Full way to do it, that returns the true resolution (including when the user has changed the resolution) is to use "getRealSize".

I've noticed that all other available functions, including the ones the docs say to use instead of this - have some cases that the result is smaller.

Here's the code to do it:

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point size = new Point();
            wm.getDefaultDisplay().getRealSize(size);
            final int width = size.x, height = size.y;

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val config = context.resources.configuration
    val rotation = windowManager.defaultDisplay.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Configuration.ORIENTATION_LANDSCAPE
    else
        Configuration.ORIENTATION_PORTRAIT
}

/**
 * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
    val screenNaturalOrientation = getScreenNaturalOrientation(context)
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val point = Point()
    wm.defaultDisplay.getRealSize(point)
    val currentOrientation = context.resources.configuration.orientation
    if (currentOrientation == screenNaturalOrientation)
        return point
    else return Point(point.y, point.x)
}


问:
Random high content download time in chrome?
We have an API which randomly takes high content download time in chrome, It works fine always in firefox and takes an only few ms. The response size is 20kb uncompressed and 4kb compressed. The same request also works fine using curl.

Things that we have tried:

Disabling If-None-Match header to disable cache response from the browser.

Trying various compressions (gzip, deflate, br).

Disabling compression.

Disabling all chrome extensions.

The same request works fine sometimes on chrome but randomly returns very high content download time.

We are unable to understand the root cause of this issue. What are the other things we can try to minimize this time?

I made three requests here and the 3rd one took the most time (before the last spike). CPU does not seem to be maxing out for a longer period of time. Most of the time is idle time.

Also, When replaying the call using Replay XHR menu, the Content download period drops from 2s to 200 ms.

答:
Are you by chance trying to implement infinite scrolling? If you are, try dragging the scroll bar instead of using the mouse wheel. For some reason, Chrome seems to struggle with mouse scroll events. If the scroll bar worked just fine, keep reading.

This post provides a detailed walkthrough of someone experiencing something similar - https://github.com/TryGhost/Ghost/issues/7934

I had attached a watcher on the scroll event which would trigger an AJAX request. I had throttled the request and could see that only 1 was being sent. I watched my dev server return the response within a few ms but there would be a 2 second delay in chrome. No render, no api calls, no and scripts executing. But the "Content Download" would take 3 seconds for 14kb. No other browser had this issue.

I stumbled upon suggestions that using requestAnimationFrame instead of setTimeout would solve the problem. That approach seems that approach works when the "Waiting" or green is significant, not so much for the "Content Download" or blue.

After hours of digging, I tried conditionally calling e.preventDefault() on the mousewheel event and to my amazement, it worked.

A few things to note:

1) I did not use the mousewheel event to make the api call. I used the scroll event along with throttling.

2) The mousewheel event is non-standard and should not be used. See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel

3) BUT in this case, you have to watch and handle the mousewheel event because of chrome. Other browsers ignore the event if they don't support it and I have yet to see it cause an issue in another browser.

4) You don't want to call preventDefault() every time because that disables scrolling with a mouse :) You only want to call it when deltaY is 1 if you are using vertical scroll. You can see from the attached image that deltaY is 1 when you basically can't scroll anymore. the mousewheel event is fired even though the page cannot scroll. As a side note, deltaX is -0 when you are scrolling vertically and deltaY is -0 when scrolling horizontally.

My solution:

```<code>window.addEventListener("mousewheel", (e) => {
    if (e.deltaY === 1) {
        e.preventDefault();
    }
})
</code>```

That has been the only solution that I've seen work and I haven't seen it mentioned or discussed elsewhere. I hope that helps.

console log of mousewheel event

ContentLicense: CC BY-SA 3.0

Body:
Are you by chance trying to implement infinite scrolling? If you are, try dragging the scroll bar instead of using the mouse wheel. For some reason, Chrome seems to struggle with mouse scroll events. If the scroll bar worked just fine, keep reading.

This post provides a detailed walkthrough of someone experiencing something similar - https://github.com/TryGhost/Ghost/issues/7934

I had attached a watcher on the scroll event which would trigger an AJAX request. I had throttled the request and could see that only 1 was being sent. I watched my dev server return the response within a few ms but there would be a 2 second delay in chrome. No render, no api calls, no and scripts executing. But the "Content Download" would take 3 seconds for 14kb. No other browser had this issue.

I stumbled upon suggestions that using requestAnimationFrame instead of setTimeout would solve the problem. That approach seems that approach works when the "Waiting" or green is significant, not so much for the "Content Download" or blue.

After hours of digging, I tried conditionally calling e.preventDefault() on the mousewheel event and to my amazement, it worked.

A few things to note:

1) I did not use the mousewheel event to make the api call. I used the scroll event along with throttling.

2) The mousewheel event is non-standard and should not be used. See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel

3) BUT in this case, you have to watch and handle the mousewheel event because of chrome. Other browsers ignore the event if they don't support it and I have yet to see it cause an issue in another browser.

4) You don't want to call preventDefault() every time because that disables scrolling with a mouse :) You only want to call it when deltaY is 1 if you are using vertical scroll. You can see from the attached image that deltaY is 1 when you basically can't scroll anymore. the mousewheel event is fired even though the page cannot scroll. As a side note, deltaX is -0 when you are scrolling vertically and deltaY is -0 when scrolling horizontally.

My solution:

window.addEventListener("mousewheel", (e) => {
    if (e.deltaY === 1) {
        e.preventDefault();
    }
})

That has been the only solution that I've seen work and I haven't seen it mentioned or discussed elsewhere. I hope that helps.

console log of mousewheel event


问:
Angular orderBy:'timestamp' putting things in the wrong order

What I want to do:

Take an array of objects, each object with object.timestamp in milliseconds, and order them from newest to oldest.

The problem:

Angular's orderBy doesn't seem to be putting things in the correct order. The following timestamps are getting put in the following order:

1416187808218 - // Nov/16/2014 5:30:PM

1416187881192 - // Nov/16/2014 5:31:PM

1416189118263 - // Nov/16/2014 5:51:PM

1416189138827 - // Nov/16/2014 5:52:PM

1416130064119 - // Nov/16/2014 1:27:AM

The correct/desired order is obviously be:

1416189138827 - // Nov/16/2014 5:52:PM

1416189118263 - // Nov/16/2014 5:51:PM

1416187881192 - // Nov/16/2014 5:31:PM

1416187808218 - // Nov/16/2014 5:30:PM

1416130064119 - // Nov/16/2014 1:27:AM

So it's going 4, 3, 2, 1, 5 when it should be, obviously, 1, 2, 3, 4, 5

The relavent code:

html:

```<code><div class="cardWrapper" ng-repeat="card in cards | orderBy:'timestamp'">
  various child elements
</div>
</code>```

javascript:

```<code>scope.cards = homeData.get().cards; // returns an array of objects
// ^this^ becomes something similar to
scope.cards = [
  {text: 'some text...', timestamp: 1416189138827, other: 'data'},
  {text: 'some text...', timestamp: 1416187881192, other: 'data'}
  //etc...
];
</code>```

答: Is your timestamp coming through your API as a string and not an integer? I realize here it looks fine.</p>

Body:
What I want to do:

Take an array of objects, each object with object.timestamp in milliseconds, and order them from newest to oldest.

The problem:

Angular's orderBy doesn't seem to be putting things in the correct order. The following timestamps are getting put in the following order:

1416187808218 - // Nov/16/2014 5:30:PM

1416187881192 - // Nov/16/2014 5:31:PM

1416189118263 - // Nov/16/2014 5:51:PM

1416189138827 - // Nov/16/2014 5:52:PM

1416130064119 - // Nov/16/2014 1:27:AM

The correct/desired order is obviously be:

1416189138827 - // Nov/16/2014 5:52:PM

1416189118263 - // Nov/16/2014 5:51:PM

1416187881192 - // Nov/16/2014 5:31:PM

1416187808218 - // Nov/16/2014 5:30:PM

1416130064119 - // Nov/16/2014 1:27:AM

So it's going 4, 3, 2, 1, 5 when it should be, obviously, 1, 2, 3, 4, 5

The relavent code:

html:

  various child elements

javascript:

scope.cards = homeData.get().cards; // returns an array of objects
// ^this^ becomes something similar to
scope.cards = [
  {text: 'some text...', timestamp: 1416189138827, other: 'data'},
  {text: 'some text...', timestamp: 1416187881192, other: 'data'}
  //etc...
];


问:
Load .csv files into dictionary and print keys and values separately
I am having troubles figuring out how to store multiple .csv files into a dictionary and then print the keys and values separately. I have to take 6 .csv files all containing different information and load them into a dictionary(s) and then write a code so that I am able to isolate the key from the various values its associated with so that I can print ie. "animal" eats "prey1, prey2, etc".

I think I have to do each file separately, so 6 different loops to get the right output for each list of key/values, but everything I've tried has given me an error message.
Here is an examples of a csv file and the expected output:

file1.csv:

```<code>Rabbit,Grass
Snake,Mouse
Mouse,Grass
</code>```

Output:

```<code>Predator and prey:
"Rabbit eats grass"
"Snake eats mouse"
"Mouse eats grass"
</code>```

this is the code I have so far for one file:

```<code>import sys
import csv

inf = open("file1.csv", "r")
reader = csv.reader(inf)

data = {}
for row in reader:
    for i in data.keys():
        print(data[i], "eats", i)
</code>```

I know its not right but I'm not sure how to isolate a key in a dictionary when its a .csv file. I am new to coding so any help would be greatly appreciated! :)
I am using python3.
thanks!!

答:
Well, there are no keys (header fields) or anything in your CSV, just simple value pairs and you just want to print separately the elements of each row which is quite simple:

```<code>import csv

with open("file1.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[0], "eats", row[1])
</code>```

Which should produce:

```Rabbit eats Grass
Snake eats Mouse
Mouse eats Grass```

UPDATE: If you want to store the data into a dictionary, just use the first value as a key and the second value as one of the values, e.g.:

```<code>import collections
import csv

# we'll use defaultdict to save us some trouble initializing for each predator
predators = collections.defaultdict(set)  # our final dict, use set to filter out duplicates

files = ["file1.csv", "file2.csv", "file3.csv"]  # all of your CSV files

for file in files:  # go through each CSV file...
    with open(file, "r") as f:  # open it...
        reader = csv.reader(f)  # make a CSV reader
        for row in reader:  # go through it line by line
            predators[row[0]].add(row[1])  # add it to the predators dict

for predator in predators:
    print(predator, "eats", predators[predator])
</code>```

Body:
I am having troubles figuring out how to store multiple .csv files into a dictionary and then print the keys and values separately. I have to take 6 .csv files all containing different information and load them into a dictionary(s) and then write a code so that I am able to isolate the key from the various values its associated with so that I can print ie. "animal" eats "prey1, prey2, etc".

I think I have to do each file separately, so 6 different loops to get the right output for each list of key/values, but everything I've tried has given me an error message.
Here is an examples of a csv file and the expected output:

file1.csv:

Rabbit,Grass
Snake,Mouse
Mouse,Grass

Output:

Predator and prey:
"Rabbit eats grass"
"Snake eats mouse"
"Mouse eats grass"

this is the code I have so far for one file:

import sys
import csv

inf = open("file1.csv", "r")
reader = csv.reader(inf)

data = {}
for row in reader:
    for i in data.keys():
        print(data[i], "eats", i)

I know its not right but I'm not sure how to isolate a key in a dictionary when its a .csv file. I am new to coding so any help would be greatly appreciated! :)
I am using python3.
thanks!!

Body:
Well, there are no keys (header fields) or anything in your CSV, just simple value pairs and you just want to print separately the elements of each row which is quite simple:

import csv

with open("file1.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[0], "eats", row[1])

Which should produce:

Rabbit eats Grass
Snake eats Mouse
Mouse eats Grass

UPDATE: If you want to store the data into a dictionary, just use the first value as a key and the second value as one of the values, e.g.:

import collections
import csv

# we'll use defaultdict to save us some trouble initializing for each predator
predators = collections.defaultdict(set)  # our final dict, use set to filter out duplicates

files = ["file1.csv", "file2.csv", "file3.csv"]  # all of your CSV files

for file in files:  # go through each CSV file...
    with open(file, "r") as f:  # open it...
        reader = csv.reader(f)  # make a CSV reader
        for row in reader:  # go through it line by line
            predators[row[0]].add(row[1])  # add it to the predators dict

for predator in predators:
    print(predator, "eats", predators[predator])


问:
How to sort content of a csv file in java
I have a big csv file that looks like this

```<code> Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
 3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
 293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
 293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
 483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology
</code>```

I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far

```<code>package project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(System.in);
            int choice=0;
            boolean flag = true;

            while (flag) {
                System.out.println("Enter 1 to display data.");
                System.out.println("Enter 2 to sort data.");
                System.out.println("Enter 3 to idk.");
                System.out.println("Enter 0 to exit.");
                System.out.print("Your choice: ");
                choice = input.nextInt();
                if (choice ==1) {
                    File inputFile = new File("dataToLoad.csv");
                    String line;
                    String delimiter = ",";
                    Scanner in = new Scanner(inputFile);
                    int numberOfLines = 0;
                    int numberOfColumns = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        numberOfLines++;
                    }
                    in.close();
                    String[][] data = new String[numberOfLines][8];
                    in = new Scanner(inputFile);
                    int currentRow = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        String[] parts = line.split(delimiter);
                        numberOfColumns = parts.length;
                        for (int i = 0; i<numberOfColumns; i++) {
                            data[currentRow][i] = parts[i];
                        }
                        currentRow++;
                    }
                    in.close();
                    System.out.println(Arrays.deepToString(data));
                    for (int row=0; row<numberOfLines; row++) {
                        for (int col=0; col<numberOfColumns; col++) {
                            System.out.printf("%-20s", data[row][col]);
                        }
                        System.out.println();
                    }
                }
                else {
                    if (choice ==2) {

                    }
                    else
                        if (choice==0) {
                        System.out.println("Good bye!");
                        flag = false;
                    }
                else System.out.println("I am sorry, this is not a valid option. Please try again.");
            }
            }
    }
}
</code>```

As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.

答:
This should help, I believe that you will figure out what's going on here

Main.java

```<code>package pkg;

import java.util.Arrays;

import static pkg.Order.OrderBuilder;

public class Main {

    private static Order[] orders = new Order[3];
    private static OrderBuilder orderBuilder = new OrderBuilder();

    public static void main(String[] args) {
        Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
        Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
        Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();

        orders[0] = order3;
        orders[1] = order1;
        orders[2] = order2;

        System.out.println("Before sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }

        Arrays.sort(orders);

        System.out.println("After sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }
    }
}
</code>```

Order.java

```<code>package pkg;

public class Order implements Comparable<Order> {
    private int id;
    private String priority;
    private float quantity;
    private float price;
    private String shipMode;
    private String customerName;
    private String customerSegment;
    private String productCategory;

    private void setId(int id) {
        this.id = id;
    }

    int getId() {
        return this.id;
    }

    private void setPriority(String priority) {
        this.priority = priority;
    }

    private void setQuantity(float quantity) {
        this.quantity = quantity;
    }

    private void setPrice(float price) {
        this.price = price;
    }

    private void setShipMode(String shipMode) {
        this.shipMode = shipMode;
    }

    private void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    private void setCustomerSegment(String customerSegment) {
        this.customerSegment = customerSegment;
    }

    private void setProductCategory(String productCategory) {
        this.productCategory = productCategory;
    }

    @Override
    public int compareTo(Order o) {
        return this.id - o.getId();
    }

    static class OrderBuilder {
        private Order order;

        OrderBuilder withId(int id) {
            order.setId(id);
            return this;
        }

        OrderBuilder withPriority(String priority) {
            order.setPriority(priority);
            return this;
        }

        OrderBuilder withQuantity(float quantity) {
            order.setQuantity(quantity);
            return this;
        }

        OrderBuilder withPrice(float price) {
            order.setPrice(price);
            return this;
        }

        OrderBuilder withShipMode(String shipMode) {
            order.setShipMode(shipMode);
            return this;
        }

        OrderBuilder withCustomerName(String customerName) {
            order.setCustomerName(customerName);
            return this;
        }

        OrderBuilder withCustomerSegment(String customerSegment) {
            order.setCustomerSegment(customerSegment);
            return this;
        }

        OrderBuilder withProductCategory(String productCategory) {
            order.setProductCategory(productCategory);
            return this;
        }

        OrderBuilder createNewOrder() {
            order = new Order();
            return this;
        }

        Order build() {
            return order;
        }

    }
}
</code>```

Body:
I have a big csv file that looks like this

 Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
 3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
 293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
 293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
 483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology

I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far

package project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(System.in);
            int choice=0;
            boolean flag = true;

            while (flag) {
                System.out.println("Enter 1 to display data.");
                System.out.println("Enter 2 to sort data.");
                System.out.println("Enter 3 to idk.");
                System.out.println("Enter 0 to exit.");
                System.out.print("Your choice: ");
                choice = input.nextInt();
                if (choice ==1) {
                    File inputFile = new File("dataToLoad.csv");
                    String line;
                    String delimiter = ",";
                    Scanner in = new Scanner(inputFile);
                    int numberOfLines = 0;
                    int numberOfColumns = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        numberOfLines++;
                    }
                    in.close();
                    String[][] data = new String[numberOfLines][8];
                    in = new Scanner(inputFile);
                    int currentRow = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        String[] parts = line.split(delimiter);
                        numberOfColumns = parts.length;
                        for (int i = 0; i<numberOfColumns; i++) {
                            data[currentRow][i] = parts[i];
                        }
                        currentRow++;
                    }
                    in.close();
                    System.out.println(Arrays.deepToString(data));
                    for (int row=0; row<numberOfLines; row++) {
                        for (int col=0; col<numberOfColumns; col++) {
                            System.out.printf("%-20s", data[row][col]);
                        }
                        System.out.println();
                    }
                }
                else {
                    if (choice ==2) {

                    }
                    else
                        if (choice==0) {
                        System.out.println("Good bye!");
                        flag = false;
                    }
                else System.out.println("I am sorry, this is not a valid option. Please try again.");
            }
            }
    }
}

As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.

Body:
This should help, I believe that you will figure out what's going on here

Main.java

package pkg;

import java.util.Arrays;

import static pkg.Order.OrderBuilder;

public class Main {

    private static Order[] orders = new Order[3];
    private static OrderBuilder orderBuilder = new OrderBuilder();

    public static void main(String[] args) {
        Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
        Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
        Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();

        orders[0] = order3;
        orders[1] = order1;
        orders[2] = order2;

        System.out.println("Before sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }

        Arrays.sort(orders);

        System.out.println("After sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }
    }
}

Order.java

package pkg;

public class Order implements Comparable<Order> {
    private int id;
    private String priority;
    private float quantity;
    private float price;
    private String shipMode;
    private String customerName;
    private String customerSegment;
    private String productCategory;

    private void setId(int id) {
        this.id = id;
    }

    int getId() {
        return this.id;
    }

    private void setPriority(String priority) {
        this.priority = priority;
    }

    private void setQuantity(float quantity) {
        this.quantity = quantity;
    }

    private void setPrice(float price) {
        this.price = price;
    }

    private void setShipMode(String shipMode) {
        this.shipMode = shipMode;
    }

    private void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    private void setCustomerSegment(String customerSegment) {
        this.customerSegment = customerSegment;
    }

    private void setProductCategory(String productCategory) {
        this.productCategory = productCategory;
    }

    @Override
    public int compareTo(Order o) {
        return this.id - o.getId();
    }

    static class OrderBuilder {
        private Order order;

        OrderBuilder withId(int id) {
            order.setId(id);
            return this;
        }

        OrderBuilder withPriority(String priority) {
            order.setPriority(priority);
            return this;
        }

        OrderBuilder withQuantity(float quantity) {
            order.setQuantity(quantity);
            return this;
        }

        OrderBuilder withPrice(float price) {
            order.setPrice(price);
            return this;
        }

        OrderBuilder withShipMode(String shipMode) {
            order.setShipMode(shipMode);
            return this;
        }

        OrderBuilder withCustomerName(String customerName) {
            order.setCustomerName(customerName);
            return this;
        }

        OrderBuilder withCustomerSegment(String customerSegment) {
            order.setCustomerSegment(customerSegment);
            return this;
        }

        OrderBuilder withProductCategory(String productCategory) {
            order.setProductCategory(productCategory);
            return this;
        }

        OrderBuilder createNewOrder() {
            order = new Order();
            return this;
        }

        Order build() {
            return order;
        }

    }
}


问:
Querying MongoDB to return only document with single value with matching condition
I want MongoDB to return an entire document if it has exactly one element in array matching the condition. I have written following:

```<code>db.myCollection.find({ $where: "this.Tags.filter(x => x.indexOf(':') < 0).length === 1" })
</code>```

It works fine, except that it's slow as hell, because $where clause doesn't use indicies.

Could this query be rewritten somehow to normal find/match/... operations that are aware of indicies or this is the only way to perform such an operation? I can defenitly add some field like NumberOfTagsThatDoNotContainSemicolon, but my question is about more generic approach that doesn't require changes to how data is inserted.

答:
Here's a much more concise version that doesn't need any unwinds:

```<code>db.myCollection.aggregate([
{
    $addFields: { // we want to add new field...
        "NumberOfTagsWithoutSemiColon": {
            $size: { // ...that shall contain the number...
                $filter: {
                    input: "$Tags", // ...of all tags...
                    cond: {
                        $eq: // ...that do not contain a semicolon
                        [
                            { $indexOfBytes: [ "$$this", ":" ] },
                            -1
                        ]
                    }
                }
            }
        }
    }
}, {
    $match: {
        "NumberOfTagsWithoutSemiColon": 1 // we only keep the ones where
    }
}, {
    $project: {
        "NumberOfTagsWithoutSemiColon": 0
    }
}])
</code>```

Body:
I want MongoDB to return an entire document if it has exactly one element in array matching the condition. I have written following:

db.myCollection.find({ $where: "this.Tags.filter(x => x.indexOf(':') < 0).length === 1" })

It works fine, except that it's slow as hell, because $where clause doesn't use indicies.

Could this query be rewritten somehow to normal find/match/... operations that are aware of indicies or this is the only way to perform such an operation? I can defenitly add some field like NumberOfTagsThatDoNotContainSemicolon, but my question is about more generic approach that doesn't require changes to how data is inserted.

Body:
Here's a much more concise version that doesn't need any unwinds:

db.myCollection.aggregate([
{
    $addFields: { // we want to add new field...
        "NumberOfTagsWithoutSemiColon": {
            $size: { // ...that shall contain the number...
                $filter: {
                    input: "$Tags", // ...of all tags...
                    cond: {
                        $eq: // ...that do not contain a semicolon
                        [
                            { $indexOfBytes: [ "$$this", ":" ] },
                            -1
                        ]
                    }
                }
            }
        }
    }
}, {
    $match: {
        "NumberOfTagsWithoutSemiColon": 1 // we only keep the ones where
    }
}, {
    $project: {
        "NumberOfTagsWithoutSemiColon": 0
    }
}])


问:
Update mysql row if value different or create new row not added yet
For some reason this is not coming to me, and I do not see this specific question answered where there are two conditions.  I want to update my_table for the following two conditions:

If the Primary key vin is the same and the price is different. - or -

If there is no vin then just create a new row

Example of before and after two example updates:

In this exable vin 12345 exist so just the price is update as it's different, in the other example vin 55555 wasn't in the table so it's created.

答:
MySql supports a conditional insert/update - check https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html</p>

```<code>INSERT INTO my_table (vin,price) VALUES (12345, 7777)
    ON DUPLICATE KEY UPDATE price=7777;
</code>```

Body:
MySql supports a conditional insert/update - check https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

INSERT INTO my_table (vin,price) VALUES (12345, 7777)
    ON DUPLICATE KEY UPDATE price=7777;


问:
XML add new child to each element child of array node
I have xml that looks like this:

```<code><ArrayOfConfig>
    <Config>
        <!--stuff-->
    </Config>
    <Config>
        <!--stuff-->
    </Config>
</ArrayOfConfig>
</code>```

And I need to populate each Config node with a new child, such that it will look like:

```<code><ArrayOfConfig>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>
</code>```

I have run the following Powershell an an attempt to do so:

```<code>$doc = New-Object System.Xml.XmlDocument
$doc.Load('C:\temp\Configs.xml')
$child = $doc.CreateElement("NewChild")
$child.InnerText = "foo"
$doc.ArrayOfConfig.Config.AppendChild($child)
$doc.Save('C:\temp\Configs.xml')
</code>```

Running this kind of works, it only adds the child node to the second Config.  Example:

```<code><ArrayOfConfig>
    <Config>
        <!--stuff-->
    </Config>
    <Config>
        <!--stuff-->
        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>
</code>```

The amount of Config child nodes of ArrayOfConfig varies, so I can't do any static assignment.  How do I iterate over the children of ArrayOfConfig and make sure each of them correctly gets the new child node?

答:
```<code>$doc = New-Object System.Xml.XmlDocument
$doc.Load('C:\temp\Configs.xml')
foreach($config in $doc.SelectNodes('//Config'))
{
    $child = $doc.CreateElement("NewChild")
    $child.InnerText = "foo"
    $config.AppendChild($child)
}
$doc.Save('C:\temp\Configs.xml')
</code>```

Body:
I have xml that looks like this:

<ArrayOfConfig>
    <Config>

    </Config>
    <Config>

    </Config>
</ArrayOfConfig>

And I need to populate each Config node with a new child, such that it will look like:

<ArrayOfConfig>
    <Config>

        <NewChild>foo</NewChild>
    </Config>
    <Config>

        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>

I have run the following Powershell an an attempt to do so:

$doc = New-Object System.Xml.XmlDocument
$doc.Load('C:\temp\Configs.xml')
$child = $doc.CreateElement("NewChild")
$child.InnerText = "foo"
$doc.ArrayOfConfig.Config.AppendChild($child)
$doc.Save('C:\temp\Configs.xml')

Running this kind of works, it only adds the child node to the second Config.  Example:

<ArrayOfConfig>
    <Config>

    </Config>
    <Config>

        <NewChild>foo</NewChild>
    </Config>
</ArrayOfConfig>

The amount of Config child nodes of ArrayOfConfig varies, so I can't do any static assignment.  How do I iterate over the children of ArrayOfConfig and make sure each of them correctly gets the new child node?


问:
How to resample and round every index into nearest seconds?
My data looks like (the datatype is Pandas DataFrame) :

```<code>price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24
</code>```

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

```<code>03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24
</code>```

and used

```<code>price.resample('Min').last()
</code>```

However I got.

```<code>03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24
</code>```

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

答:
You need to use floor:

```<code>df.groupby(df.index.floor('Min')).last().resample('Min').asfreq()
</code>```

Let's try for speed(need Pandas 0.21.0+):

```<code>df.set_axis(df.index.floor('Min'), axis=0, inplace=False)\
  .drop_duplicates().resample('Min').asfreq()
</code>```

Output:

```<code>             bid
time
03:03:00  116.02
03:04:00     NaN
03:05:00     NaN
03:06:00     NaN
03:07:00  116.24
</code>```

Body:
My data looks like (the datatype is Pandas DataFrame) :

price =

time                bid
03:03:34.797000     116.02
03:03:34.797000     116.02
03:03:54.152000     116.02
03:03:54.169000     116.02
03:03:54.169000     116.02
03:07:36.899000     116.24
03:07:48.760000     116.24
03:07:48.760000     116.24
03:07:48.761000     116.24

I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be:

03:04:00    116.02
03:05:00    NaN
03:06:00    NaN
03:07:00    NaN
03:08:00    116.24

and used

price.resample('Min').last()

However I got.

03:03:34.797000     116.02
03:04:34.797000     NaN
03:05:34.797000     NaN
03:06:34.797000     NaN
03:07:34.797000     116.24

Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.

Body:
You need to use floor:

df.groupby(df.index.floor('Min')).last().resample('Min').asfreq()

Let's try for speed(need Pandas 0.21.0+):

df.set_axis(df.index.floor('Min'), axis=0, inplace=False)\
  .drop_duplicates().resample('Min').asfreq()

Output:

             bid
time
03:03:00  116.02
03:04:00     NaN
03:05:00     NaN
03:06:00     NaN
03:07:00  116.24


问:
How to write less code for a long if-else statement in Scala (code review)
I have the following code:

```<code>  def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (pc.isEmpty && level != "N") {
      // the pc is empty so add the level
      pc += level
    } else if (pc.contains("H") && level == "L") {
      // giving high information to low is not allowed
      errorReject()
    } else if (pc.contains("L") && level == "L") {
      // nothing to change because the pc is the same
      println("okay")
    } else if (pc.contains("H") && level == "H") {
      println("okay")
    } else if (pc.contains("L") && level == "H")
      // we have to raise the pc
    pc += level
    else if (level == "N") {
      println("We have a not valid operation!")
    } else {
      println("Something went terribly wrong!")
    }
  }
</code>```

Do you see some level of enhancement I can do, so that this big chunk of code looks just better. Thanks for your advise, Matthias.

答:
One common trick is to wrap the two values (pc and level) into a tuple, giving you a single entity that you can pattern match on:

```<code>(pc,level) match {
  case (a,b) if condition => ...
  case _ => ...
}
</code>```

The check pc.isEmpty immediately after creating an empty pc suggests that you've cropped the code for stackoverflow, so the approach may not help you here.  But I'll try it anyway:

```<code>def updateProgrammcounter(element: Name) {
  val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
  var pc = new HashSet[String]
  println("LEVEL: " + level)

  (pc, level) match {
    case (pc, level) if pc.isEmpty && level != "N" => pc += level
    case (pc, "L") if pc.contains("H") => errorReject()
    case (pc, "L") if pc.contains("L") => println("okay")
    case (pc, "H") if pc.contains("H") => println("okay")
    case (pc, "H") if pc.contains("L") => pc += level
    case (_,  "N") => println("We have a not valid operation!")
    case _ => println("Something went terribly wrong!")
  }
}
</code>```

This is obviously nonsence, as half of those conditions are impossible, but it is a literal translation of the code you originally supplied.  I'm also unhappy with the side effects and mutation, but didn't want to change too much in one sitting!

If you can add back in the code you removed, or give a better idea of what you're trying to achieve then I'll happily update my answer :)

UPDATE Prompted by Daniel, here's the next step; rearranging and optimising the cases:

```<code>(pc, level) match {
  case (_,  "N") => println("We have a not valid operation!")
  case (pc, level) if pc.isEmpty => pc += level
  case (pc, level) if pc.contains(level) => println("okay")
  case (pc, "L") if pc.contains("H") => errorReject()
  case (pc, "H") if pc.contains("L") => pc += level
  case _ => println("Something went terribly wrong!")
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following code:

  def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (pc.isEmpty && level != "N") {
      // the pc is empty so add the level
      pc += level
    } else if (pc.contains("H") && level == "L") {
      // giving high information to low is not allowed
      errorReject()
    } else if (pc.contains("L") && level == "L") {
      // nothing to change because the pc is the same
      println("okay")
    } else if (pc.contains("H") && level == "H") {
      println("okay")
    } else if (pc.contains("L") && level == "H")
      // we have to raise the pc
    pc += level
    else if (level == "N") {
      println("We have a not valid operation!")
    } else {
      println("Something went terribly wrong!")
    }
  }

Do you see some level of enhancement I can do, so that this big chunk of code looks just better. Thanks for your advise, Matthias.

Body:
One common trick is to wrap the two values (pc and level) into a tuple, giving you a single entity that you can pattern match on:

(pc,level) match {
  case (a,b) if condition => ...
  case _ => ...
}

The check pc.isEmpty immediately after creating an empty pc suggests that you've cropped the code for stackoverflow, so the approach may not help you here.  But I'll try it anyway:

def updateProgrammcounter(element: Name) {
  val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
  var pc = new HashSet[String]
  println("LEVEL: " + level)

  (pc, level) match {
    case (pc, level) if pc.isEmpty && level != "N" => pc += level
    case (pc, "L") if pc.contains("H") => errorReject()
    case (pc, "L") if pc.contains("L") => println("okay")
    case (pc, "H") if pc.contains("H") => println("okay")
    case (pc, "H") if pc.contains("L") => pc += level
    case (_,  "N") => println("We have a not valid operation!")
    case _ => println("Something went terribly wrong!")
  }
}

This is obviously nonsence, as half of those conditions are impossible, but it is a literal translation of the code you originally supplied.  I'm also unhappy with the side effects and mutation, but didn't want to change too much in one sitting!

If you can add back in the code you removed, or give a better idea of what you're trying to achieve then I'll happily update my answer :)

UPDATE Prompted by Daniel, here's the next step; rearranging and optimising the cases:

(pc, level) match {
  case (_,  "N") => println("We have a not valid operation!")
  case (pc, level) if pc.isEmpty => pc += level
  case (pc, level) if pc.contains(level) => println("okay")
  case (pc, "L") if pc.contains("H") => errorReject()
  case (pc, "H") if pc.contains("L") => pc += level
  case _ => println("Something went terribly wrong!")
}


问:
Django crashes on the second form POST while creating a matplotlib.pyplot image from a pandas object
My Django program crashes with the following error:
Segmentation fault (core dumped)

... which is some kind of C error. My difficulty is debugging the stack - I don't know where to chase the problem.

analysis is a pandas DataFrame object

Here's the offending code that loads in Django in the index View:

```<code>def index(request):
    d = {'a': [0,1,2,3], 'b': [-2,5,3,0] }
    analysis = pd.DataFrame(data=d)
    myImage = image(analysis)
    context = {'form': form, 'myImage': myImage }

def image(analysis):
    print('if this is the second POST, you will crash on running the next line')
    image = analysis.plot(x='a', y='b')
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    image = base64.b64encode(buf.read())
    return image
</code>```

The form POST runs perfectly the first time. The second POST is the problem.

I can reproduce the error by doing the following:

User visits /

User fills in the form, selects his file and pushes submit

Form directs to / (the same URL) and loads with an image after analyzing a uploaded file

User changes the form fields, uploads a file (new or different doesn't matter), then pushes submit for the second time

The program crashes on running image = analysis.plot(x='Indicator Value', y='Mean Period Return') in image()

I made a little test program to run outside of Django, which is posted below. It runs flawlessly. It's only when I run this code in my Django View that everything crashes.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import io, base64

d = {'a': [0,1,2,3], 'b': [-2,5,3,0] }
analysis = pd.DataFrame(data=d)

def image(analysis):
    print('if this is the second POST, you will crash on running the next line')
    image = analysis.plot(x='a', y='b')
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    image = base64.b64encode(buf.read())
    return image

myImage = image(analysis)
print('******\tmade image a')
myImage = image(analysis)
print('******\tmade image b')
</code>```

Lastly, the crash page in my browser is not the usual Django debugger. Django exits, so the only page that I see is a connection reset page.

答:
I had the same problem, and I find out that there was a problem with the backend that matplotlib was using, to solve this, the recommended backend is Agg, and you should set this up before importing pyplot:

```<code>import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
</code>```

You can find more documentation here.

Body:
My Django program crashes with the following error:
Segmentation fault (core dumped)

... which is some kind of C error. My difficulty is debugging the stack - I don't know where to chase the problem.

analysis is a pandas DataFrame object

Here's the offending code that loads in Django in the index View:

def index(request):
    d = {'a': [0,1,2,3], 'b': [-2,5,3,0] }
    analysis = pd.DataFrame(data=d)
    myImage = image(analysis)
    context = {'form': form, 'myImage': myImage }

def image(analysis):
    print('if this is the second POST, you will crash on running the next line')
    image = analysis.plot(x='a', y='b')
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    image = base64.b64encode(buf.read())
    return image

The form POST runs perfectly the first time. The second POST is the problem.

I can reproduce the error by doing the following:

User visits /

User fills in the form, selects his file and pushes submit

Form directs to / (the same URL) and loads with an image after analyzing a uploaded file

User changes the form fields, uploads a file (new or different doesn't matter), then pushes submit for the second time

The program crashes on running image = analysis.plot(x='Indicator Value', y='Mean Period Return') in image()

I made a little test program to run outside of Django, which is posted below. It runs flawlessly. It's only when I run this code in my Django View that everything crashes.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import io, base64

d = {'a': [0,1,2,3], 'b': [-2,5,3,0] }
analysis = pd.DataFrame(data=d)

def image(analysis):
    print('if this is the second POST, you will crash on running the next line')
    image = analysis.plot(x='a', y='b')
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    image = base64.b64encode(buf.read())
    return image

myImage = image(analysis)
print('******\tmade image a')
myImage = image(analysis)
print('******\tmade image b')

Lastly, the crash page in my browser is not the usual Django debugger. Django exits, so the only page that I see is a connection reset page.

Body:
I had the same problem, and I find out that there was a problem with the backend that matplotlib was using, to solve this, the recommended backend is Agg, and you should set this up before importing pyplot:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot

You can find more documentation here.


问:
Create generic data filter on pandas dataframe in Python
I am trying to create a generic filter on some data. Consider a boiled down example:

```<code>my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}
</code>```

now I want to leverage numpy's where to do something like:

```<code>np.where(my_data (...) my_filter["value"])
</code>```

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

答:
If I get you, using np.where i imagine something like this</p>

```<code>df['filter'] = np.where((df['value'] == 100) & (df['direction'] == '>'), 1,0)

df.loc[df['filter'] == 1]
</code>```

Body:
I am trying to create a generic filter on some data. Consider a boiled down example:

my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}

now I want to leverage numpy's where to do something like:

np.where(my_data (...) my_filter["value"])

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

Body:
If I get you, using np.where i imagine something like this

df['filter'] = np.where((df['value'] == 100) & (df['direction'] == '>'), 1,0)

df.loc[df['filter'] == 1]


问:
The regular expression doesn't work equal in different code even being the same input
I'm creating a code, a part of this code uses a regular expression which is:

var ex = "122", checker = /(\d)\1{1,}/g,
    c = pattern.test(+ex);
if(c) console.log(`works.`);```
</div>
</div>
</p>

<p>My goal is to check if there is a repeated number.</p>

<p>The problem arises when I use the above snippet in a larger section of code. I have the <strong>same input</strong> at the above snippet, but in the below code, the regex isnt work</p>

<p>Here is the code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function almostIncreasingSequence(sequence) {
    var clone = [].concat(sequence),
        l = clone.length,
        pattern = /(\d)\1{2,}/ig;
    if (pattern.test(clone)) {
        return false;
    }

    var sorted = sequence.splice(0).sort(function(a, b) {
            return a - b;
        }),
        element, finder, checker = /(\d)\1{1,}/g;

    for (var i = 0; i < l; ++i) {
        element = clone[i];
        finder = sorted.indexOf(element);
        clone.splice(i, 1);
        sorted.splice(finder, 1);
        if (clone.join("") === sorted.join("") && !checker.test(+clone.join(""))) {
            /*
            In the conditional above, i use the regex
            */
            console.log(`
            Same input: ${+clone.join("")}

            PD: This message, it should not be shown, since the conditional should not have been true,
            `);
            return true;
        } else {
            clone.splice(i, 0, element);
            sorted.splice(finder, 0, element);
        }
    }
    return false;
}
console.log(almostIncreasingSequence([1, 2, 1, 2]))</code>```

So in the first snippet code, the regex return true, but in the second snippet code, or the regex is bad or the negation isn't works, because i'm negating the result of regex, because the regex in the second snippet code have the same input as the first, so the negation of true is false .

答:
Edit: sort list and return only incremental values without using regex:

function almostIncreasingSequence (array) {
  return Array.from(array)
    .sort()
    .reduce(function(acc, cur, i, arr) {
      if (arr[i - 1] !== cur) {
        return acc.concat(cur)
      } else {
        return acc
      }
    }, [])
}

console.log(almostIncreasingSequence([1, 2, 1, 2])) // [1,2]
console.log(almostIncreasingSequence([1, 2, 2, 4, 3])) // [1,2,3,4]```

Body:
I'm creating a code, a part of this code uses a regular expression which is:

var ex = "122", checker = /(\d)\1{1,}/g,
    c = pattern.test(+ex);
if(c) console.log(`works.`);

My goal is to check if there is a repeated number.

The problem arises when I use the above snippet in a larger section of code. I have the same input at the above snippet, but in the below code, the regex isnt work

Here is the code:

function almostIncreasingSequence(sequence) {
    var clone = [].concat(sequence),
        l = clone.length,
        pattern = /(\d)\1{2,}/ig;
    if (pattern.test(clone)) {
        return false;
    }

    var sorted = sequence.splice(0).sort(function(a, b) {
            return a - b;
        }),
        element, finder, checker = /(\d)\1{1,}/g;

    for (var i = 0; i < l; ++i) {
        element = clone[i];
        finder = sorted.indexOf(element);
        clone.splice(i, 1);
        sorted.splice(finder, 1);
        if (clone.join("") === sorted.join("") && !checker.test(+clone.join(""))) {
            /*
            In the conditional above, i use the regex
            */
            console.log(`
            Same input: ${+clone.join("")}

            PD: This message, it should not be shown, since the conditional should not have been true,
            `);
            return true;
        } else {
            clone.splice(i, 0, element);
            sorted.splice(finder, 0, element);
        }
    }
    return false;
}
console.log(almostIncreasingSequence([1, 2, 1, 2]))

So in the first snippet code, the regex return true, but in the second snippet code, or the regex is bad or the negation isn't works, because i'm negating the result of regex, because the regex in the second snippet code have the same input as the first, so the negation of true is false .


问:
Laravel: How can i pass data from controller to blade using yajra/laravel-datatables
I am using yajra/laravel-datatables. It's successfully installed. Now, how can i pass data Laravel Controller to blade??

```<code>$contacts = Contact::Where('is_deleted',0)->get();
</code>```

This is the code. There are lots of data. For those reason, It takes lots of time to load in dataTable. I want to load and pass data to dataTable using yajra/laravel-datatables.

答:
There are many option which you can use

compact method

```<code>  $data = Contact::Where('is_deleted',0)->get();
  return view('home',compact('data'))
</code>```

with method

```<code>$data = Contact::Where('is_deleted',0)->get()
        ->with('data',$data);
</code>```

For more information, read the documentation

Body:
I am using yajra/laravel-datatables. It's successfully installed. Now, how can i pass data Laravel Controller to blade??

$contacts = Contact::Where('is_deleted',0)->get();

This is the code. There are lots of data. For those reason, It takes lots of time to load in dataTable. I want to load and pass data to dataTable using yajra/laravel-datatables.

Body:
There are many option which you can use

compact method

  $data = Contact::Where('is_deleted',0)->get();
  return view('home',compact('data'))

with method

$data = Contact::Where('is_deleted',0)->get()
        ->with('data',$data);

For more information, read the documentation


问:
looking for direction with basic grep function in R (incorporated into a function)
Help with the following function. I am trying to create a function that will take values (from 'years')  and run a simple grep on a data.frame(searches).

The data.frame(searches) looks like;

```<code>> data.table(searches)[53:58]
         date hits    keyword          geo gprop   category
1: 2014-01-05   34 Price world             web        0
2: 2014-01-12   25 Price world             web        0
3: 2014-01-19   44 Price world             web        0
4: 2014-01-26   30 Price world             web        0
5: 2014-02-02   31 Price world             web        0
6: 2014-02-09   29 Price world             web        0
</code>```

I am trying to extract each year, 2013, 2014, 2015 etc. at the moment using the grep function and save just the columns from the above data.frame "date" and "hits".

The code I currently have is;

```<code>years <- c("2013", "2014", "2015", "2016", "2017")

func_src <- for(i in ncol(1:5)){

  func_src[i] <- searches[grep(years(ncol[1:5]), searches$date),]
  print(func_src[i])
}
</code>```

This returns a NULL value.

The final output I am hoping to obtain would have something like

```<code>colnames <- date hits1 hits2 hits3 hits4
</code>```

(I am tidying the data based on date and not keyword as the keyword can change based on previous inputs, i.e. "sell world" and the date 2014, 2015, 2016 does not change)

EDIT: For clarification I paste in all the code and add in further comments.

The following code should get you to where I am at (it is just test data/var names so the number of hits = 0 does not matter).

```<code>library(gtrendsR)

Variable_names <- c("VAR1")

keywords <- c("US news", "", "Canada News", "US Car news", "Canada Car news")

trends <- apply(expand.grid(Variable_names, keywords), 1, paste, collapse=" ")
trends

searches <- gtrends(trends)$interest_over_time
searches <- searches[-c(1:4), ]

years <- c("2013", "2014", "2015", "2016", "2017")
</code>```

After running this code, I hope to apply a function which will split across different years, 2013, 2014, 2015 etc. I have each keyword from 2013:2017 and I am only interested in keeping the date column and hits column. so;

I am trying to create a data.frame to have a date column, and then split on each row once we have reached the end of 2017 (as thats when a new keyword would come into play).

Ultimately I am trying to acheive

```<code>date hits1 hits2 hits3 hits4
</code>```

each hits column would also correspond to each "keyword" in the keywords dataframe (but I am trying to split on year and not keyword)

hope this makes what I am trying to do a little clearer.

答:
I think you're overthinking this!

you can use the lubridate package to pull the year out. This is contained in tidyverse which is a medley of great tidying packages.

```<code>library(tidyverse)

searches_new <- searches %>%
    mutate(year = year(date)) %>%
    select(year, date, hits)
</code>```

That will create a new column with just the year. I'm not sure what final output you want without more clarification. But I think you'll just want to either do some group_by or utilize spread

Body:
Help with the following function. I am trying to create a function that will take values (from 'years')  and run a simple grep on a data.frame(searches).

The data.frame(searches) looks like;

> data.table(searches)[53:58]
         date hits    keyword          geo gprop   category
1: 2014-01-05   34 Price world             web        0
2: 2014-01-12   25 Price world             web        0
3: 2014-01-19   44 Price world             web        0
4: 2014-01-26   30 Price world             web        0
5: 2014-02-02   31 Price world             web        0
6: 2014-02-09   29 Price world             web        0

I am trying to extract each year, 2013, 2014, 2015 etc. at the moment using the grep function and save just the columns from the above data.frame "date" and "hits".

The code I currently have is;

years <- c("2013", "2014", "2015", "2016", "2017")

func_src <- for(i in ncol(1:5)){

  func_src[i] <- searches[grep(years(ncol[1:5]), searches$date),]
  print(func_src[i])
}

This returns a NULL value.

The final output I am hoping to obtain would have something like

colnames <- date hits1 hits2 hits3 hits4

(I am tidying the data based on date and not keyword as the keyword can change based on previous inputs, i.e. "sell world" and the date 2014, 2015, 2016 does not change)

EDIT: For clarification I paste in all the code and add in further comments.

The following code should get you to where I am at (it is just test data/var names so the number of hits = 0 does not matter).

library(gtrendsR)

Variable_names <- c("VAR1")

keywords <- c("US news", "", "Canada News", "US Car news", "Canada Car news")

trends <- apply(expand.grid(Variable_names, keywords), 1, paste, collapse=" ")
trends

searches <- gtrends(trends)$interest_over_time
searches <- searches[-c(1:4), ]

years <- c("2013", "2014", "2015", "2016", "2017")

After running this code, I hope to apply a function which will split across different years, 2013, 2014, 2015 etc. I have each keyword from 2013:2017 and I am only interested in keeping the date column and hits column. so;

I am trying to create a data.frame to have a date column, and then split on each row once we have reached the end of 2017 (as thats when a new keyword would come into play).

Ultimately I am trying to acheive

date hits1 hits2 hits3 hits4

each hits column would also correspond to each "keyword" in the keywords dataframe (but I am trying to split on year and not keyword)

hope this makes what I am trying to do a little clearer.

Body:
I think you're overthinking this!

you can use the lubridate package to pull the year out. This is contained in tidyverse which is a medley of great tidying packages.

library(tidyverse)

searches_new <- searches %>%
    mutate(year = year(date)) %>%
    select(year, date, hits)

That will create a new column with just the year. I'm not sure what final output you want without more clarification. But I think you'll just want to either do some group_by or utilize spread


问:
Convert an array of IDs to a map object
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

```<code>var ids = [4, 15, 8, 16, 42, 23];
</code>```

I am looking for some simple call to convert this into the following object:

```<code>{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }
</code>```

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

```<code>var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});
</code>```

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

```<code>var idMap = arrayToMap(ids);
</code>```

or

```<code>var idMap = arrayToMap(ids, true);
</code>```

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

答:
You could add it to the Array.prototype in your application:

```<code>var ids = [4, 15, 8, 16, 42, 23];

Array.prototype.toThing = function(propVal) {
    return this.reduce((res, val) => {
        res[val] = propVal;
        return res;
    }, {})
}
console.log(ids.toThing(true));
</code>```

Title: Convert an array of IDs to a map object

Body:
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

var ids = [4, 15, 8, 16, 42, 23];

I am looking for some simple call to convert this into the following object:

{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

var idMap = arrayToMap(ids);

or

var idMap = arrayToMap(ids, true);

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

Body:
You could add it to the Array.prototype in your application:

var ids = [4, 15, 8, 16, 42, 23];

Array.prototype.toThing = function(propVal) {
    return this.reduce((res, val) => {
        res[val] = propVal;
        return res;
    }, {})
}
console.log(ids.toThing(true));


问:
Playing RTP stream from embedded device using sockets
I'm writing an application on an embedded device which receives an RTP stream which carries G.729, PCM or H.264. The packets arrive to my application as a char* to the RTP packet. I would like to be able to see or listen to the stream (as a test), but on this device I don't have player. I thought I may forward this stream to a socket and play the RTP stream somewhere else, like on a Linux machine running a player. Would this be possible? I don't have RTSP, only RTP. Is VLC, for instance, a possible way to do this? Can I simply send the RTP packets to the socket to play them on the other side?
Thanks!</p>

答:
no, you cannot. simple RTP doesn't contain any info about the stream format etc., only info about the packet itself: sequence number, timestamp, additional synchronization info. the simplest way to stream RTP is RTP/MPEG TS (MPEG Transport Stream).

unfortunately I don't know ready to use solution. VLC can stream (and play) such streams over UDP from a file, so it takes required info from file container format. Such solution could take external stream description in SDP format and your actual RTP packets

[EDIT] btw, it's weird that you receive just RTP stream w/o any description of its format, usually its description is provided somehow by RTSP, MPEG-TS or something else


问:
How to know it is auto reply mail in Microsoft Graph?
I am using Microsoft Graph API to get mails.

```<code>GET /v1.0/me/messages
</code>```

It returns

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}
</code>```

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

```<code>mail.subject.startsWith('Automatic reply:')
</code>```

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?

答:
As @Horkrine said there is no officially guaranteed way of detecting if an email is an auto reply or not.

But there are two ways that may be useful:

Method 1 : Detect the response time

If you are capable, consider checking the amount of time between the email sent and the response. If that time is within a certain threshold, it is almost certainly an auto reply. Consider a reply received within seconds, for example. This has a lot of correlations with modern-day spam-robot detection techniques.

Method 2 :  Keywords

The other way to do it is to look for keywords, just as you are doing now. However, you also have to account for other languages, variations on spelling, misspellings, etc. You will not get everything.

For example:

mail.subject.contains('Automatic') OR  mail.subject.contains('Auto-matic')  OR  mail.subject.contains('Away')  OR  mail.subject.contains('out of office')
...
OR mail.subject.contains('automática') ...

Rather than typing out such a list, I would recommend doing a quick search on the internet and see if there are any such lists you can copy-paste from, as surely someone has done this sort of thing before and has some free code.

Body:
I am using Microsoft Graph API to get mails.

GET /v1.0/me/messages

It returns

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

mail.subject.startsWith('Automatic reply:')

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?