问:
Migrate from SBJson 2.2 to SBJson 5
Hello We are using SBJson lib with version   pod 'SBJson', '~>2.2.3' and want migrate to latest version pod 'SBJson5', '~> 5.0.0'.

What will be effort to migrate. I  mean will it support old methods or do i need find the deprecated or changed methods or any other specific change.

Does any one used this lib or done migration with SBJson do post to this thread.
Please suggest some solution

答:
I don't know how complicated your usage is, but you will definitively have to do some manual edits. I released version 3, with a major shift in focus towards streaming JSON way back in 2011, and I'm frankly amazed version 2.x.x even compiles today!

I tried to document the changes in the repo's NEWS file. When naming the releases I tried to follow SemVer, which means that every 2.x.x -> 3.x.x and 3.x.x -> 4.x.x and 4.x.x -> 5.x.x were named thus because they all broke backwards compatibility in some way.

For version 3 the API went through a big change to focus on streaming. Much of the API changed to support this. Version 4 further removed old methods that had been obsoleted in the 3.1.x, 3.2.x and 3.3.x series. For 4 -> 5 the breaking change was very small: the API stayed the same, and only the behaviour is slightly different. ("Naked Scalars", e.g. strings and numbers not wrapped it an array or object, is now accepted as per the updated JSON RFC.)

Have you considered whether you actually need to use SBJson? You may be better off just using NSJSONSerialisation. After all it's been in the iOS SDK since iOS 5, and in the Mac SDK since a bit after that. The main benefit of using SBJson is if you want to be able to start parsing JSON before it's fully downloaded. (Thus improving perceived latency.)

Other issues you may run into: I fixed a lot of bugs since 2.x.x releases, which means the parser is much stricter now than it was back then. (Due to bugs it used to allow all sorts of broken JSON, and broken UTF-8.) So if you rely on any of that behaviour you will be out of luck. Hopefully that's not the case :-)

Title: Migrate from SBJson 2.2 to SBJson 5


来源: stackexchange

问:
How to only select one of multiple records in an MS Access report query
I really hope that someone can help me with this issue.  A co-worker  and I created a database to track the training of over 300 employees.  We created a report, "Progress Report," to show the progress of employees towards a two-year 80 hour requirement for some of the training.  There are certain trainings that have to be taken every year, or two years, but should only be counted once in the progress report.  Here is the sql query:

```<code>SELECT [Employees Extended].Section, [Employees Extended].[Employee Name], Training.[Training Course], Training.Hours, Training.Category, Training.[Training Start Date], DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]") AS BGN, DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]") AS [END]
FROM Training INNER JOIN ([Employees Extended] INNER JOIN Employees ON [Employees Extended].[Employee ID] = Employees.[Employee ID]) ON Training.[Employee ID] = Employees.[Employee ID]
WHERE (((Training.Category)="Continuing Education") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="Privacy Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="Ethics Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="PRA Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]"))));
</code>```

I put this query together from different things that I looked up and was able to get it to work.  However, I'm not sure how, or what, I would need to do get get the results I need.

The Progress Report is mainly for training under the category "Continuing Education".  But there are three mandatory trainings (Privacy Training, Ethics Training, and PRA Training) that also need to be included.  It is these three trainings that will be done every year or two years.

Is there a way to adjust the query that I already have to only pull one of each of these three trainings?

答: Unfortunately... after further review of the reports this fix did not work.  The only thing I could think to do was to create a query for each of the types of trainings I was trying to include and then I created a union query.</p>

ContentLicense: CC BY-SA 3.0

Body:
I really hope that someone can help me with this issue.  A co-worker  and I created a database to track the training of over 300 employees.  We created a report, "Progress Report," to show the progress of employees towards a two-year 80 hour requirement for some of the training.  There are certain trainings that have to be taken every year, or two years, but should only be counted once in the progress report.  Here is the sql query:

SELECT [Employees Extended].Section, [Employees Extended].[Employee Name], Training.[Training Course], Training.Hours, Training.Category, Training.[Training Start Date], DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]") AS BGN, DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]") AS [END]
FROM Training INNER JOIN ([Employees Extended] INNER JOIN Employees ON [Employees Extended].[Employee ID] = Employees.[Employee ID]) ON Training.[Employee ID] = Employees.[Employee ID]
WHERE (((Training.Category)="Continuing Education") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="Privacy Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="Ethics Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]")))) OR (((Training.[Training Course])="PRA Training") AND ((Training.[Training Start Date]) Between (DLookUp("[BeginDate]","[DateIntervals]","Date()>[DateIntervals]![BeginDate]")) And (DLookUp("[EndDate]","[DateIntervals]","Date()<[DateIntervals]![EndDate]"))));

I put this query together from different things that I looked up and was able to get it to work.  However, I'm not sure how, or what, I would need to do get get the results I need.

The Progress Report is mainly for training under the category "Continuing Education".  But there are three mandatory trainings (Privacy Training, Ethics Training, and PRA Training) that also need to be included.  It is these three trainings that will be done every year or two years.

Is there a way to adjust the query that I already have to only pull one of each of these three trainings?


问:
php, mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement
I have the following code :

```<code>$id = $_GET['id'];

// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM date WHERE id=?"))
{
        $stmt->bind_param("isssssssss", $id, $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
        $stmt->execute();

        $stmt->bind_result($id, $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
        $stmt->fetch();

        // show the form
        renderForm($mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email, NULL, $id);

        $stmt->close();
}
// show an error if the query has an error
else
{
        echo "Error: could not prepare SQL statement";
}
</code>```

which generates the following errors / warnings :

```<code>Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\records.php on line 143

Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement in C:\wamp\www\records.php on line 144

Warning: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\records.php on line 146

Warning: mysqli_stmt::fetch() [mysqli-stmt.fetch]: (HY000/2053): Attempt to read a row while there is no result set associated with the statement in C:\wamp\www\records.php on line 147
</code>```

And the form is not completed with the data from db as i was expecting ... Any advice / help would be greatly appreciated.

答:
You misunderstood the use of statements.

In your query statement, you only need to bind one parameter, the id.

```<code>$stmt->bind_param("i", $id);
$id = 5; // fetch the fifth record
$stmt->execute();
</code>```

And then you access the values from your query's result by fetching the result object.

Check out the mysqli_stmt::execute exemple, php.net

ContentLicense: CC BY-SA 2.5

Body:
I have the following code :

$id = $_GET['id'];

// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM date WHERE id=?"))
{
        $stmt->bind_param("isssssssss", $id, $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
        $stmt->execute();

        $stmt->bind_result($id, $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
        $stmt->fetch();

        // show the form
        renderForm($mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email, NULL, $id);

        $stmt->close();
}
// show an error if the query has an error
else
{
        echo "Error: could not prepare SQL statement";
}

which generates the following errors / warnings :

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\records.php on line 143

Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement in C:\wamp\www\records.php on line 144

Warning: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\records.php on line 146

Warning: mysqli_stmt::fetch() [mysqli-stmt.fetch]: (HY000/2053): Attempt to read a row while there is no result set associated with the statement in C:\wamp\www\records.php on line 147

And the form is not completed with the data from db as i was expecting ... Any advice / help would be greatly appreciated.

Body:
You misunderstood the use of statements.

In your query statement, you only need to bind one parameter, the id.

$stmt->bind_param("i", $id);
$id = 5; // fetch the fifth record
$stmt->execute();

And then you access the values from your query's result by fetching the result object.

Check out the mysqli_stmt::execute exemple, php.net


问:
Crop whitespace from image in PHP
Is it possible to remove the whitespace surrounding an image in PHP?

NOTE: to clarify I mean something like photoshops trim feature.

Thanks.

答:
PHP's gd library has the imagecropauto function (PHP version 5.5+):

```<code><?php
$img=imagecreatefrompng("tux.png"); // Load and instantiate the image
if($img) {
  $cropped=imagecropauto($img,IMG_CROP_DEFAULT); // Auto-crop the image

  imagedestroy($img); // Clean up as $img is no longer needed

  header("Content-type: image/png"); // Set the appropriate header so the browser
                                     // knows how to present it
  imagepng($cropped); // Return the newly cropped image
}
</code>```

By default imagecropauto will try to crop using transparency, and then fall back on using the 4 corners of the image to attempt to detect the background to crop; I have also had success with the following constants in place of IMG_CROP_AUTO in the example above:

IMG_CROP_BLACK - Useful for images with a black background

IMG_CROP_WHITE - Useful for images with a white background

IMG_CROP_THRESHOLD - Allows you to set a colour and threshold to use when cropping

Title: Crop whitespace from image in PHP

Body:
PHP's gd library has the imagecropauto function (PHP version 5.5+):

<?php
$img=imagecreatefrompng("tux.png"); // Load and instantiate the image
if($img) {
  $cropped=imagecropauto($img,IMG_CROP_DEFAULT); // Auto-crop the image

  imagedestroy($img); // Clean up as $img is no longer needed

  header("Content-type: image/png"); // Set the appropriate header so the browser
                                     // knows how to present it
  imagepng($cropped); // Return the newly cropped image
}

By default imagecropauto will try to crop using transparency, and then fall back on using the 4 corners of the image to attempt to detect the background to crop; I have also had success with the following constants in place of IMG_CROP_AUTO in the example above:

IMG_CROP_BLACK - Useful for images with a black background

IMG_CROP_WHITE - Useful for images with a white background

IMG_CROP_THRESHOLD - Allows you to set a colour and threshold to use when cropping

ContentLicense: CC BY-SA 4.0


问:
Redirect all ASP.NET Core logging into a single NLog logger
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

```<code>        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);
</code>```

and this is also how ASP.net gets attached to nlog:

```<code>        LoggerFactory.AddNLog();
        Application.AddNLogWeb();
</code>```

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.

答:
Look at the code of NLog.Extensions.Logging, where it injects its own custom log-provider.

You can do the same and just wrap your global-logger object:

https://github.com/NLog/NLog.Extensions.Logging/blob/e48d6cc54d9abd70d976066265c7992117cbac5a/src/NLog.Extensions.Logging/NLogLoggerProvider.cs

https://github.com/NLog/NLog.Extensions.Logging/blob/1474ffe5b26d2ac95534ed01ef259133133bfb67/src/NLog.Extensions.Logging/NLogLoggerFactory.cs

https://github.com/NLog/NLog.Extensions.Logging/blob/2c05a4fbdda0fe026e60814d535e164e18786aef/src/NLog.Extensions.Logging/ConfigureExtensions.cs

```<code>    public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
    {
        ConfigureHiddenAssemblies();

        using (var provider = new NLogLoggerProvider(options))
        {
            factory.AddProvider(provider);
        }
        return factory;
    }
</code>```

Body:
I have an ASP.NET project that sends its logs to NLog.

However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.

I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.

How can this be accomplished?

This is the code that creates the logger:

        // create the module name
        var ProcessName = Process.GetCurrentProcess().ProcessName;
        _ModuleName = ProcessName  + " (\"" + Oracle.GuessMyName() + "\")";

        // create the logger configuration
        var Configuration = new LoggingConfiguration();

        // create the file target
        var FileTarget = new FileTarget ("file")
        {
            FileName            = @"x:\Logs\${processname}.log",
            ArchiveFileName     = @"x:\Logs\${processname}.{#}.log",
            Layout              = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
            ArchiveEvery        = FileArchivePeriod.Day,
            ArchiveNumbering    = ArchiveNumberingMode.Rolling,
            MaxArchiveFiles     = 7,
            ConcurrentWrites    = true
        };

        Configuration.AddTarget(FileTarget);

        // create the viewer target
        var ViewerTarget = new NLogViewerTarget ("viewer")
        {
            Layout              = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
            IncludeSourceInfo   = true,
            IncludeCallSite     = true,
            Address             = @"udp://127.0.0.1:9999"
        };

        Configuration.AddTarget(ViewerTarget);

        // set the rules
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
        Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));

        // set the configuration
        LogManager.Configuration = Configuration;

        // create a new logger
        _Logger = LogManager.GetLogger(_ModuleName);

and this is also how ASP.net gets attached to nlog:

        LoggerFactory.AddNLog();
        Application.AddNLogWeb();

Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)

so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.

the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.

Body:
Look at the code of NLog.Extensions.Logging, where it injects its own custom log-provider.

You can do the same and just wrap your global-logger object:

https://github.com/NLog/NLog.Extensions.Logging/blob/e48d6cc54d9abd70d976066265c7992117cbac5a/src/NLog.Extensions.Logging/NLogLoggerProvider.cs

https://github.com/NLog/NLog.Extensions.Logging/blob/1474ffe5b26d2ac95534ed01ef259133133bfb67/src/NLog.Extensions.Logging/NLogLoggerFactory.cs

https://github.com/NLog/NLog.Extensions.Logging/blob/2c05a4fbdda0fe026e60814d535e164e18786aef/src/NLog.Extensions.Logging/ConfigureExtensions.cs

    public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
    {
        ConfigureHiddenAssemblies();

        using (var provider = new NLogLoggerProvider(options))
        {
            factory.AddProvider(provider);
        }
        return factory;
    }


问:
C# Put Static Class Inside Dictionary
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

```<code>static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}
</code>```

答:
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.

If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.

However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.

If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.

One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:

```<code>container.Register(Component.For<ISomeInterface,SomeClass>));
</code>```

Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.

Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.

Title: C# Put Static Class Inside Dictionary

Body:
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}

Body:
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.

If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.

However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.

If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.

One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:

container.Register(Component.For<ISomeInterface,SomeClass>));

Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.

Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.


问:
Restricting one URL from Apcahe httpd reverse proxy rules
I have Apache server serving as a reverse proxy for one of Angular application.

Defined Reverse proxy rules in ssl.conf like below

 ProxyPass http://10.10.10.101/xyz/abc
 ProxyPassReverse http://10.10.10.101/xyz/abc

And also defined Rewrite conditions

RewriteCond %{REQUEST_URI} !^/xyz/abc(.*)$

But in my code i have one file coming with same URL like /xyz/abc/header.html.

I want to restrict that URL not to go through reverse proxy rule.

How can i restrict it, can some one help me out with this issue?

答:
To make exceptions to proxy you just append "!" at the end, like:</p>

```<code>ProxyPass /xyz/abc/header.html !
</code>```

Body:
To make exceptions to proxy you just append "!" at the end, like:

ProxyPass /xyz/abc/header.html !


问:
Why does my switch statement parameter require a boolean?
From my understanding, inside a switch statement parameter is supposed to be the item you are comparing against all your cases and returns the correct case.

My question is why does my switch statement require I put in the boolean true and not the "score" argument to which I am comparing all my cases? Thanks!

Heres the exercise

```<code>function convertScoreToGrade(score) {
  switch (true) {
    case (score > 100 || score < 0):
      return 'INVALID SCORE';
      break;
    case (score <=100 && score >= 90):
      return 'A';
      break;
    case (score <=89 && score >= 80):
      return 'B';
      break;
    case (score <=79 && score >= 70):
      return 'C';
      break;
    case (score <=69 && score >= 60):
      return 'D';
      break;
    case (score <=59 && score >= 0):
      return 'F';
      break;
  }
  return score;
}
</code>```

答:
Because JS evaluates an expression in the parenthesis before it compares with the switch argument. Consider this example:

convertScoreToGrade(71);

```<code>function convertScoreToGrade(score) {
  switch (true) {
    case (false):
      return 'INVALID SCORE';
      break;
    case (false):
      return 'A';
      break;
    case (false):
      return 'B';
      break;
    case (true):
      return 'C';
      break;
    case (false):
      return 'D';
      break;
    case (false):
      return 'F';
      break;
  }
  return score;
}
</code>```

Great explanation in this answer.

Body:
From my understanding, inside a switch statement parameter is supposed to be the item you are comparing against all your cases and returns the correct case.

My question is why does my switch statement require I put in the boolean true and not the "score" argument to which I am comparing all my cases? Thanks!

Heres the exercise

function convertScoreToGrade(score) {
  switch (true) {
    case (score > 100 || score < 0):
      return 'INVALID SCORE';
      break;
    case (score <=100 && score >= 90):
      return 'A';
      break;
    case (score <=89 && score >= 80):
      return 'B';
      break;
    case (score <=79 && score >= 70):
      return 'C';
      break;
    case (score <=69 && score >= 60):
      return 'D';
      break;
    case (score <=59 && score >= 0):
      return 'F';
      break;
  }
  return score;
}

Body:
Because JS evaluates an expression in the parenthesis before it compares with the switch argument. Consider this example:

convertScoreToGrade(71);

function convertScoreToGrade(score) {
  switch (true) {
    case (false):
      return 'INVALID SCORE';
      break;
    case (false):
      return 'A';
      break;
    case (false):
      return 'B';
      break;
    case (true):
      return 'C';
      break;
    case (false):
      return 'D';
      break;
    case (false):
      return 'F';
      break;
  }
  return score;
}

Great explanation in this answer.


问:
How to use SlowCheetah to transform an array elements in Json config file?
It's my first time using SlowCheetah for JSON config file. I could not find a way to let it transform an array settings. For example, if my base config file has this setting:

```<code>{
  "Settings" :  [1, 2, 3]
}
</code>```

and I want to transfer it to:

```<code>{
  "Settings" :  [4, 5, 6]
}
</code>```

It simply does the merge, instead of replacement. Is there a way I can tell it what to do? Like the way we using xdt:Transform="Replace" in xml config file.

答:
This transformation will do the job:</p>

```<code>{
  "@jdt.replace": {
    "@jdt.path": "$.Settings",
    "@jdt.value": [4,5,6]
  }
}
</code>```

Body:
It's my first time using SlowCheetah for JSON config file. I could not find a way to let it transform an array settings. For example, if my base config file has this setting:

{
  "Settings" :  [1, 2, 3]
}

and I want to transfer it to:

{
  "Settings" :  [4, 5, 6]
}

It simply does the merge, instead of replacement. Is there a way I can tell it what to do? Like the way we using xdt:Transform="Replace" in xml config file.

Body:
This transformation will do the job:

{
  "@jdt.replace": {
    "@jdt.path": "$.Settings",
    "@jdt.value": [4,5,6]
  }
}


问:
Problems with chrome.proxy API
I am trying to use the chrome proxy api but i keep getting this error for some reason. I thought i was doing everything right but i guess not :/

here is my code...

```<code>var proxy_type;
var proxy_port;
var proxy_ip;
chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    proxy_type = items.proxy_type; //this is equal to socks5
    proxy_ip = items.proxy_ip; //this is equal to 66.78.44.221
    proxy_port = parseInt(items.proxy_port); //this is equal to 58124
});
var config = {
  mode: "fixed_servers",
  rules: {
    singleProxy: {
      scheme: proxy_type,
      host: proxy_ip,
      port:proxy_port
    },
    bypassList: ["foobar.com"]
  }
};

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(proxy_ip); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
  });
</code>```

Whenever i run this code though, i get the error: Error in event handler for runtime.onMessage: Error: Invalid value for argument 1. Property 'value.rules.singleProxy.host': Property is required.

If i set the values of scheme, host, and port by just typing the values in instead of using a variable it works.

So why am i getting this error?

答:
The error indicates that the host field in the config may be undefined.  Since the chrome.storage.sync.get is asynchronous, I expect that config object is constructed before the proxy parameters are defined.

You could construct config in the callback and check that it is defined in the message handler:

```<code>var config;

chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    config = {
      mode: "fixed_servers",
      rules: {
        singleProxy: {
          scheme: items.proxy_type,
          host: items.proxy_ip,
          port: parseInt(items.proxy_port)
        },
        bypassList: ["foobar.com"]
      }
    };
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (!config) {
        console.log('proxy config not defined');
        return;
    }
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(config); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
});
</code>```

Title: Problems with chrome.proxy API

Body:
I am trying to use the chrome proxy api but i keep getting this error for some reason. I thought i was doing everything right but i guess not :/

here is my code...

var proxy_type;
var proxy_port;
var proxy_ip;
chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    proxy_type = items.proxy_type; //this is equal to socks5
    proxy_ip = items.proxy_ip; //this is equal to 66.78.44.221
    proxy_port = parseInt(items.proxy_port); //this is equal to 58124
});
var config = {
  mode: "fixed_servers",
  rules: {
    singleProxy: {
      scheme: proxy_type,
      host: proxy_ip,
      port:proxy_port
    },
    bypassList: ["foobar.com"]
  }
};

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(proxy_ip); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
  });

Whenever i run this code though, i get the error: Error in event handler for runtime.onMessage: Error: Invalid value for argument 1. Property 'value.rules.singleProxy.host': Property is required.

If i set the values of scheme, host, and port by just typing the values in instead of using a variable it works.

So why am i getting this error?

Body:
The error indicates that the host field in the config may be undefined.  Since the chrome.storage.sync.get is asynchronous, I expect that config object is constructed before the proxy parameters are defined.

You could construct config in the callback and check that it is defined in the message handler:

var config;

chrome.storage.sync.get(['proxy_type', 'proxy_port', 'proxy_ip', 'proxy'], function(items) {
    console.log('Settings retrieved', Object.values(items));
    config = {
      mode: "fixed_servers",
      rules: {
        singleProxy: {
          scheme: items.proxy_type,
          host: items.proxy_ip,
          port: parseInt(items.proxy_port)
        },
        bypassList: ["foobar.com"]
      }
    };
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (!config) {
        console.log('proxy config not defined');
        return;
    }
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "connect"){
        console.log('setting proxy');
        console.log(config); //shows 66.78.44.221 in the log...
        chrome.proxy.settings.set(
          {value: config, scope: 'regular'},
          function() {});
    }
});


问:
How to get all existing images src in this url with PHP?
There are 6 images in this url which I want to give src images. My goal is getting all images src with PHP but only one image src coming.</p>

```<code><?php
require_once ('simple_html_dom/simple_html_dom.php');
$html = file_get_html('https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142');
foreach($html->find('img') as $element){
     echo $element->src . '<br>';
}
?>
</code>```

答:
Actually those base64encodes are the images base64ecnoded images. As far as this page you want to parse although the images are base64 encoded the a tags that are the parents of the images actually are containing the image urls.

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);
</code>```

and now the data manipulation

```<code>libxml_use_internal_errors(true);
$siteData = new DOMDocument();
$siteData->loadHTML($data);

$a = $siteData->getElementsByTagName("a"); //get the a tags
for($i=0;$i<$a->length;$i++){
    if($a->item($i)->getAttribute("class")=="_seoImg"){ //_seoImg class   is the image class
       echo $a->item($i)->getAttribute("href").'<br/>';
    }
}
</code>```

and the result is

```<code>//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_1_1.jpg?ts=1508311623896
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_1_1_1.jpg?ts=1508311816920
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_3_1.jpg?ts=1508311715728
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_10_1.jpg?ts=1508315639664
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_2_1.jpg?ts=1508311682567
</code>```

Body:
There are 6 images in this url which I want to give src images. My goal is getting all images src with PHP but only one image src coming.

<?php
require_once ('simple_html_dom/simple_html_dom.php');
$html = file_get_html('https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142');
foreach($html->find('img') as $element){
     echo $element->src . '
';
}
?>

Body:
Actually those base64encodes are the images base64ecnoded images. As far as this page you want to parse although the images are base64 encoded the a tags that are the parents of the images actually are containing the image urls.

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);

and now the data manipulation

libxml_use_internal_errors(true);
$siteData = new DOMDocument();
$siteData->loadHTML($data);

$a = $siteData->getElementsByTagName("a"); //get the a tags
for($i=0;$i<$a->length;$i++){
    if($a->item($i)->getAttribute("class")=="_seoImg"){ //_seoImg class   is the image class
       echo $a->item($i)->getAttribute("href").'<br/>';
    }
}

and the result is

//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_1_1.jpg?ts=1508311623896
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_1_1_1.jpg?ts=1508311816920
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_3_1.jpg?ts=1508311715728
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_10_1.jpg?ts=1508315639664
//static.zara.net/photos///2017/I/1/1/p/5318/201/040/3/w/560/5318201040_2_2_1.jpg?ts=1508311682567


问:
Using jQuery in CRM Dynamics 365 webresource in popup-window
In my CRM Dynamics 365 solution I have a form with an embedded webresource A. This webresource A opens another webresource B in a popup-window using window.open. The opening could of course also be done using  Xrm.Utility.openWebResource.

I would like to utilize jQuery in webresource B. I am aware that CRM itself loads jQuery in some version, which is easy to spot when monitoring network requests and filtering for jquery.

The problem is that the webresource B doesn't have "access" to the jQuery or $-variable. The question is what you would recommend to do in order to use jQuery. I've prioritized a list of some possible solutions:

Load a webresource with an independent version of jQuery

An option I haven't thought of

Load it from a CDN

Look for all loaded scripts with jQuery and pass the URL to webresource B so it can load it by itself (almost a hack)

Avoid jQuery, use vanilla JS

UPDATE:
The main reason for using jQuery was to easily resize an iframe (with random contents) embedded in popup-window which displayed webresource B according to the dimensions of the popup-window.

I decided to lose jQuery altogether and use CSS instead. My solution became this which work nicely in Google Chrome, Windows Edge and Internet Explorer 11:

```<code>#externalframe {
    width: 100%;
    height: 100%;
    display: block;
    float: left;
}
</code>```

答:
I recommend Encapsulation & Namespacing of jQuery technique.

if you would like to quickly get access to the jQuery libraries in Dynamics CRM, you can install the SparkelXrm managed solution and include the web resource named ‘sparkle_/js/SparkleXrmUI_Dependancies.js’ – this is a single library that has both jQuery, jQueryUI as well as a few other goodies such as Knockout JS!

Body:
In my CRM Dynamics 365 solution I have a form with an embedded webresource A. This webresource A opens another webresource B in a popup-window using window.open. The opening could of course also be done using  Xrm.Utility.openWebResource.

I would like to utilize jQuery in webresource B. I am aware that CRM itself loads jQuery in some version, which is easy to spot when monitoring network requests and filtering for jquery.

The problem is that the webresource B doesn't have "access" to the jQuery or $-variable. The question is what you would recommend to do in order to use jQuery. I've prioritized a list of some possible solutions:

Load a webresource with an independent version of jQuery

An option I haven't thought of

Load it from a CDN

Look for all loaded scripts with jQuery and pass the URL to webresource B so it can load it by itself (almost a hack)

Avoid jQuery, use vanilla JS

UPDATE:
The main reason for using jQuery was to easily resize an iframe (with random contents) embedded in popup-window which displayed webresource B according to the dimensions of the popup-window.

I decided to lose jQuery altogether and use CSS instead. My solution became this which work nicely in Google Chrome, Windows Edge and Internet Explorer 11:

#externalframe {
    width: 100%;
    height: 100%;
    display: block;
    float: left;
}


问:
EXCEL VBA: Condensing multiple ranges with a SUMIF formula to one line
I have the following lines of code to fill specific ranges with SUMIF formulas:

```<code>Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
</code>```

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

```<code>Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))
</code>```

答:
To make it even shorter you could set the range values like so;

```<code>[B7:B9,B12:B13,B17,B21:B25,B29:B33,B37].Formula = "=SUMIF($M$2:$M$500,A7,$L$2:$L$500)"
</code>```

The [] is a shortcut for the range object

Body:
I have the following lines of code to fill specific ranges with SUMIF formulas:

Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))

Body:
To make it even shorter you could set the range values like so;

[B7:B9,B12:B13,B17,B21:B25,B29:B33,B37].Formula = "=SUMIF($M$2:$M$500,A7,$L$2:$L$500)"

The [] is a shortcut for the range object


问:
Can an inner class retrieve the instance of the top class?
The program I am working on uses nested classes. The top class is named Brain which has two inner classes, Neuron and Axon. The inner classes need to be able to modify the instance variables of the top class.

Brain keeps track of how many neurons and axons have been instantiated. Neuron holds information regarding its action potential and its outputs. Axon determines how to traverse the energy from one neuron to another. This way whenever I instantiate a neuron, it is saved within the instance of the brain. The same goes for the axon.

This is my code so far:

```<code>class Brain(object):
    def __init__(self):
        self.neurons = []
        self.axons = []

    class Neuron(object):
        def __init__(self, pos, AP_Energy, AP_threshold):
            # General attributes
            self.outputs = {}
            self.Energy = 0
            self.x, self.y = pos[0], pos[1]

            # Action Potential attributes
            self.AP_Energy = AP_Energy
            self.AP_threshold = AP_threshold

            """Append self to instance
               of Brain in neurons"""

        def add(self, value): self.Energy += value
        def link(self, neuron, weight): self.outputs[neuron] = weight

        def act(self):
            for neuron in self.outputs.keys():
                """Append Axon(self, neuron) to
                   instance of Brain in axons"""

    class Axon(object):
        def __init__(self, n1, n2):
            # Neurons
            self.n1, self.n2 = n1, n2

            # Action Potential attributes
            self.wavelength = sqrt((5*n1.AP_Energy)/3)
            self.distance = sqrt((n2.x-n1.x)**2+(n2.y-n1.y)**2)

        def action_potential(self): # Bunch of math stuff
</code>```

The idea is that you can create neurons without having to include the instance of the brain as one of its arguments. Therefore, if I want to create an instance of Brain with two neurons, it should appear as so:

```<code>EntityA = Brain()
EntityA.Neuron((0, 1), 15, 24)
EntityA.Neuron((4, 2), 30, 41)
</code>```

And if I need to call add() from the first neuron in EntityA, I should be able to refer to it as EntityA.neurons[0].add(value) since as I create the neurons it should automatically append itself to the list.

How would I go about doing this, and if it's not possible what can be done to give a similar result?

Edit: Using a function to both instantiate the class Neuron and saving it into a list within an instance of Brain seems the obvious answer. The problem occurs in the function Neuron.act() which instantiates the class Axon and must save it into a list that is in the same instance of Brain as used for the neuron. The previous constraints still apply.

答:
```<code>class Brain(object):
    def __init__(self):
        self.neurons = []
        self.axons = []

    class Neuron(object):
        ...

    class Axon(object):
        ...

    def add_neuron(self, pos, AP_Energy, AP_threshold):
        self.neurons.append(Brain.Neuron(pos, AP_Energy, AP_threshold))

EntityA = Brain()
EntityA.add_neuron((0, 10), 15, 24)
</code>```

Body:
The program I am working on uses nested classes. The top class is named Brain which has two inner classes, Neuron and Axon. The inner classes need to be able to modify the instance variables of the top class.

Brain keeps track of how many neurons and axons have been instantiated. Neuron holds information regarding its action potential and its outputs. Axon determines how to traverse the energy from one neuron to another. This way whenever I instantiate a neuron, it is saved within the instance of the brain. The same goes for the axon.

This is my code so far:

class Brain(object):
    def __init__(self):
        self.neurons = []
        self.axons = []

    class Neuron(object):
        def __init__(self, pos, AP_Energy, AP_threshold):
            # General attributes
            self.outputs = {}
            self.Energy = 0
            self.x, self.y = pos[0], pos[1]

            # Action Potential attributes
            self.AP_Energy = AP_Energy
            self.AP_threshold = AP_threshold

            """Append self to instance
               of Brain in neurons"""

        def add(self, value): self.Energy += value
        def link(self, neuron, weight): self.outputs[neuron] = weight

        def act(self):
            for neuron in self.outputs.keys():
                """Append Axon(self, neuron) to
                   instance of Brain in axons"""

    class Axon(object):
        def __init__(self, n1, n2):
            # Neurons
            self.n1, self.n2 = n1, n2

            # Action Potential attributes
            self.wavelength = sqrt((5*n1.AP_Energy)/3)
            self.distance = sqrt((n2.x-n1.x)**2+(n2.y-n1.y)**2)

        def action_potential(self): # Bunch of math stuff

The idea is that you can create neurons without having to include the instance of the brain as one of its arguments. Therefore, if I want to create an instance of Brain with two neurons, it should appear as so:

EntityA = Brain()
EntityA.Neuron((0, 1), 15, 24)
EntityA.Neuron((4, 2), 30, 41)

And if I need to call add() from the first neuron in EntityA, I should be able to refer to it as EntityA.neurons[0].add(value) since as I create the neurons it should automatically append itself to the list.

How would I go about doing this, and if it's not possible what can be done to give a similar result?

Edit: Using a function to both instantiate the class Neuron and saving it into a list within an instance of Brain seems the obvious answer. The problem occurs in the function Neuron.act() which instantiates the class Axon and must save it into a list that is in the same instance of Brain as used for the neuron. The previous constraints still apply.


问:
JavaFX - ListView item not selected upon Initialization
Hi all I have a fairly odd question regarding the initialization of a Scene in JavaFX that contains a ListView.

The issue is that when I initialize a scene for my program I want the first item of a ListView to be selected. However, if I am able to select it (through odd means mentioned later on) the ListView itself is not in focus. What I want to happen is that the first item in the ListView is selected and the ListView being in focus.

I'll start with minimal code to try and illustrate my issue:

```<code>public class SceneSetter {

static Stage mainStage;
static Scene adminScene;
static AdminController adminCont;

public static void initialize(Stage stage) throws IOException {
    mainStage = stage;

    FXMLLoader adminLoader = new FXMLLoader();
    adminLoader.setLocation(SceneSetter.class.getResource("/view/Admin.fxml"));
    SplitPane adminRoot = adminLoader.load();
    adminScene = new Scene(adminRoot);
    adminCont = adminLoader.getController();

    goToAdmin();
}

public static void goToAdmin() {
    mainStage.setScene(adminScene);
    //adminCont.initialize();
    mainStage.show();
}
}
</code>```

My original program has multiple scenes that all need to be set upon the program starting. So within this SceneSetter class all those scenes are set and the controllers added in. I have removed those as this bit of code is able to demonstrate the issue.

My admincontroller is as follows:

```<code>public class AdminController {
Stage mainStage;
private ObservableList<User> userList;

@FXML
private ListView<User> userListView;

@FXML
private Button adminAdd;

public void initialize() {
    userListView.setItems(Admin.getUserlist());
    userListView.getSelectionModel().select(0);
    userListView.getFocusModel().focus(0);
}

public void setMainStage(Stage s) {
    mainStage = s;
}
}
</code>```

The problem here is that when I run my code the item that I want to be selected is either:

Not selected

Not in Focus

My confusion is compounded bc of the following. If in my SceneSetter class, in my goToAdmin methods the commented line of code adminCont.initialize() is kept commented the program appears as follows:

When I uncomment the same line of code, the program appears as follows:

In the first instance, the correct item is not even selected. In the second, the ListView is not in focus.

How can I fix this issue?

答:
In order to focus a control you need to request it. The method you are searching for is requestFocus(). But there is a catch. Reading the JavaDoc :

To be eligible to receive the focus, the node must be part of a scene,
  it and all of its ancestors must be visible, and it must not be
  disabled

So that means you have two choices.

You could call the requestFocus() inside a Platform.runLater() in order to be sure that the scene graph have been created.

You could call the requestFocus() after you added the control on the Scene.

Example :

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class SceneSetter extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage mainStage) throws Exception {
        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList("Single", "Double", "Suite", "Family App");
        list.setItems(items);

        list.getSelectionModel().select(0);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                list.requestFocus();
            }
        });

        mainStage.setScene(new Scene(list));
        // or here
        // list.requestFocus();
        mainStage.show();
    }

}
</code>```

An example with FXML file

Main :

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class SceneSetter extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage mainStage) throws Exception {
        ListView<String> list = FXMLLoader.load(this.getClass().getResource("GUI.fxml"));

        mainStage.setScene(new Scene(list));

        mainStage.show();
    }

}
</code>```

Controller :

```<code>import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;

public class MyController {

    @FXML
    private ListView<String> userListView;

    @FXML
    public void initialize() {

        ObservableList<String> items = FXCollections.observableArrayList("Single", "Double", "Suite", "Family App");
        userListView.setItems(items);
        userListView.getSelectionModel().select(0);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                userListView.requestFocus();
            }
        });
    }
}
</code>```

Body:
Hi all I have a fairly odd question regarding the initialization of a Scene in JavaFX that contains a ListView.

The issue is that when I initialize a scene for my program I want the first item of a ListView to be selected. However, if I am able to select it (through odd means mentioned later on) the ListView itself is not in focus. What I want to happen is that the first item in the ListView is selected and the ListView being in focus.

I'll start with minimal code to try and illustrate my issue:

public class SceneSetter {

static Stage mainStage;
static Scene adminScene;
static AdminController adminCont;

public static void initialize(Stage stage) throws IOException {
    mainStage = stage;

    FXMLLoader adminLoader = new FXMLLoader();
    adminLoader.setLocation(SceneSetter.class.getResource("/view/Admin.fxml"));
    SplitPane adminRoot = adminLoader.load();
    adminScene = new Scene(adminRoot);
    adminCont = adminLoader.getController();

    goToAdmin();
}

public static void goToAdmin() {
    mainStage.setScene(adminScene);
    //adminCont.initialize();
    mainStage.show();
}
}

My original program has multiple scenes that all need to be set upon the program starting. So within this SceneSetter class all those scenes are set and the controllers added in. I have removed those as this bit of code is able to demonstrate the issue.

My admincontroller is as follows:

public class AdminController {
Stage mainStage;
private ObservableList<User> userList;

@FXML
private ListView<User> userListView;

@FXML
private Button adminAdd;

public void initialize() {
    userListView.setItems(Admin.getUserlist());
    userListView.getSelectionModel().select(0);
    userListView.getFocusModel().focus(0);
}

public void setMainStage(Stage s) {
    mainStage = s;
}
}

The problem here is that when I run my code the item that I want to be selected is either:

Not selected

Not in Focus

My confusion is compounded bc of the following. If in my SceneSetter class, in my goToAdmin methods the commented line of code adminCont.initialize() is kept commented the program appears as follows:

When I uncomment the same line of code, the program appears as follows:

In the first instance, the correct item is not even selected. In the second, the ListView is not in focus.

How can I fix this issue?

Body:
In order to focus a control you need to request it. The method you are searching for is requestFocus(). But there is a catch. Reading the JavaDoc :

To be eligible to receive the focus, the node must be part of a scene,
  it and all of its ancestors must be visible, and it must not be
  disabled

So that means you have two choices.

You could call the requestFocus() inside a Platform.runLater() in order to be sure that the scene graph have been created.

You could call the requestFocus() after you added the control on the Scene.

Example :

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class SceneSetter extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage mainStage) throws Exception {
        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList("Single", "Double", "Suite", "Family App");
        list.setItems(items);

        list.getSelectionModel().select(0);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                list.requestFocus();
            }
        });

        mainStage.setScene(new Scene(list));
        // or here
        // list.requestFocus();
        mainStage.show();
    }

}

An example with FXML file

Main :

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

public class SceneSetter extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage mainStage) throws Exception {
        ListView<String> list = FXMLLoader.load(this.getClass().getResource("GUI.fxml"));

        mainStage.setScene(new Scene(list));

        mainStage.show();
    }

}

Controller :

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;

public class MyController {

    @FXML
    private ListView<String> userListView;

    @FXML
    public void initialize() {

        ObservableList<String> items = FXCollections.observableArrayList("Single", "Double", "Suite", "Family App");
        userListView.setItems(items);
        userListView.getSelectionModel().select(0);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                userListView.requestFocus();
            }
        });
    }
}


问:
Selecting MySql table data into an array
I try to catch data from mysql to put them all in array.
Suppose:

```<code>    users table
    -----------------------
    id| name | code
    ----------------------
    1| gorge | 2132
    2| flix | ksd02
    3| jasmen | skaod2

    $sql = mysql_query("select id, name, code from users");
    $userinfo = array()
    while($row_user = mysql_fetch_array($sql)){
    $userinfo = $row_user[name]
    }
-------------------------
foreach($userinfo as $usinfo){
echo $usinfo."<br/>";
}
</code>```

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.

答:
```<code>   while($row_user = mysql_fetch_array($sql)){
    $row_id = $row_user ["id"];
        $row_author = $row_user ["author"];
        $row_code = $row_user ["code"];
       $userinfo[] = array("id"=> $row_id , "author"=> $row_author, "code"=> $row_code);
    }
foreach ($userinfo as $user) {
    echo "Id: {$user[id]}\n"
       . "Name: {$user[name]}\n"
       . "Code: {$user[code]}\n\n";
}
</code>```

Body:
I try to catch data from mysql to put them all in array.
Suppose:

    users table
    -----------------------
    id| name | code
    ----------------------
    1| gorge | 2132
    2| flix | ksd02
    3| jasmen | skaod2

    $sql = mysql_query("select id, name, code from users");
    $userinfo = array()
    while($row_user = mysql_fetch_array($sql)){
    $userinfo = $row_user[name]
    }
-------------------------
foreach($userinfo as $usinfo){
echo $usinfo."
";
}

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.


问:
Apache 2.4 redirect https to another port
I'm a rookie, but I've struggled with this for some time and I am definitely doing something wrong.

We use Apache 2.4 as the front of our internal web pages.

When I try to forward a request to a port other than 80, it goes crazy and is redirected several times
http://demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/[...]/demos.company.com/WebApplicationFail

httpd.conf:

```<code>LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so

<VirtualHost *:80>
    RewriteEngine on
    RewriteCond %{HTTPS} !on
    RewriteRule ^(.*) %{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile "C:/Program Files/Apache24/conf/ssl/company.crt"
    SSLCertificateKeyFile "C:/Program Files/Apache24/conf/ssl/company.key"
    SSLCertificateChainFile "C:/Program Files/Apache24/conf/ssl/CA.pem"

    # Proxy configuration
    ProxyPreserveHost On
    ProxyRequests Off
    ServerName demos.company.com

    ProxyPass /WebApplicationOK http://10.0.0.160/WebApplicationOK
    ProxyPassReverse /WebApplicationOK http://10.0.0.160/WebApplicationOK
    ProxyPass /WebApplicationFailRoute http://10.0.0.125:8000/WebApplicationFail
    ProxyPassReverse /WebApplicationFailRoute http://10.0.0.125:8000/WebApplicationFail
</VirtualHost>
</code>```

We need to maintain the redirection of every http request to https.

If possible, we need that the Internet address "https://demos.company.com/ThisContext" show the intranet web "http://10.0.0.125:8000/OtherContext".

Thanks in advance.

答:
That's the problem with adding complex directives for trivial tasks.

You have a Virtualhost which uses port 80, why even check for SSL?, everything it will receive will not be SSL.

Also the rewrite directive is missing the scheme.

So just:

```<code>RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [R,L]
</code>```

If you don't need to use variables, for variable host names I would go even simpler:

```<code>Redirect / https://whateverhost.example.com/
</code>```

Rule to success in httpd: Go always with the most simple option.

Body:
I'm a rookie, but I've struggled with this for some time and I am definitely doing something wrong.

We use Apache 2.4 as the front of our internal web pages.

When I try to forward a request to a port other than 80, it goes crazy and is redirected several times
http://demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/demos.company.com/[...]/demos.company.com/WebApplicationFail

httpd.conf:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so

<VirtualHost *:80>
    RewriteEngine on
    RewriteCond %{HTTPS} !on
    RewriteRule ^(.*) %{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile "C:/Program Files/Apache24/conf/ssl/company.crt"
    SSLCertificateKeyFile "C:/Program Files/Apache24/conf/ssl/company.key"
    SSLCertificateChainFile "C:/Program Files/Apache24/conf/ssl/CA.pem"

    # Proxy configuration
    ProxyPreserveHost On
    ProxyRequests Off
    ServerName demos.company.com

    ProxyPass /WebApplicationOK http://10.0.0.160/WebApplicationOK
    ProxyPassReverse /WebApplicationOK http://10.0.0.160/WebApplicationOK
    ProxyPass /WebApplicationFailRoute http://10.0.0.125:8000/WebApplicationFail
    ProxyPassReverse /WebApplicationFailRoute http://10.0.0.125:8000/WebApplicationFail
</VirtualHost>

We need to maintain the redirection of every http request to https.

If possible, we need that the Internet address "https://demos.company.com/ThisContext" show the intranet web "http://10.0.0.125:8000/OtherContext".

Thanks in advance.

Body:
That's the problem with adding complex directives for trivial tasks.

You have a Virtualhost which uses port 80, why even check for SSL?, everything it will receive will not be SSL.

Also the rewrite directive is missing the scheme.

So just:

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [R,L]

If you don't need to use variables, for variable host names I would go even simpler:

Redirect / https://whateverhost.example.com/

Rule to success in httpd: Go always with the most simple option.


问:
Automapper returning "default" instance of mapped entity
I'm trying to get automapper working for .NET core, and I seem to be missing something important.

I have my automapper set up as follows:

In Startup.cs in my ConfigureServices method, I have the following line:

```<code>services.AddAutoMapper(typeof(Startup), typeof(ApplicationDbContext));
</code>```

I also have a class called MappingProfile which resembles this:

```<code>public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<CfGroup, GroupModel>()
            .IgnoreAllUnmapped();
        CreateMap<GroupModel, CfGroup>()
            .IgnoreAllUnmapped();
        ...
    }
}
</code>```

The IgnoreAllUnmapped was suggested by another SO question, and it looks like this:

```<code>    public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(
        this IMappingExpression<TSource, TDest> expression)
    {
        expression.ForAllMembers(opt => opt.Ignore());
        return expression;
    }
</code>```

My CfGroup looks like this:

```<code>[Table("Groups")]
public class CfGroup
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(100)]
    [Required]
    public string Name { get; set; }

    [DataType(DataType.ImageUrl)]
    [StringLength(250)]
    public string ImageUrl { get; set; }

    [Required]
    public int FounderId { get; set; }

    [ForeignKey("FounderId")]
    public virtual CfUser Founder { get; set; }

    [Required]
    public bool IsActive { get; set; }

    [Required]
    public DateTime CreatedTimestampUtc { get; set; }

    [StringLength(3000)]
    public string About { get; set; }

    public virtual ISet<UserGroupMember> Members { get; set; }

    public virtual ISet<UserGroupManager> Managers { get; set; }
}
</code>```

... and my GroupModel looks like this:

```<code>public class GroupModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string ImageUrl { get; set; }

    public string About { get; set; }
}
</code>```

When calling my web api endpoint, I get a collection of CfGroup entities from the database just fine.  I then run a command like so:

```<code>var dtos = entities.Select(_mapper.Map<GroupModel>);
</code>```

...but my dtos are "empty"... IOW, the instance is created, but Id value is set to 0 and all the string values are set to null.  That is definitely not what is in the entities variable.

I have also tried to explicitly convert it like so:

```<code>var dtos = entities.Select(x => _mapper.Map<GroupModel>(x));
</code>```

and, postulating that it's an IEnumerable issue, tried making a List out of it:

```<code>var dtos = entities.Select(x => _mapper.Map<GroupModel>(x)).ToList();
</code>```

...but no matter what, the DTO's remain instantiated, but with all properties set to their default values.

What am I doing wrong?

答:
I suspect it may be because you are mapping inside your linq expression. try something like this:</p>

```<code>var dtos = _mapper.Map<IEnumerable<GroupModel>>(entities.ToList());
</code>```

Body:
I'm trying to get automapper working for .NET core, and I seem to be missing something important.

I have my automapper set up as follows:

In Startup.cs in my ConfigureServices method, I have the following line:

services.AddAutoMapper(typeof(Startup), typeof(ApplicationDbContext));

I also have a class called MappingProfile which resembles this:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<CfGroup, GroupModel>()
            .IgnoreAllUnmapped();
        CreateMap<GroupModel, CfGroup>()
            .IgnoreAllUnmapped();
        ...
    }
}

The IgnoreAllUnmapped was suggested by another SO question, and it looks like this:

    public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(
        this IMappingExpression<TSource, TDest> expression)
    {
        expression.ForAllMembers(opt => opt.Ignore());
        return expression;
    }

My CfGroup looks like this:

[Table("Groups")]
public class CfGroup
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(100)]
    [Required]
    public string Name { get; set; }

    [DataType(DataType.ImageUrl)]
    [StringLength(250)]
    public string ImageUrl { get; set; }

    [Required]
    public int FounderId { get; set; }

    [ForeignKey("FounderId")]
    public virtual CfUser Founder { get; set; }

    [Required]
    public bool IsActive { get; set; }

    [Required]
    public DateTime CreatedTimestampUtc { get; set; }

    [StringLength(3000)]
    public string About { get; set; }

    public virtual ISet<UserGroupMember> Members { get; set; }

    public virtual ISet<UserGroupManager> Managers { get; set; }
}

... and my GroupModel looks like this:

public class GroupModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string ImageUrl { get; set; }

    public string About { get; set; }
}

When calling my web api endpoint, I get a collection of CfGroup entities from the database just fine.  I then run a command like so:

var dtos = entities.Select(_mapper.Map<GroupModel>);

...but my dtos are "empty"... IOW, the instance is created, but Id value is set to 0 and all the string values are set to null.  That is definitely not what is in the entities variable.

I have also tried to explicitly convert it like so:

var dtos = entities.Select(x => _mapper.Map<GroupModel>(x));

and, postulating that it's an IEnumerable issue, tried making a List out of it:

var dtos = entities.Select(x => _mapper.Map<GroupModel>(x)).ToList();

...but no matter what, the DTO's remain instantiated, but with all properties set to their default values.

What am I doing wrong?

Body:
I suspect it may be because you are mapping inside your linq expression. try something like this:

var dtos = _mapper.Map<IEnumerable<GroupModel>>(entities.ToList());


问:
Break up a SQL Server 2008 query into batches
I'm trying to prepare some data for deletion by a 3rd party, and unfortunately they can only process data in batches of 2000 records.  I have 100k records and may need to divide-and-export this data several more times, so I'd like to automate the process somehow.

Is there a reasonably easy way to do this using SQL Server 2008?  I'm not running a complex query -- it's not too far off from SELECT PKID FROM Sometable ORDER BY PKID -- and while I can probably do this using a cursor, I'd like to know if there's a better way.

答:
I think you can take advantage of using ROW_NUMBER and then using BETWEEN to specify a range of rows that you like. Alternatively you could use PKID if you knew there wasn't gaps, or didn't care about the gaps

e.g.

```<code>SELECT ...
FROM
   (SELECT ...
         ROW_NUMBER() OVER(ORDER BY PKID ) as RowNum
    FROM Sometable e
   ) t
WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
</code>```

This is often used for paging results. 4GuysFromRolla have a good article on it

Body:
I think you can take advantage of using ROW_NUMBER and then using BETWEEN to specify a range of rows that you like. Alternatively you could use PKID if you knew there wasn't gaps, or didn't care about the gaps

e.g.

SELECT ...
FROM
   (SELECT ...
         ROW_NUMBER() OVER(ORDER BY PKID ) as RowNum
    FROM Sometable e
   ) t
WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1

This is often used for paging results. 4GuysFromRolla have a good article on it


问:
Split dataFrames based on column header prefix
I have a data frame where the column names share a common element, other columns have been generated with a suffix to this common element. I have a list of these elements that is around ~100 entries. I'd like to iteratively slice the large df using this list, transform the sub-df's by grouping and eventually concatenate them back together.

I was thinking of using a dictionary approach-- using the list as keys, and then defining the columns sharing this element as values. I am not sure how to implement this. I have copied a simplified version to illustrate what I'd like to scale up. In reality there'd be around 100 keys each with 20 associated columns.

```<code>   A A_1 A_2 A_3  B B_1 B_2 B_3
0  1   e   f   g  1   x   y   z
1  2   e   f   g  2   x   y   z
2  3   e   f   g  3   x   y   z
3  3   e   f   g  3   x   y   z
4  3   e   f   g  4   x   y   z
5  3   e   f   g  4   x   y   z

df_list = ['A','B']

df_A = df[df.columns[df.columns.to_series().str.contains('A')]]

df_B = df[df.columns[df.columns.to_series().str.contains('B')]]

calc_A = df_A.groupby(['A']).head(1)
print(calc_A)

   A A_1 A_2 A_3
0  1   e   f   g
1  2   e   f   g
2  3   e   f   g

calc_B = df_B.groupby(['B']).head(1)
print(calc_B)

   B B_1 B_2 B_3
0  1   x   y   z
1  2   x   y   z
2  3   x   y   z
4  4   x   y   z
</code>```

Please advise how to structure this dictionary, iterating through the list to slice the df and assign columns sharing the key as values for the new sub-df. Thank you.

答:
IIUC, you can group on column prefixes, and then initialise a dictionary:

```<code>d = {}
for i, g in df.groupby(by=lambda x: x.split('_')[0], axis=1):
    d[i] = g.groupby(i).head(1)
</code>```

You could also do this using a dict comprehension:

```<code>d = {
        i : g.groupby(i).head(1)
        for (i, g) in df.groupby(by=lambda x: x.split('_')[0], axis=1)
}

for k, v in d.items():
    print(v, '\n')

   A A_1 A_2 A_3
0  1   e   f   g
1  2   e   f   g
2  3   e   f   g

   B B_1 B_2 B_3
0  1   x   y   z
1  2   x   y   z
2  3   x   y   z
4  4   x   y   z

d.keys()
dict_keys(['A', 'B'])
</code>```

Body:
I have a data frame where the column names share a common element, other columns have been generated with a suffix to this common element. I have a list of these elements that is around ~100 entries. I'd like to iteratively slice the large df using this list, transform the sub-df's by grouping and eventually concatenate them back together.

I was thinking of using a dictionary approach-- using the list as keys, and then defining the columns sharing this element as values. I am not sure how to implement this. I have copied a simplified version to illustrate what I'd like to scale up. In reality there'd be around 100 keys each with 20 associated columns.

   A A_1 A_2 A_3  B B_1 B_2 B_3
0  1   e   f   g  1   x   y   z
1  2   e   f   g  2   x   y   z
2  3   e   f   g  3   x   y   z
3  3   e   f   g  3   x   y   z
4  3   e   f   g  4   x   y   z
5  3   e   f   g  4   x   y   z

df_list = ['A','B']

df_A = df[df.columns[df.columns.to_series().str.contains('A')]]

df_B = df[df.columns[df.columns.to_series().str.contains('B')]]

calc_A = df_A.groupby(['A']).head(1)
print(calc_A)

   A A_1 A_2 A_3
0  1   e   f   g
1  2   e   f   g
2  3   e   f   g

calc_B = df_B.groupby(['B']).head(1)
print(calc_B)

   B B_1 B_2 B_3
0  1   x   y   z
1  2   x   y   z
2  3   x   y   z
4  4   x   y   z

Please advise how to structure this dictionary, iterating through the list to slice the df and assign columns sharing the key as values for the new sub-df. Thank you.

Body:
IIUC, you can group on column prefixes, and then initialise a dictionary:

d = {}
for i, g in df.groupby(by=lambda x: x.split('_')[0], axis=1):
    d[i] = g.groupby(i).head(1)

You could also do this using a dict comprehension:

d = {
        i : g.groupby(i).head(1)
        for (i, g) in df.groupby(by=lambda x: x.split('_')[0], axis=1)
}

for k, v in d.items():
    print(v, '\n')

   A A_1 A_2 A_3
0  1   e   f   g
1  2   e   f   g
2  3   e   f   g

   B B_1 B_2 B_3
0  1   x   y   z
1  2   x   y   z
2  3   x   y   z
4  4   x   y   z

d.keys()
dict_keys(['A', 'B'])


问:
Why does Kubernetes try to create a load balancer for a service type ClusterIP?
I'm using an Ingress to expose my services from outside the Kubernetes cluster, so I don't need Kubernetes to provision a loadbalancer. Therefore, I created a ClusterIP service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp
  namespace: default
spec:
  ports:
  - port: 80
    targetPort: 8080
  selector:
    app: myapp
  type: ClusterIP
</code>```

This works - I have a separate Ingress and Deployment set up and I can access the app just fine.

However, Kubernetes insists on trying to create a loadbalancer anyway. Since it doesn't have permission in my AWS account do so, every service I create logs errors like this:

```<code>FirstSeen   LastSeen    Count   From            SubObjectPath   Type        Reason              Message
  --------- --------    -----   ----            -------------   --------    ------              -------
  22s       22s     1   service-controller          Warning     CreatingLoadBalancerFailed  Error creating load balancer (will retry): Error getting LB for service default/myapp: AccessDenied: User: -redacted- is not authorized to perform: elasticloadbalancing:DescribeLoadBalancers with an explicit deny
        status code: 403, request id: -redacted-
</code>```

I assume that it's trying to DescribeLoadBalancers because it intends to create one. The docs claim that loadbalancers should only be created when you specify service type "LoadBalancer". How can I stop Kubernetes from trying anyway?

答:
It is not trying to create one. You are receiving the error message from service_controller.go:287:

```<code>func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *v1.Service) (error, bool) {
    [...]
    if !wantsLoadBalancer(service) {
        _, exists, err := s.balancer.GetLoadBalancer(s.clusterName, service)
        if err != nil {
            return fmt.Errorf("Error getting LB for service %s: %v", key, err), retryable
        }
        [...]
</code>```

In turn GetLoadBalancer is calling the cloudprovider to describe (check if one exists). I suggest you authorize the aws service account for this particular action.

Body:
I'm using an Ingress to expose my services from outside the Kubernetes cluster, so I don't need Kubernetes to provision a loadbalancer. Therefore, I created a ClusterIP service:

apiVersion: v1
kind: Service
metadata:
  name: myapp
  namespace: default
spec:
  ports:
  - port: 80
    targetPort: 8080
  selector:
    app: myapp
  type: ClusterIP

This works - I have a separate Ingress and Deployment set up and I can access the app just fine.

However, Kubernetes insists on trying to create a loadbalancer anyway. Since it doesn't have permission in my AWS account do so, every service I create logs errors like this:

FirstSeen   LastSeen    Count   From            SubObjectPath   Type        Reason              Message
  --------- --------    -----   ----            -------------   --------    ------              -------
  22s       22s     1   service-controller          Warning     CreatingLoadBalancerFailed  Error creating load balancer (will retry): Error getting LB for service default/myapp: AccessDenied: User: -redacted- is not authorized to perform: elasticloadbalancing:DescribeLoadBalancers with an explicit deny
        status code: 403, request id: -redacted-

I assume that it's trying to DescribeLoadBalancers because it intends to create one. The docs claim that loadbalancers should only be created when you specify service type "LoadBalancer". How can I stop Kubernetes from trying anyway?

Body:
It is not trying to create one. You are receiving the error message from service_controller.go:287:

func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *v1.Service) (error, bool) {
    [...]
    if !wantsLoadBalancer(service) {
        _, exists, err := s.balancer.GetLoadBalancer(s.clusterName, service)
        if err != nil {
            return fmt.Errorf("Error getting LB for service %s: %v", key, err), retryable
        }
        [...]

In turn GetLoadBalancer is calling the cloudprovider to describe (check if one exists). I suggest you authorize the aws service account for this particular action.


问:
How to create a dictionary of arrays to strings in Python?
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

```<code>a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
</code>```

Both codes are free of errors but obviously they don't match. Here is my idea:

```<code>b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']
</code>```

Thanks in advance.

答:
You can grab the string using a tuple as a key. The reason you can't use a list as a key is because lists can be modified, and you wouldn't other spots in your code modifying your dictionary keys.

```<code>>>> a[[1,1,0,0]] # Won't work because it's not a tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> a[(1,1,0,0)] # Works
'Car'
</code>```

If you want to use the list as a key, then you can convert it

```<code>>>> a[tuple([1,1,0,0])]
'Car'
</code>```

If you have a list of arrays (like in your example) then you can grab all their matching strings like this

```<code>>>> b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
>>> [a[tuple(eachList)] for eachList in b]
['Car','Traffic Light','Pedestrian']
</code>```

Body:
I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])

Both codes are free of errors but obviously they don't match. Here is my idea:

b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']

Thanks in advance.

Body:
You can grab the string using a tuple as a key. The reason you can't use a list as a key is because lists can be modified, and you wouldn't other spots in your code modifying your dictionary keys.

>>> a[[1,1,0,0]] # Won't work because it's not a tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> a[(1,1,0,0)] # Works
'Car'

If you want to use the list as a key, then you can convert it

>>> a[tuple([1,1,0,0])]
'Car'

If you have a list of arrays (like in your example) then you can grab all their matching strings like this

>>> b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
>>> [a[tuple(eachList)] for eachList in b]
['Car','Traffic Light','Pedestrian']


问:
Check variable equality against a list of values
I'm checking a variable, say foo, for equality to a number of values. For example,

```<code>if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}
</code>```

The point is that it is rather much code for such a trivial task. I came up with the following:

```<code>if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}
</code>```

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

答:
Using the answers provided, I ended up with the following:

```<code>Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}
</code>```

It can be called like:

```<code>if(foo.in(1, 3, 12)) {
    // ...
}
</code>```

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

```<code>/foo|bar|something/.test(str);
</code>```

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

```<code>/^(foo|bar|something)$/.test(str);
</code>```

Body:
I'm checking a variable, say foo, for equality to a number of values. For example,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

Body:
Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
    // ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);


问:
Elixir Macro issue with unquoting
Can you please have a look at my Macro?
I am getting undefined function number/0 error, and I can't figure it out why.

```<code> defmodule DbUtil do
        defmacro __using__(opts) do
            quote do
              import unquote(__MODULE__)
              @before_compile unquote(__MODULE__)
            end
        end

        defmacro __before_compile__(%{module: definition} = _env) do

            quote do
                import Ecto.Query

                def last do
                    from x in unquote(definition), order_by: [desc: x.id], limit: 1
                end

                # This dumps error
                def limits(number) do
                    from a in unquote(definition), limit: ^unquote(number)
                end
            end

        end
    end
</code>```

答:
You don't need to unquote number. unquote is used when you want to inject a variable present outside the quote block. Since number is defined inside the quote, you don't need to unquote. The following should work for you:

```<code>def limits(number) do
  from a in unquote(definition), limit: ^number
end
</code>```

Title: Elixir Macro issue with unquoting

Body:
Can you please have a look at my Macro?
I am getting undefined function number/0 error, and I can't figure it out why.

 defmodule DbUtil do
        defmacro __using__(opts) do
            quote do
              import unquote(__MODULE__)
              @before_compile unquote(__MODULE__)
            end
        end

        defmacro __before_compile__(%{module: definition} = _env) do

            quote do
                import Ecto.Query

                def last do
                    from x in unquote(definition), order_by: [desc: x.id], limit: 1
                end

                # This dumps error
                def limits(number) do
                    from a in unquote(definition), limit: ^unquote(number)
                end
            end

        end
    end

Body:
You don't need to unquote number. unquote is used when you want to inject a variable present outside the quote block. Since number is defined inside the quote, you don't need to unquote. The following should work for you:

def limits(number) do
  from a in unquote(definition), limit: ^number
end


问:
Implementing a dynamic Time Zone selector Angular 2/4/5
I need to build a TimeZone selector in my Angular 4/5 Application. When a user changes the timezone, I expect all displayed time values on the page to update immediately.

I was planning to use:

momentjs with timezone support using angular2-moment and angular-moment-timezone.

To format the date use amLocal pipe, followed by other pipes.

When user selects a different time zone, I am planning to call moment.tz.setDefault(_timezone)

With the above values from this point on gets formatted as new time zone, while currently displayed time values do not change. Angular change detection mechanism does not update displayed time values, as the input values have not changed.

I do not want to create an 'impure' pipe because of performance overheads (considering timezone change is not a frequent activity).

As fallback I can create a pipe (or use an existing one) that takes the current time zone as parameter. It actually works but I will need to pass around the current time zone value to each component and template.

I have not been able to find a way for Angular change detection to believe there is a change even when there was no change of values.

Any suggestions will be welcome.

答:
When using for example ngx-translate for example, switching the language imply fetching new translation. As you can see here they use an impure Pipe which as you said imply performance issues.

The other way I imagine is to define a component DateComponent available for your whole app. That way, instead of having in your html {{ value | formatDate }} you'll have <custom-date [date]="new Date()"></custom-date>.

In your custom date component will look like this

```<code>@Component({
  selector: 'custom-date',
  template: '<span>{{ formatedDate }}</span>'
})
export class DateComponent {
  @Input() date: string;
  timezone: string;
  formatedDate: string;
  constructor(private userService: UserService) {}

  ngOnInit(){
    this.timezone = this.userService.getTimeZone();
    this.updateValue();
    this.userService.onTimezoneChange()
      .subscribe(timezone => {
        this.timezone = timezone;
        this.updateValue();
      });
  }

  updateValue() {
    // Do your formatting the way you want
    this.formatedDate = moment(this.date).tz(this.timezone).format();
  }
}
</code>```

Body:
When using for example ngx-translate for example, switching the language imply fetching new translation. As you can see here they use an impure Pipe which as you said imply performance issues.

The other way I imagine is to define a component DateComponent available for your whole app. That way, instead of having in your html {{ value | formatDate }} you'll have <custom-date [date]="new Date()"></custom-date>.

In your custom date component will look like this

@Component({
  selector: 'custom-date',
  template: '<span>{{ formatedDate }}</span>'
})
export class DateComponent {
  @Input() date: string;
  timezone: string;
  formatedDate: string;
  constructor(private userService: UserService) {}

  ngOnInit(){
    this.timezone = this.userService.getTimeZone();
    this.updateValue();
    this.userService.onTimezoneChange()
      .subscribe(timezone => {
        this.timezone = timezone;
        this.updateValue();
      });
  }

  updateValue() {
    // Do your formatting the way you want
    this.formatedDate = moment(this.date).tz(this.timezone).format();
  }
}