问:
DynamoDB auto scaling with Cloudformation
AWS released auto scaling for DynamoDB. I would like to know how to create a Table with auto scaling via Cloudformation.</p>

答:
Here is the ClodFormation auto-scaling policy for DynamoDB table. Hope it gives you some idea about how to form the policy script.

```<code>{
  "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy",
  "Properties" : {
    "PolicyName" : "MyScalingPolicy",
    "PolicyType" : "TargetTrackingScaling",
    "ResourceId" : "arn:aws:dynamodb:us-east-1:123456789012:table/books_table",
    "ScalableDimension" : "dynamodb:table:WriteCapacityUnits",
    "ServiceNamespace" : "dynamodb",
    "TargetTrackingScalingPolicyConfiguration" : {
    "PredefinedMetricSpecification": {
            "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
        },
        "ScaleOutCooldown": 60,
        "ScaleInCooldown": 60,
        "TargetValue": 50.0
    }
  }
}
</code>```

References:-

CloudFormaction auto-scaling policy

AWS CLI command for auto scaling

AWS CLI Command:-

```<code>aws application-autoscaling put-scaling-policy \
    --service-namespace dynamodb \
    --resource-id "table/TestTable" \
    --scalable-dimension "dynamodb:table:WriteCapacityUnits" \
    --policy-name "MyScalingPolicy" \
    --policy-type "TargetTrackingScaling" \
    --target-tracking-scaling-policy-configuration file://scaling-policy.json
</code>```

scaling-policy.json:-

```<code>{
    "PredefinedMetricSpecification": {
        "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
    },
    "ScaleOutCooldown": 60,
    "ScaleInCooldown": 60,
    "TargetValue": 50.0
}
</code>```

Body:
Here is the ClodFormation auto-scaling policy for DynamoDB table. Hope it gives you some idea about how to form the policy script.

{
  "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy",
  "Properties" : {
    "PolicyName" : "MyScalingPolicy",
    "PolicyType" : "TargetTrackingScaling",
    "ResourceId" : "arn:aws:dynamodb:us-east-1:123456789012:table/books_table",
    "ScalableDimension" : "dynamodb:table:WriteCapacityUnits",
    "ServiceNamespace" : "dynamodb",
    "TargetTrackingScalingPolicyConfiguration" : {
    "PredefinedMetricSpecification": {
            "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
        },
        "ScaleOutCooldown": 60,
        "ScaleInCooldown": 60,
        "TargetValue": 50.0
    }
  }
}

References:-

CloudFormaction auto-scaling policy

AWS CLI command for auto scaling

AWS CLI Command:-

aws application-autoscaling put-scaling-policy \
    --service-namespace dynamodb \
    --resource-id "table/TestTable" \
    --scalable-dimension "dynamodb:table:WriteCapacityUnits" \
    --policy-name "MyScalingPolicy" \
    --policy-type "TargetTrackingScaling" \
    --target-tracking-scaling-policy-configuration file://scaling-policy.json

scaling-policy.json:-

{
    "PredefinedMetricSpecification": {
        "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
    },
    "ScaleOutCooldown": 60,
    "ScaleInCooldown": 60,
    "TargetValue": 50.0
}


来源: stackexchange

问:
Why is the size of this struct 32?
This is the struct.

```<code>//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};
</code>```

This is my code to display the size of this struct :

```<code>    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);
</code>```

The MessageBox displays 32.
Thank you!

答:
What packing? And compiled for what platform? Alignment requirement differ between x86, AMD64 and IA64. And packing can wreak havoc in a struct size.

Assuming default packing (8) and AMD64 target (or x86, wouldn't differ) you have 8 bytes for the brilliance (4 bytes size, 4 bytes wasted), 8 bytes for contraste and then 16 bytes for the convolution (9 bytes size, 7 bytes wasted). Total 32, which seems just about what you get.

ContentLicense: CC BY-SA 2.5

Title: Why is the size of this struct 32?

Body:
This is the struct.

//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};

This is my code to display the size of this struct :

    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);

The MessageBox displays 32.
Thank you!


问:
proper installation of node
My understanding is that NVM is the preferred way to install and manage node versions over Homebrew.
I have a couple versions of Node installed with NVM. But it looks like the Homebrew installation is still there too.  I tried brew uninstall node but got an error

```<code>Error: Refusing to uninstall /usr/local/Cellar/node/8.0.0_1
because it is required by babel 6.24.1, yarn 0.24.6, which are
currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies node
</code>```

答:
You have two packages installed by Homebrew (babel and yarn) that depends on node. You have two choices:

1) You don't need babel and yarn anymore. You can remove them with:

```<code>brew uninstall babel
brew uninstall yarn
</code>```

and then you will be able to remove the node version installed by Homebrew:

```<code>brew uninstall node
</code>```

2) You want to keep babel and yarn. Both of these packages depend on node. If you install a node version with nvm, they will rely on this new version. So you can uninstall the homebrew version with:

```<code>brew uninstall --ignore-dependencies node
</code>```

ContentLicense: CC BY-SA 3.0

Title: proper installation of node

Body:
My understanding is that NVM is the preferred way to install and manage node versions over Homebrew.
I have a couple versions of Node installed with NVM. But it looks like the Homebrew installation is still there too.  I tried brew uninstall node but got an error

Error: Refusing to uninstall /usr/local/Cellar/node/8.0.0_1
because it is required by babel 6.24.1, yarn 0.24.6, which are
currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies node

Body:
You have two packages installed by Homebrew (babel and yarn) that depends on node. You have two choices:

1) You don't need babel and yarn anymore. You can remove them with:

brew uninstall babel
brew uninstall yarn

and then you will be able to remove the node version installed by Homebrew:

brew uninstall node

2) You want to keep babel and yarn. Both of these packages depend on node. If you install a node version with nvm, they will rely on this new version. So you can uninstall the homebrew version with:

brew uninstall --ignore-dependencies node


问:
C#: Throw an exception without overwriting the currently-active one
Take the following minimal example:

```<code>try { foo }
finally { bar() }
</code>```

foo may or may not throw, and bar() may or may not throw.
If both functions throw, then the exception thrown by bar() will overwrite the exception thrown by foo. However, I need to instead see the exception that was thrown by foo. The only code I can control is that inside bar().
In C++, this can be achieved by checking std::uncaught_exceptions inside bar().
What about C#?

There is a check using Marshal.GetExceptionPointers(), but as the answer states, this is a horrible hack, and in my case it does not suffice because my code needs to run on Mono, which does not implement that function.

Context:

In my real-life case, foo is a large block of code which is provided by the library user and may throw all sorts of exceptions, and bar() is a Dispose function which is provided by me and called automatically.

答:
This will

throw the exception from foo, even if an exception is thrown in bar.

throw the exception from bar if there was no exception from foo.

not throw anything if nothing throws an exception.

preserve the original stacktrace from either exception.

```<code>    ExceptionDispatchInfo exceptionInfo = null;
    try
    {
        foo();
    }
    catch(Exception ex)
    {
        exceptionInfo = ExceptionDispatchInfo.Capture(ex);
    }
    finally
    {
        try
        {
            bar();
        }
        catch(Exception ex)
        {
            exceptionInfo = exceptionInfo ?? ExceptionDispatchInfo.Capture(ex);
        }
    }
    exceptionInfo?.Throw();
</code>```

Body:
Take the following minimal example:

try { foo }
finally { bar() }

foo may or may not throw, and bar() may or may not throw.
If both functions throw, then the exception thrown by bar() will overwrite the exception thrown by foo. However, I need to instead see the exception that was thrown by foo. The only code I can control is that inside bar().
In C++, this can be achieved by checking std::uncaught_exceptions inside bar().
What about C#?

There is a check using Marshal.GetExceptionPointers(), but as the answer states, this is a horrible hack, and in my case it does not suffice because my code needs to run on Mono, which does not implement that function.

Context:

In my real-life case, foo is a large block of code which is provided by the library user and may throw all sorts of exceptions, and bar() is a Dispose function which is provided by me and called automatically.

Body:
This will

throw the exception from foo, even if an exception is thrown in bar.

throw the exception from bar if there was no exception from foo.

not throw anything if nothing throws an exception.

preserve the original stacktrace from either exception.

    ExceptionDispatchInfo exceptionInfo = null;
    try
    {
        foo();
    }
    catch(Exception ex)
    {
        exceptionInfo = ExceptionDispatchInfo.Capture(ex);
    }
    finally
    {
        try
        {
            bar();
        }
        catch(Exception ex)
        {
            exceptionInfo = exceptionInfo ?? ExceptionDispatchInfo.Capture(ex);
        }
    }
    exceptionInfo?.Throw();


问:
How can I delete Docker's images?
I've the following images:

```<code>alex@alexvps:~$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>              <none>              70c0e19168cf        5 days ago          1.069 GB
<none>              <none>              c2ce80b62174        8 days ago          399.2 MB
<none>              <none>              60afe4036d97        8 days ago          325.1 MB
</code>```

and when I try to remove one of them I get:

```<code>alex@alexvps:~$ sudo docker rmi 60afe4036d97
Error: Conflict, 60afe4036d97 wasn't deleted
2014/01/28 00:54:00 Error: failed to remove one or more images
</code>```

How can I remove them? Why is there such conflict?

答:
To delete some Docker image you must execute the following command:

```<code>$ docker rmi <docker_image_id>
</code>```

So, to delete all Docker images you can execute the following command:

```<code>$ docker rmi $(docker images -q)
</code>```

Now, if you want delete all Docker images (including images that are in use), you can add the flag -f, for example:

```<code>$ docker rmi -f $(docker images -q)
</code>```

Title: How can I delete Docker's images?

Body:
I've the following images:

alex@alexvps:~$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>              <none>              70c0e19168cf        5 days ago          1.069 GB
<none>              <none>              c2ce80b62174        8 days ago          399.2 MB
<none>              <none>              60afe4036d97        8 days ago          325.1 MB

and when I try to remove one of them I get:

alex@alexvps:~$ sudo docker rmi 60afe4036d97
Error: Conflict, 60afe4036d97 wasn't deleted
2014/01/28 00:54:00 Error: failed to remove one or more images

How can I remove them? Why is there such conflict?

Body:
To delete some Docker image you must execute the following command:

$ docker rmi <docker_image_id>

So, to delete all Docker images you can execute the following command:

$ docker rmi $(docker images -q)

Now, if you want delete all Docker images (including images that are in use), you can add the flag -f, for example:

$ docker rmi -f $(docker images -q)

ContentLicense: CC BY-SA 4.0


问:
Can ListView Typecasted into TextView?
Can  ListView be type casted into TextView in android studio?

答: First you must add constructor to your WordAdapter, because you have compilation error on that class</p>

Title: Can ListView Typecasted into TextView?


问:
join list of lists in python
Is the a short syntax for joining a list of lists into a single list( or iterator) in python?

For example I have a list as follows and I want to iterate over a,b and c.

```<code>x = [["a","b"], ["c"]]
</code>```

The best I can come up with is as follows.

```<code>result = []
[ result.extend(el) for el in x]

for el in result:
  print el
</code>```

答:
Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

```<code>def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]
</code>```

Seems to work. Test:

```<code>flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))
</code>```

returns:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
</code>```

OwnerDisplayName: Kozyarchuk

Title: join list of lists in python

Body:
Is the a short syntax for joining a list of lists into a single list( or iterator) in python?

For example I have a list as follows and I want to iterate over a,b and c.

x = [["a","b"], ["c"]]

The best I can come up with is as follows.

result = []
[ result.extend(el) for el in x]

for el in result:
  print el

Body:
Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))

returns:

[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]


问:
QMainWindow visibility issue when switching virtual desktop
My application has a QSystemTrayIcon that toggles the QMainWindow visibility when left-clicked.

```<code>   def tray_icon_activated_cb(reason):
        if reason == QtWidgets.QSystemTrayIcon.Trigger:
            self.main_window.setVisible(not self.main_window.isVisible())
    self.activated.connect(tray_icon_activated_cb)
</code>```

It works correctly, except if I switch virtual desktop while the QMainWindow is visible.

For instance:

```<code>On virtual desktop 1, window hidden
Click
On virtual desktop 1, window visible
Click
On virtual desktop 1, window hidden
Change desktop
On virtual desktop 2, window hidden
Click
On virtual desktop 2, window visible
Click
On virtual desktop 2, window hidden
Change desktop
On virtual desktop 1, window hidden
Click
On virtual desktop 1, window visible
Change desktop
On virtual desktop 2, window hidden
Click
On virtual desktop 2, window hidden  <- wrong
Change desktop
On virtual desktop 1, window hidden
Click
On virtual desktop 1, window hidden  <-- still wrong
</code>```

I only get the QMainWindow back by restarting the application.

I added prints in method above and could check that we go through

```<code>self.main_window.setVisible(not self.main_window.isVisible())
</code>```

because self.main_window.isVisible() returns True and False alternatively.

I just don't know where that QMainWindow is visible.

Debian Stretch, Mate 1.16.2, Python 3.5.3. I can reproduce with both PyQt4 and PyQt5.

答:
It appears the window is minimized when hidden then shown from another desktop, but I could not see that because it does not appear in the taskbar, as it has following flags:

```<code>self.setWindowFlags(QtCore.Qt.Tool |
                    QtCore.Qt.FramelessWindowHint |
                    QtCore.Qt.WindowStaysOnTopHint)
</code>```

I fixed the issue by unminimizing it explicitly on show event:

```<code>def showEvent(self, event):
    super().showEvent(event)
    # Ensure the window is not minimized on virtual desktop change
    self.showNormal()
</code>```

Body:
My application has a QSystemTrayIcon that toggles the QMainWindow visibility when left-clicked.

   def tray_icon_activated_cb(reason):
        if reason == QtWidgets.QSystemTrayIcon.Trigger:
            self.main_window.setVisible(not self.main_window.isVisible())
    self.activated.connect(tray_icon_activated_cb)

It works correctly, except if I switch virtual desktop while the QMainWindow is visible.

For instance:

On virtual desktop 1, window hidden
Click
On virtual desktop 1, window visible
Click
On virtual desktop 1, window hidden
Change desktop
On virtual desktop 2, window hidden
Click
On virtual desktop 2, window visible
Click
On virtual desktop 2, window hidden
Change desktop
On virtual desktop 1, window hidden
Click
On virtual desktop 1, window visible
Change desktop
On virtual desktop 2, window hidden
Click
On virtual desktop 2, window hidden  <- wrong
Change desktop
On virtual desktop 1, window hidden
Click
On virtual desktop 1, window hidden  <-- still wrong

I only get the QMainWindow back by restarting the application.

I added prints in method above and could check that we go through

self.main_window.setVisible(not self.main_window.isVisible())

because self.main_window.isVisible() returns True and False alternatively.

I just don't know where that QMainWindow is visible.

Debian Stretch, Mate 1.16.2, Python 3.5.3. I can reproduce with both PyQt4 and PyQt5.

Body:
It appears the window is minimized when hidden then shown from another desktop, but I could not see that because it does not appear in the taskbar, as it has following flags:

self.setWindowFlags(QtCore.Qt.Tool |
                    QtCore.Qt.FramelessWindowHint |
                    QtCore.Qt.WindowStaysOnTopHint)

I fixed the issue by unminimizing it explicitly on show event:

def showEvent(self, event):
    super().showEvent(event)
    # Ensure the window is not minimized on virtual desktop change
    self.showNormal()


问:
Multiple aggregate functions in Java 8 Stream API
I have a class defined like

```<code>public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}
</code>```

I would like to perform the following SQL statement using Java 8 Stream API.

```<code>SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate
</code>```

I tried :

```<code>Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....
</code>```

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

答:
Here's a way with a custom collector. It only needs one pass, but it's not very easy, especially because of generics...

If you have this method:

```<code>@SuppressWarnings("unchecked")
@SafeVarargs
static <T, A, C extends Collector<T, A, Double>> Collector<T, ?, List<Double>>
averagingManyDoubles(ToDoubleFunction<? super T>... extractors) {

    List<C> collectors = Arrays.stream(extractors)
        .map(extractor -> (C) Collectors.averagingDouble(extractor))
        .collect(Collectors.toList());

    class Acc {
        List<A> averages = collectors.stream()
            .map(c -> c.supplier().get())
            .collect(Collectors.toList());

        void add(T elem) {
            IntStream.range(0, extractors.length).forEach(i ->
                collectors.get(i).accumulator().accept(averages.get(i), elem));
        }

        Acc merge(Acc another) {
            IntStream.range(0, extractors.length).forEach(i ->
                averages.set(i, collectors.get(i).combiner()
                    .apply(averages.get(i), another.averages.get(i))));
            return this;
        }

        List<Double> finish() {
            return IntStream.range(0, extractors.length)
                .mapToObj(i -> collectors.get(i).finisher().apply(averages.get(i)))
                .collect(Collectors.toList());
        }
    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finish);
}
</code>```

This receives an array of functions that will extract double values from each element of the stream. These extractors are converted to Collectors.averagingDouble collectors and then the local Acc class is created with the mutable structures that are used to accumulate the averages for each collector. Then, the accumulator function forwards to each accumulator, and so with the combiner and finisher functions.

Usage is as follows:

```<code>Map<String, List<Double>> averages = list.stream()
    .collect(Collectors.groupingBy(
        TimePeriodCalc::getAtDate,
        averagingManyDoubles(
            TimePeriodCalc::getOccupancy,
            TimePeriodCalc::getEfficiency)));
</code>```

Body:
I have a class defined like

public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}

I would like to perform the following SQL statement using Java 8 Stream API.

SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate

I tried :

Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

Body:
Here's a way with a custom collector. It only needs one pass, but it's not very easy, especially because of generics...

If you have this method:

@SuppressWarnings("unchecked")
@SafeVarargs
static <T, A, C extends Collector<T, A, Double>> Collector<T, ?, List<Double>>
averagingManyDoubles(ToDoubleFunction<? super T>... extractors) {

    List<C> collectors = Arrays.stream(extractors)
        .map(extractor -> (C) Collectors.averagingDouble(extractor))
        .collect(Collectors.toList());

    class Acc {
        List<A> averages = collectors.stream()
            .map(c -> c.supplier().get())
            .collect(Collectors.toList());

        void add(T elem) {
            IntStream.range(0, extractors.length).forEach(i ->
                collectors.get(i).accumulator().accept(averages.get(i), elem));
        }

        Acc merge(Acc another) {
            IntStream.range(0, extractors.length).forEach(i ->
                averages.set(i, collectors.get(i).combiner()
                    .apply(averages.get(i), another.averages.get(i))));
            return this;
        }

        List<Double> finish() {
            return IntStream.range(0, extractors.length)
                .mapToObj(i -> collectors.get(i).finisher().apply(averages.get(i)))
                .collect(Collectors.toList());
        }
    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finish);
}

This receives an array of functions that will extract double values from each element of the stream. These extractors are converted to Collectors.averagingDouble collectors and then the local Acc class is created with the mutable structures that are used to accumulate the averages for each collector. Then, the accumulator function forwards to each accumulator, and so with the combiner and finisher functions.

Usage is as follows:

Map<String, List<Double>> averages = list.stream()
    .collect(Collectors.groupingBy(
        TimePeriodCalc::getAtDate,
        averagingManyDoubles(
            TimePeriodCalc::getOccupancy,
            TimePeriodCalc::getEfficiency)));


问:
How to rename a Django app and migrate data from an app to the other
I have a Django app named app1 with models and migrations files.
I renamed this app to app2 and I fixed all imports, urls etc...
I now have a problem with migrations files and data in tables.

How can I write migrations with the correct way to ensure:

New installation => create the new tables

Update old versions => create new tables, move data, remove old tables

Note 1: there is several tables with many Foreign Keys.

Here is my progress so far and I am not sure if I am on the good way:

I removed all older migrations

I ran python manage.py makemigrations to generate new migrations files

After these 2 steps, I can install my application but I still have problems with old version.

Question: What is the best way to migrate data?

Note 2: I don't use South.

答:
Renaming an app is always a tricky issue.

If you do the migration like a simple table renaming migration, at any moment the apps.get_model() for the old app cannot work because the app simply doesn't exist.

I found this answer. I know you are not using south, but I think it might work the same way, just skip the south steps.

Basically, you have to:

Dump the data, before rename, into a json file

Run the script in the answer to rename references in the json file from the app1 to app2

Rename app1 to app2 (all import references, settings.py, etc)

Run the migrations to create the tables for app2

Load the data from json file to the database

Drop the app1 tables

I hope this help.


问:
Wordpress Customizer sanitize_callback: How to Reset to Default on Fail
I check the sanity of some settings with sanitize_callback. It works, but on fail, I want to reset the value do the default one. How can I do that?

```<code>$wp_customize->add_setting(
    $attribute[0],
    array(
        "default" => $attribute[1],
        "sanitize_callback" => $validate_func,
    )
);
</code>```

答:
Unfortunately sanitize_callback is not meant for validation, it simply cleans the input for return. If you post your $validate_func we might be able to help a little more.

EDIT Perhaps if you set your function to return false on fail it might help?

As always, the Codex is not a bad place to look. (https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_setting)

Body:
I check the sanity of some settings with sanitize_callback. It works, but on fail, I want to reset the value do the default one. How can I do that?

$wp_customize->add_setting(
    $attribute[0],
    array(
        "default" => $attribute[1],
        "sanitize_callback" => $validate_func,
    )
);


问:
How to retrieve data from Symantec using their API?
Currently I am getting an error 400 status code

I am lost at what I need to do. Status code 400 is related to syntax. How do I format my output into JSON file format?

```<code>import requests, json, urllib3
urllib3.disable_warnings()

url = 'https://symantecwebsite:8446/sepm/api/v1/identity/authenticate'
cert_location = 'newsymanteccert.cer'

headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}

r = requests.post(url, verify=cert_location, auth=('myusername','password*-uTem'),
                  headers=headers)

print r.status_code
</code>```

If I change the last line to print json.dumps, I get
    "function dumps at 0x03D349B0"

trying to get output from page 6 https://symwisedownload.symantec.com/resources/sites/SYMWISE/content/live/DOCUMENTATION/9000/DOC9447/en_US/REST_API_Ref_SEP14.pdf?gda=1499425764_2f09acf4cf9167a583f6e98bf13e44e0

答:
I might not be able to give you a full answer but I read through the PDF you linked. First step is to get a valid token from the chapter under Authenticate to Symantec Endpoint Protection Manager

e.g. "token": "c34692c5-201d-4d94-b0f8-61ed03383337"

My guess is you need to pass a dictionary:

```<code>urldata = {
"username" : "admin",
"password" : "password",
"domain" : ""
}

headers = {"Content-Type": "application/json"} # not 100% sure here but looks like you need to send headers too

response = requests.post(url, data = urldata, headers = heaaders) # gets data
rdata = json.loads(response.text) # loads data into a dictionary
mytoken = rdata["token"] # saves token to mytoken variable
</code>```

Body:
Currently I am getting an error 400 status code

I am lost at what I need to do. Status code 400 is related to syntax. How do I format my output into JSON file format?

import requests, json, urllib3
urllib3.disable_warnings()

url = 'https://symantecwebsite:8446/sepm/api/v1/identity/authenticate'
cert_location = 'newsymanteccert.cer'

headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'}

r = requests.post(url, verify=cert_location, auth=('myusername','password*-uTem'),
                  headers=headers)

print r.status_code

If I change the last line to print json.dumps, I get
    "function dumps at 0x03D349B0"

trying to get output from page 6 https://symwisedownload.symantec.com/resources/sites/SYMWISE/content/live/DOCUMENTATION/9000/DOC9447/en_US/REST_API_Ref_SEP14.pdf?gda=1499425764_2f09acf4cf9167a583f6e98bf13e44e0

Body:
I might not be able to give you a full answer but I read through the PDF you linked. First step is to get a valid token from the chapter under Authenticate to Symantec Endpoint Protection Manager

e.g. "token": "c34692c5-201d-4d94-b0f8-61ed03383337"

My guess is you need to pass a dictionary:

urldata = {
"username" : "admin",
"password" : "password",
"domain" : ""
}

headers = {"Content-Type": "application/json"} # not 100% sure here but looks like you need to send headers too

response = requests.post(url, data = urldata, headers = heaaders) # gets data
rdata = json.loads(response.text) # loads data into a dictionary
mytoken = rdata["token"] # saves token to mytoken variable


问:
can a Ruby cloud instance handle the same amount of traffic a node instance would do?
We're going to work on revamping a cms based website for a tv channel that we expect to serve at least 10+ million unique user/month, about 400+ million requests/month and an average of 40 terabytes of bandwidth/month that's their CloudFlare stats from their old website and they expecting even more.

the team stack is mainly ruby/rails with react for the frontend, so we're planning to build the backend as rest API that serves a frontend react and another react app for the cms admin panel, we're arguing between Ruby and node and some says that node is faster and will be cheaper in terms of resources consumption, will Ruby be efficient vs node?, can a Ruby cloud instance handle the same amount of traffic a node instance would do? any advice on is it worth the shift to node?

答:
The reason node can handle such high throughput is due to it's highly parallelised nature and the fact that the JS JIT is incredibly optimized and can do certain things for performance boosts that ruby can't plus, want more performance? Just allow it to run with more threads.
You can do the same using a webserver like Puma and configure it to run with more threads but ultimately it's still ruby based.

What you could do is to use more smaller frameworks such as using sinatra for the front end and grape for the backend, smaller means lighter thus less load.
Also maybe apache for static asset distribution or offload entirely to a static asset server. On top of that If you're able to you can code performance critical components in a lower level language such as C, C++, Rust, etc.

Lastly you can try for specific ruby optimizations, I don't know off the top of my head but I'm sure they exist though how much you'll get from them I can't say.

Ruby Itself won't really be reasonably fast by itself until at least ruby 3.0 and I'm not sure when that is coming out.


问:
When would this Koajs error happen
I'm trying to get my head around Koa and I am making small progress. At the moment I think I understand this code

```<code>import Koa from 'koa';
import router from './router';

const app = new Koa();

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.body = { message: err.message };
    ctx.status = err.status || 500;
  }
});
app.use(router.routes());
app.listen(3000);

export default app;
</code>```

Instead of having a callback to handle the error, we go upstream to that catch. But I would like to make the above error execute.

How can I simulate an error

答:
To simulate an error do :</p>

```<code>throw new Error('error message')
</code>```

Title: When would this Koajs error happen

Body:
I'm trying to get my head around Koa and I am making small progress. At the moment I think I understand this code

import Koa from 'koa';
import router from './router';

const app = new Koa();

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.body = { message: err.message };
    ctx.status = err.status || 500;
  }
});
app.use(router.routes());
app.listen(3000);

export default app;

Instead of having a callback to handle the error, we go upstream to that catch. But I would like to make the above error execute.

How can I simulate an error

Body:
To simulate an error do :

throw new Error('error message')


问:
Redirect via JavaScript if Variable Equals False?
Ive tried just about everything I know how to do (not much tbh), so here is the code WITHOUT the attempted redirect:

```<code>  if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition);
  } else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
  }
  blacklisted_areas = {
    'area 51': [1, 2],
    'pink unicorn zoo': [1, 2],
  };
  // Success callback function
  function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';
  }
  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (displayPosition()[0] === x[0] && displayPosition()[1] === x[1]) {
        blacklisted = true;
    }
  }
  //Now right below here is where I need to check for blacklisted's value (if false redirect to a different site)
</code>```

Please help me :((

答:
```<code>if (!blacklisted){
  window.location = "URL goes here";
}
</code>```

This checks the opposite of blacklisted. If blacklisted is false, then the condition is true and the redirect happens.

Edit: navigator.geolocation is async, so you'll want to handle all your logic in the callback

```<code>function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }
}
</code>```

Let me know if that works

Body:
Ive tried just about everything I know how to do (not much tbh), so here is the code WITHOUT the attempted redirect:

  if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition);
  } else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
  }
  blacklisted_areas = {
    'area 51': [1, 2],
    'pink unicorn zoo': [1, 2],
  };
  // Success callback function
  function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '
Your longitude is :' + mylong + ' and your latitide is ' + mylat + '
';
  }
  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (displayPosition()[0] === x[0] && displayPosition()[1] === x[1]) {
        blacklisted = true;
    }
  }
  //Now right below here is where I need to check for blacklisted's value (if false redirect to a different site)

Please help me :((

Body:
if (!blacklisted){
  window.location = "URL goes here";
}

This checks the opposite of blacklisted. If blacklisted is false, then the condition is true and the redirect happens.

Edit: navigator.geolocation is async, so you'll want to handle all your logic in the callback

function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }
}

Let me know if that works


问:
View button with if else statement
I have a gridview and I want to add a button 'VIEW' which redirects to the (Customers.aspx?CustomerID=) page. Every customer has a ID and each ID is associated with a report.  I don't want the ID to show up in my gridview and I want it to be hidden.
Also, I want this button to show up only if the USER is an "Admin" or a "Salesperson" category. I s there a way i can bind my CustomerID to a UserCategory to generate reports for each ID separately.

I tried looking at some other posts as well but my button doesn't redirect for some reason.
Can someone please help me figure out what i am doing wrong here or if i am missing something. Any help will be greatly appreciated.
Thank you.

```<code>    <asp:TemplateField ShowHeader="False">
             <ItemTemplate>
                 <asp:Button ID="btnView" runat="server" CausesValidation="false" CommandName="Select" Text="VIEW"  />
              </ItemTemplate>
              <ControlStyle CssClass="button" />
           </asp:TemplateField>

 protected void btnView(object sender, EventArgs e)
{
    Button button = (Button)sender;
    GridViewRow row = (GridViewRow)button.NamingContainer;
    Label lblCustomerID = (Label)row.FindControl("lblCustomerID");

    txtHFUserCategory.Value = Session["UserCategoryPC"].ToString();
    String strUserCat = MTProcs.GetSingleDatabaseResult("SELECT tblUsers.UserCategoryID FROM tblUsers WHERE UserID = " + txtHFUserID.Value);
    if (strUserCat == "4" || strUserCat == "12")
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open(Customers.aspx?CustomerID=" + lblLeadID.Text + "');", true);

    }
}
</code>```

答:
Hi you can do it with simply adding visible property in your button
like</p>

```<code><asp:button ID="yourBtnID" runat="server" Text="WotEver" visible='<%# Convert.toInt(Eval("admin"))==1 && Convert.toInt(Eval("SALESPERSON"))==1 %>'/>
</code>```

Title: View button with if else statement

Body:
I have a gridview and I want to add a button 'VIEW' which redirects to the (Customers.aspx?CustomerID=) page. Every customer has a ID and each ID is associated with a report.  I don't want the ID to show up in my gridview and I want it to be hidden.
Also, I want this button to show up only if the USER is an "Admin" or a "Salesperson" category. I s there a way i can bind my CustomerID to a UserCategory to generate reports for each ID separately.

I tried looking at some other posts as well but my button doesn't redirect for some reason.
Can someone please help me figure out what i am doing wrong here or if i am missing something. Any help will be greatly appreciated.
Thank you.

    <asp:TemplateField ShowHeader="False">
             <ItemTemplate>
                 <asp:Button ID="btnView" runat="server" CausesValidation="false" CommandName="Select" Text="VIEW"  />
              </ItemTemplate>
              <ControlStyle CssClass="button" />
           </asp:TemplateField>

 protected void btnView(object sender, EventArgs e)
{
    Button button = (Button)sender;
    GridViewRow row = (GridViewRow)button.NamingContainer;
    Label lblCustomerID = (Label)row.FindControl("lblCustomerID");

    txtHFUserCategory.Value = Session["UserCategoryPC"].ToString();
    String strUserCat = MTProcs.GetSingleDatabaseResult("SELECT tblUsers.UserCategoryID FROM tblUsers WHERE UserID = " + txtHFUserID.Value);
    if (strUserCat == "4" || strUserCat == "12")
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open(Customers.aspx?CustomerID=" + lblLeadID.Text + "');", true);

    }
}

Body:
Hi you can do it with simply adding visible property in your button
like

<asp:button ID="yourBtnID" runat="server" Text="WotEver" visible='<%# Convert.toInt(Eval("admin"))==1 && Convert.toInt(Eval("SALESPERSON"))==1 %>'/>


问:
AWS API Gateway endpoint gives CORS error when POST from static site on S3
I have created an API endpoint with Serverless(serverless.com) which I expose through API Gateway. I'm getting following error though I have enabled CORS from the

XMLHttpRequest cannot load
  https://xxxxxxxxx.execute-api.us-west-2.amazonaws.com/development/signup.
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin
  'http://yyyyyyyyy.com.s3-website-us-east-1.amazonaws.com' is therefore
  not allowed access.

I don't get any errors when I use Postman to make requests, despite I have set origin header or not. How can I fix this problem?

答:
I have the this problem...I enable CORS, the Test work as it is sending the headers, but when I call it from my app it fails and no headers found on the response.

it is because after set  CORS you have to DEPLOY the API. I Deplyed the API and everything works great.


问:
Multiple AJAX calls in single PHP file
I am trying to validate username and email via AJAX frim single JavaScript file and sending data to single PHP file... my code is

HTML code ->

```<code><input type="text" name="user_name" id="user_name" onBlur="userChk()" class="form-control" placeholder="Username" />
    <input type="email" name="email" id="email" onBlur="emailchk()" class="form-control" placeholder="Email">
</code>```

JavaScript code ->

```<code>function userChk(){
  var user_name = $('#user_name').val();
      $.ajax({

        type : 'POST',
        url  : 'login/signup-fn.php',
        data : { name: user_name},
        success : function(data)
              {
                   $("#result").html(data);
                }
        });
        return false;
  }

  function emailchk(){
  var email = $('#email').val();
      $.ajax({

        type : 'POST',
        url  : 'login/signup-fn.php',
        data : {email:email},
        success : function(data)
              {
                   $("#result").html(data);
                }
        });
        return false;
  }
</code>```

PHP code ->

```<code>include('../components/connectdb.php');
if($_POST['name']) {
    $user_name     = strip_tags($_POST['name']);
        $uselect_sql= "SELECT user_name FROM users WHERE user_name='{$user_name}'";

       $uselect_query = mysqli_query($conn, $uselect_sql);

      $urow = mysqli_num_rows($uselect_query);

      if($urow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>User Name Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }

    else if($_POST['email']){
      $email = ($_POST['email']);
       $eselect_sql= "SELECT email FROM users WHERE email='{$email}'";

       $eselect_query = mysqli_query($conn, $eselect_sql);

      $erow = mysqli_num_rows($eselect_query);
      if($erow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Warning!</strong>Email Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }
</code>```

I don't know where's the mistalke... I am new in web devlopment.

答:
You need to add isset() else it ll throw undefined index error. Because suppose when the ajax call for name check will call email variable would not set so it ll throw error undefined index email.

if($_POST['name']) will not check for undefined variable.

```<code>include('../components/connectdb.php');
if(isset($_POST['name'])) {
    $user_name     = strip_tags($_POST['name']);
        $uselect_sql= "SELECT user_name FROM users WHERE user_name='{$user_name}'";

       $uselect_query = mysqli_query($conn, $uselect_sql);

      $urow = mysqli_num_rows($uselect_query);

      if($urow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>User Name Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }

    else if(isset($_POST['email'])){
      $email = ($_POST['email']);
       $eselect_sql= "SELECT email FROM users WHERE email='{$email}'";

       $eselect_query = mysqli_query($conn, $eselect_sql);

      $erow = mysqli_num_rows($eselect_query);
      if($erow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Warning!</strong>Email Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }
</code>```

Title: Multiple AJAX calls in single PHP file

Body:
I am trying to validate username and email via AJAX frim single JavaScript file and sending data to single PHP file... my code is

HTML code ->

<input type="text" name="user_name" id="user_name" onBlur="userChk()" class="form-control" placeholder="Username" />
    <input type="email" name="email" id="email" onBlur="emailchk()" class="form-control" placeholder="Email">

JavaScript code ->

function userChk(){
  var user_name = $('#user_name').val();
      $.ajax({

        type : 'POST',
        url  : 'login/signup-fn.php',
        data : { name: user_name},
        success : function(data)
              {
                   $("#result").html(data);
                }
        });
        return false;
  }

  function emailchk(){
  var email = $('#email').val();
      $.ajax({

        type : 'POST',
        url  : 'login/signup-fn.php',
        data : {email:email},
        success : function(data)
              {
                   $("#result").html(data);
                }
        });
        return false;
  }

PHP code ->

include('../components/connectdb.php');
if($_POST['name']) {
    $user_name     = strip_tags($_POST['name']);
        $uselect_sql= "SELECT user_name FROM users WHERE user_name='{$user_name}'";

       $uselect_query = mysqli_query($conn, $uselect_sql);

      $urow = mysqli_num_rows($uselect_query);

      if($urow > 0){
      echo "
×User Name Already Exist
";
    }
    else
    {
      echo "";
    }
    }

    else if($_POST['email']){
      $email = ($_POST['email']);
       $eselect_sql= "SELECT email FROM users WHERE email='{$email}'";

       $eselect_query = mysqli_query($conn, $eselect_sql);

      $erow = mysqli_num_rows($eselect_query);
      if($erow > 0){
      echo "
×Warning!Email Already Exist
";
    }
    else
    {
      echo "";
    }
    }

I don't know where's the mistalke... I am new in web devlopment.

Body:
You need to add isset() else it ll throw undefined index error. Because suppose when the ajax call for name check will call email variable would not set so it ll throw error undefined index email.

if($_POST['name']) will not check for undefined variable.

include('../components/connectdb.php');
if(isset($_POST['name'])) {
    $user_name     = strip_tags($_POST['name']);
        $uselect_sql= "SELECT user_name FROM users WHERE user_name='{$user_name}'";

       $uselect_query = mysqli_query($conn, $uselect_sql);

      $urow = mysqli_num_rows($uselect_query);

      if($urow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>User Name Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }

    else if(isset($_POST['email'])){
      $email = ($_POST['email']);
       $eselect_sql= "SELECT email FROM users WHERE email='{$email}'";

       $eselect_query = mysqli_query($conn, $eselect_sql);

      $erow = mysqli_num_rows($eselect_query);
      if($erow > 0){
      echo "<div class='alert alert-danger alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Warning!</strong>Email Already Exist</div>";
    }
    else
    {
      echo "";
    }
    }


问:
My class doesn't seem to map correctly with an API's JSON response, not binding
I am having issues with deserializing a JSON response.

```<code>userResponse = JsonConvert.DeserializeObject<UserResponse>(result);
</code>```

The json response looks like:

```<code>{
    "Results" : [
        {
            "Id" :  1,
            "Name" : "John",
            "Age"  : 50
        }
    ],
    "Paging" : {
        "TotalPages" : 5,
        "CurrentPage" : 1
    }
}
</code>```

My UserResponse class that is suppose to bind to the JSON above looks like:

```<code>[DataContract]
public class UserResponse
{
    [DateMember(Name = "Results" )]
    public List<User> Results {get;set;}

    [DateMember(Name = "Paging" )]
    public Paging Paging {get;set;}

}

[DataContract]
public class User
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Age {get;set;}
}

[DataContract]
public class Paging
{
    public int TotalPages {get;set;}
    public int CurrentPage {get;set;}
}
</code>```

Does the current UserResponse look have any issues with it?
I'm not sure why it isn't binding correctly.

The userResponse object is coming back not null, but the values of the properties are null.

答:
You can use the following structure:</p>

```<code>public class Result
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Paging
{
    public int TotalPages { get; set; }
    public int CurrentPage { get; set; }
}

public class RootObject
{
    public List<Result> Results { get; set; }
    public Paging Paging { get; set; }
}
</code>```

Body:
I am having issues with deserializing a JSON response.

userResponse = JsonConvert.DeserializeObject<UserResponse>(result);

The json response looks like:

{
    "Results" : [
        {
            "Id" :  1,
            "Name" : "John",
            "Age"  : 50
        }
    ],
    "Paging" : {
        "TotalPages" : 5,
        "CurrentPage" : 1
    }
}

My UserResponse class that is suppose to bind to the JSON above looks like:

[DataContract]
public class UserResponse
{
    [DateMember(Name = "Results" )]
    public List<User> Results {get;set;}

    [DateMember(Name = "Paging" )]
    public Paging Paging {get;set;}

}

[DataContract]
public class User
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int Age {get;set;}
}

[DataContract]
public class Paging
{
    public int TotalPages {get;set;}
    public int CurrentPage {get;set;}
}

Does the current UserResponse look have any issues with it?
I'm not sure why it isn't binding correctly.

The userResponse object is coming back not null, but the values of the properties are null.

Body:
You can use the following structure:

public class Result
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Paging
{
    public int TotalPages { get; set; }
    public int CurrentPage { get; set; }
}

public class RootObject
{
    public List<Result> Results { get; set; }
    public Paging Paging { get; set; }
}


问:
Angular 2 Universal + Akamai
I want to see if I can create a stack based on both, CDN and also angular 2 universal. So when the user navigate has the CDN to get the assets, and if the user access the first time will have the complete html rendered by Universal.

I was thinking in:

Client  <===>  Akamai  <===>  Varnish  <===> Origin Server (node.js with universal)

This sounds good? have you ever tried it?
Also i'm considering adding nginx and ELB for the complete stack.

The question is:
- Can this stack work as expected?

答:
Yes it can be done! The big issue is how do you invalidate an arbitrary number of http requests made in Angular that determine the rendered page. Using some sort of header schema to invalidate might be helpful.

Assuming your are using official ng-express engine, a service like this could let you define the response from the Angular runtime:

import { RESPONSE } from '@nguniversal/express-engine/tokens'
import { Inject, Injectable, Optional } from '@angular/core'
import { Response } from 'express'

export interface IServerResponseService {
  getHeader(key: string): string
  setHeader(key: string, value: string): this
  setHeaders(dictionary: { [key: string]: string }): this
  appendHeader(key: string, value: string, delimiter?: string): this
  setStatus(code: number, message?: string): this
  setNotFound(message?: string): this
  setError(message?: string): this
}

@Injectable()
export class ServerResponseService implements IServerResponseService {

  private response: Response

  constructor(@Optional() @Inject(RESPONSE) res: any) {
    this.response = res
  }

  getHeader(key: string): string {
    return this.response.getHeader(key)
  }

  setHeader(key: string, value: string): this {
    if (this.response)
      this.response.header(key, value)
    return this
  }

  appendHeader(key: string, value: string, delimiter = ','): this {
    if (this.response) {
      const current = this.getHeader(key)
      if (!current) return this.setHeader(key, value)

      const newValue = [...current.split(delimiter), value]
        .filter((el, i, a) => i === a.indexOf(el))
        .join(delimiter)

      this.response.header(key, newValue)
    }
    return this
  }

  setHeaders(dictionary: { [key: string]: string }): this {
    if (this.response)
      Object.keys(dictionary).forEach(key => this.setHeader(key, dictionary[key]))
    return this
  }

  setStatus(code: number, message?: string): this {
    if (this.response) {
      this.response.statusCode = code
      if (message)
        this.response.statusMessage = message
    }
    return this
  }

  setNotFound(message = 'not found'): this {
    if (this.response) {
      this.response.statusCode = 404
      this.response.statusMessage = message
    }
    return this
  }

  setError(message = 'internal server error'): this {
    if (this.response) {
      this.response.statusCode = 500
      this.response.statusMessage = message
    }
    return this
  }
}
```

Title: Angular 2 Universal + Akamai


问:
Why is the size of this struct 32?
This is the struct.

```<code>//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};
</code>```

This is my code to display the size of this struct :

```<code>    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);
</code>```

The MessageBox displays 32.
Thank you!

答:
The biggest(memory wise) member of the struct is the double which takes 8 bytes. The struct will by default align memory on the largest member. Since the char is 9 bytes long, it needs 2x8 bytes to store it and the int even if taking only 4 bytes(on 32bit machine) will use 8 bytes.

4 -> 8 + 8 -> 8 + 9 -> 16 = 32 bytes.

Title: Why is the size of this struct 32?

Body:
This is the struct.

//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};

This is my code to display the size of this struct :

    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);

The MessageBox displays 32.
Thank you!


问:
Form new array from associative arrays
I have 3 arrays and looks like this

```<code>Array1
(
[0] => Array
    (
        [Month] => 'Jan 2015'
        [Total] => 10
    )

[1] => Array
    (
        [Month] => 'Feb 2015'
        [Total] => 8
    )

[2] => Array
    (
        [Month] => 'Mar 2015'
        [Total] => 10
    )
)

Array2
(
[0] => Array
    (
        [Month] => 'Jan 2016'
        [Total] => 7
    )

[1] => Array
    (
        [Month] => 'Feb 2016'
        [Total] => 5
    )

[2] => Array
    (
        [Month] => 'Mar 2016'
        [Total] => 15
    )
)

Array3
(
[0] => Array
    (
        [Month] => 'Jan 2017'
        [Total] => 13
    )

[1] => Array
    (
        [Month] => 'Feb 2017'
        [Total] => 10
    )

[2] => Array
    (
        [Month] => 'Mar 2017'
        [Total] => 11
    )
)
</code>```

All 3 arrays are of the same size.

What I want to achieve is to output identical months sequentially and corresponding values in the same order. The new arrays should look like this:

Desired result:

```<code>$months = array['Jan 2015','Jan 2016','Jan 2017', 'Feb 2015', 'Feb 2016'...'Mar 2016','Mar 2017'];
$totals = array[10,7,13,5,5,...,15,11];
</code>```

答:
try this https://eval.in/829000

```<code><?php
$array1 = Array
(
    0 => Array ( 'Month' => 'Jan 2015', 'Total' => 10 ),
    1 => Array ( 'Month' => 'Feb 2015', 'Total' => 8),
    2 => Array ( 'Month' => 'Mar 2015', 'Total' => 10)
);

$array2 = Array
(
    0 => Array( 'Month' => 'Jan 2016', 'Total' => 7),
    1 => Array( 'Month' => 'Feb 2016', 'Total' => 5),
    2 => Array( 'Month' => 'Mar 2016', 'Total' => 15)
);

$array3 = Array
(
    0 => Array( 'Month' => 'Jan 2017', 'Total' => 13),
    1 => Array( 'Month' => 'Feb 2017', 'Total' => 10),
    2 => Array( 'Month' => 'Mar 2017', 'Total' => 11)
);

//ordered months names in lower case
$monthsNames = ['jan','feb','mar','abr','may','jun','jul','aug','sept','oct','nov','dec'];
$months = [];
$totals = [];
$orderedMonths = [];
$orderedTotals = [];
$orderedIndexes = [];

foreach($array1 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
foreach($array2 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
foreach($array3 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
//now the $months and $totals has all the values but not ordered, we need to order them
//get the indexes order;
foreach ($monthsNames as $monthName){
    $index = 0; //reset the index for the next month
    foreach ($months as $inputMonth){
        //if the $inputMonth == $monthName then collected it's index
        if (strpos(strtolower($inputMonth), $monthName) !== false ){
            $orderedIndexes[] = $index;
        }
        $index ++;
    }
}
//build the final ordered array
foreach ($orderedIndexes  as $index){
    $orderedMonths[] = $months[$index];
    $orderedTotals[] = $totals[$index];
}
var_dump($orderedMonths);
var_dump($orderedTotals);
exit;
?>
</code>```

this outputs

```<code>array(9) {
  [0]=>
  string(8) "Jan 2015"
  [1]=>
  string(8) "Jan 2016"
  [2]=>
  string(8) "Jan 2017"
  [3]=>
  string(8) "Feb 2015"
  [4]=>
  string(8) "Feb 2016"
  [5]=>
  string(8) "Feb 2017"
  [6]=>
  string(8) "Mar 2015"
  [7]=>
  string(8) "Mar 2016"
  [8]=>
  string(8) "Mar 2017"
}
array(9) {
  [0]=>
  int(10)
  [1]=>
  int(7)
  [2]=>
  int(13)
  [3]=>
  int(8)
  [4]=>
  int(5)
  [5]=>
  int(10)
  [6]=>
  int(10)
  [7]=>
  int(15)
  [8]=>
  int(11)
}
</code>```

note that the totals in your desired result is not the correct order you want, since Feb 2015 is 8 not 5.

also note that if you trust the months string format you can also make use of the PHP date and time functions.

Title: Form new array from associative arrays

Body:
I have 3 arrays and looks like this

Array1
(
[0] => Array
    (
        [Month] => 'Jan 2015'
        [Total] => 10
    )

[1] => Array
    (
        [Month] => 'Feb 2015'
        [Total] => 8
    )

[2] => Array
    (
        [Month] => 'Mar 2015'
        [Total] => 10
    )
)

Array2
(
[0] => Array
    (
        [Month] => 'Jan 2016'
        [Total] => 7
    )

[1] => Array
    (
        [Month] => 'Feb 2016'
        [Total] => 5
    )

[2] => Array
    (
        [Month] => 'Mar 2016'
        [Total] => 15
    )
)

Array3
(
[0] => Array
    (
        [Month] => 'Jan 2017'
        [Total] => 13
    )

[1] => Array
    (
        [Month] => 'Feb 2017'
        [Total] => 10
    )

[2] => Array
    (
        [Month] => 'Mar 2017'
        [Total] => 11
    )
)

All 3 arrays are of the same size.

What I want to achieve is to output identical months sequentially and corresponding values in the same order. The new arrays should look like this:

Desired result:

$months = array['Jan 2015','Jan 2016','Jan 2017', 'Feb 2015', 'Feb 2016'...'Mar 2016','Mar 2017'];
$totals = array[10,7,13,5,5,...,15,11];

Body:
try this https://eval.in/829000

<?php
$array1 = Array
(
    0 => Array ( 'Month' => 'Jan 2015', 'Total' => 10 ),
    1 => Array ( 'Month' => 'Feb 2015', 'Total' => 8),
    2 => Array ( 'Month' => 'Mar 2015', 'Total' => 10)
);

$array2 = Array
(
    0 => Array( 'Month' => 'Jan 2016', 'Total' => 7),
    1 => Array( 'Month' => 'Feb 2016', 'Total' => 5),
    2 => Array( 'Month' => 'Mar 2016', 'Total' => 15)
);

$array3 = Array
(
    0 => Array( 'Month' => 'Jan 2017', 'Total' => 13),
    1 => Array( 'Month' => 'Feb 2017', 'Total' => 10),
    2 => Array( 'Month' => 'Mar 2017', 'Total' => 11)
);

//ordered months names in lower case
$monthsNames = ['jan','feb','mar','abr','may','jun','jul','aug','sept','oct','nov','dec'];
$months = [];
$totals = [];
$orderedMonths = [];
$orderedTotals = [];
$orderedIndexes = [];

foreach($array1 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
foreach($array2 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
foreach($array3 as $array){
    $months[] = $array['Month'];
    $totals[] = $array['Total'];
}
//now the $months and $totals has all the values but not ordered, we need to order them
//get the indexes order;
foreach ($monthsNames as $monthName){
    $index = 0; //reset the index for the next month
    foreach ($months as $inputMonth){
        //if the $inputMonth == $monthName then collected it's index
        if (strpos(strtolower($inputMonth), $monthName) !== false ){
            $orderedIndexes[] = $index;
        }
        $index ++;
    }
}
//build the final ordered array
foreach ($orderedIndexes  as $index){
    $orderedMonths[] = $months[$index];
    $orderedTotals[] = $totals[$index];
}
var_dump($orderedMonths);
var_dump($orderedTotals);
exit;
?>

this outputs

array(9) {
  [0]=>
  string(8) "Jan 2015"
  [1]=>
  string(8) "Jan 2016"
  [2]=>
  string(8) "Jan 2017"
  [3]=>
  string(8) "Feb 2015"
  [4]=>
  string(8) "Feb 2016"
  [5]=>
  string(8) "Feb 2017"
  [6]=>
  string(8) "Mar 2015"
  [7]=>
  string(8) "Mar 2016"
  [8]=>
  string(8) "Mar 2017"
}
array(9) {
  [0]=>
  int(10)
  [1]=>
  int(7)
  [2]=>
  int(13)
  [3]=>
  int(8)
  [4]=>
  int(5)
  [5]=>
  int(10)
  [6]=>
  int(10)
  [7]=>
  int(15)
  [8]=>
  int(11)
}

note that the totals in your desired result is not the correct order you want, since Feb 2015 is 8 not 5.

also note that if you trust the months string format you can also make use of the PHP date and time functions.


问:
switch statement always goes to default in javascript
I want to do a simple program that prints out different phrases depending on whether a specific condition is met. We input 2 integer parameters in a function and it evaluates whether one number is greater, less than, or whether both numbers are equal to each other. My code looks like this:

```<code>function CheckNums(num1,num2) {
switch (num1,num2) {
  case (num2>num1):
   console.log('num2 greater than num1');
   break;
  case (num2 === num1):
   console.log('both equal');
   break;
  default:
   console.log('num1 greater than num2');
  }
}
</code>```

Either case, whether I input: CheckNums(4,5) , CheckNums(2,2) , CheckNums(5,4) the program runs default.

IMPORTANT: Im not asking for an alternative solution to this problem. I already managed to solve it using if statements or the ternary operator. What I'm asking is: WHY IS THIS SWITCH NOT WORKING?

Questions that I`ve consulted that didn't solve my problem:

JavaScript switch statement only executes the default case

The sol:This guy had a problem where the Math.random() generator only generated numbers with decimal places, which of course, wouldn't go to either case except default.

JS Switch case not working correctly always default is executed

The sol:This guy was inputing strings as a parameter, and was expecting int values in the cases.

Other notes:

-Maybe the answer lies on using parseint? (Assuming that the parameters are not being inputed as ints.)

-I removed the parenthesis that go in the cases. That didn't solve my problem.

-For the second case, I also experimented using equality operator(==) instead of the Identity operator (===). The second case still did not work.

My best guess for where the problem is hiding:
When I compiled the program in google chrome console, I get the following notification: "undefined". So, I think that's whats not allowing my cases to evaluate the parameters properly. Something is not being defined properly.

答:
If you really want to use a switch statement to do that you'll have to be clever.  Hint:  an IF is way easier.

function CheckNums(num1, num2) {
  switch (Math.sign(num1 - num2)) {
  case -1:
   console.log('num2 greater than num1');
   break;
  case 0:
   console.log('both equal');
   break;
  case 1:
   console.log('num1 greater than num2');
   break;
  default:
   console.log('Something went wrong');
   break;
  }
}

CheckNums(8, 5);
CheckNums(3, 4);
CheckNums(10, 10);
CheckNums("argh", "argh");```

Body:
I want to do a simple program that prints out different phrases depending on whether a specific condition is met. We input 2 integer parameters in a function and it evaluates whether one number is greater, less than, or whether both numbers are equal to each other. My code looks like this:

function CheckNums(num1,num2) {
switch (num1,num2) {
  case (num2>num1):
   console.log('num2 greater than num1');
   break;
  case (num2 === num1):
   console.log('both equal');
   break;
  default:
   console.log('num1 greater than num2');
  }
}

Either case, whether I input: CheckNums(4,5) , CheckNums(2,2) , CheckNums(5,4) the program runs default.

IMPORTANT: Im not asking for an alternative solution to this problem. I already managed to solve it using if statements or the ternary operator. What I'm asking is: WHY IS THIS SWITCH NOT WORKING?

Questions that I`ve consulted that didn't solve my problem:

JavaScript switch statement only executes the default case

The sol:This guy had a problem where the Math.random() generator only generated numbers with decimal places, which of course, wouldn't go to either case except default.

JS Switch case not working correctly always default is executed

The sol:This guy was inputing strings as a parameter, and was expecting int values in the cases.

Other notes:

-Maybe the answer lies on using parseint? (Assuming that the parameters are not being inputed as ints.)

-I removed the parenthesis that go in the cases. That didn't solve my problem.

-For the second case, I also experimented using equality operator(==) instead of the Identity operator (===). The second case still did not work.

My best guess for where the problem is hiding:
When I compiled the program in google chrome console, I get the following notification: "undefined". So, I think that's whats not allowing my cases to evaluate the parameters properly. Something is not being defined properly.


问:
AWS ECS weird docker behavior
I'm fairly new with Amazon's EC2 service, and I'm at a loss with the weird behavior I'm getting from it.

I have a Docker image that runs flawlessly when ran locally. I have uploaded it to a repository and made a cluster/service/task definition to run it in EC2.

When I attempt to curl to my running service, I'm told the connection refused (as I assume the port is not opened or mapped correctly).

If I ssh into Amazon EC2 and start the image manually with the -p 1200:1200 flag, it again runs without a problem and can be curled without error.

In addition to this, when I try to retrieve the logs from the image that amazon automatically deploys, they are empty.

When running this locally or manually on EC2, the logs exist and are correct. My inbound and outbound rules are not an issue to my knowledge, and my port mappings are set correctly as far as I know as well.

I've included screenshots of all of the described behavior, as well as a copy of my Dockerfile.

stopping amazon's running image and starting it manually with -p 1200:1200:
(after doing this, my service responds to curl)

logs from doing so:

empty logs from EC2 running the image:

inbound rules:

outbound rules:

port mappings:

Dockerfile:

```<code>    FROM thedarbear/facerec

    EXPOSE 1200

    RUN mkdir -p /facerec
    WORKDIR /facerec
    COPY . /facerec
    RUN cd /facerec
    CMD python3 -u server.py
</code>```

local inspect:

https://pastebin.com/7Y48ukqa

ec2 inspect:

https://pastebin.com/EdJRSEpi

Any insight into why this is happening would be greatly appreciated!

答:
I see the difference in the docker images listed.

ECS is running the one that reads <none> and you are manually running the one that reads latest.

So, update your task definition adding :latest in the image field. Then update your service to use that task definition.

Also, remove manually the problematic image docker rmi -f 4e1b63e39c66

Title: AWS ECS weird docker behavior

Body:
I'm fairly new with Amazon's EC2 service, and I'm at a loss with the weird behavior I'm getting from it.

I have a Docker image that runs flawlessly when ran locally. I have uploaded it to a repository and made a cluster/service/task definition to run it in EC2.

When I attempt to curl to my running service, I'm told the connection refused (as I assume the port is not opened or mapped correctly).

If I ssh into Amazon EC2 and start the image manually with the -p 1200:1200 flag, it again runs without a problem and can be curled without error.

In addition to this, when I try to retrieve the logs from the image that amazon automatically deploys, they are empty.

When running this locally or manually on EC2, the logs exist and are correct. My inbound and outbound rules are not an issue to my knowledge, and my port mappings are set correctly as far as I know as well.

I've included screenshots of all of the described behavior, as well as a copy of my Dockerfile.

stopping amazon's running image and starting it manually with -p 1200:1200:
(after doing this, my service responds to curl)

logs from doing so:

empty logs from EC2 running the image:

inbound rules:

outbound rules:

port mappings:

Dockerfile:

    FROM thedarbear/facerec

    EXPOSE 1200

    RUN mkdir -p /facerec
    WORKDIR /facerec
    COPY . /facerec
    RUN cd /facerec
    CMD python3 -u server.py

local inspect:

https://pastebin.com/7Y48ukqa

ec2 inspect:

https://pastebin.com/EdJRSEpi

Any insight into why this is happening would be greatly appreciated!


问:
Export As A Fixed Format Excel 2007
I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!

Here is my code

```<code>' Define all variables
    Dim strFileName As String
    Dim folder As String
    Dim member As Integer
    Dim member_count As Integer
    Dim member_name As String
    Dim show As Variant
    Dim MyTime As String

'Save as new file
        Worksheets("Input data").Visible = True
        folder = Sheets("Input data").Range("location").Value
        MyTime = Time
        Sheets("Input data").Select
        Range("G2").Value = MyTime
        strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
        Sheets("Material Request").Select
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
</code>```

答:
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.

I was passing a cell value as part of generating the filename. I was doing this in the format of

```<code>fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"
</code>```

The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.

In any case, this fixed the issue for me.

Title: Export As A Fixed Format Excel 2007

Body:
I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!

Here is my code

' Define all variables
    Dim strFileName As String
    Dim folder As String
    Dim member As Integer
    Dim member_count As Integer
    Dim member_name As String
    Dim show As Variant
    Dim MyTime As String

'Save as new file
        Worksheets("Input data").Visible = True
        folder = Sheets("Input data").Range("location").Value
        MyTime = Time
        Sheets("Input data").Select
        Range("G2").Value = MyTime
        strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
        Sheets("Material Request").Select
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`

Body:
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.

I was passing a cell value as part of generating the filename. I was doing this in the format of

fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"

The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.

In any case, this fixed the issue for me.


问:
How can I make the font-awesome can take the full area of its parent container
As you can see the thumbs are over its parent area.
The UI layout is not acceptable.

The following is the expected result.
I tried to put margin-bottom with a negative number,
Or tried to make them in FLEX layout.
None of them works.
Any ideas?

Parent container

```<code>#vote-buttons-section .iconic-button#upvote {
  background: #7f7f7f !important;
  width: 75px;
  height: 55px; }
#vote-buttons-section .iconic-button#downvote {
  background: #7f7f7f;
  height: 55px;
  width: 75px; }
</code>```

Font-awesome icons appear on the BEFORE attribute

```<code>.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f087";
  font-size: 55px;
  color: white;
  vertical-align: middle;
  line-height: 55px;
  }

.ui-button.iconic-button.iconic-button-downvote:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f088";
  font-size: 64px;
  color: white;
  vertical-align: middle; }
</code>```

答:
Seems like the heights of the containers are 55px. What you can do is to add the rule line-height: 55px; to the part that's handling the icons. It seems like you should add it to the selectors

```<code>.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before
</code>```

Then it should be centered. You can adjust the font-size if you want, as long as the line-height is correct, it will be centered.

Body:
As you can see the thumbs are over its parent area.
The UI layout is not acceptable.

The following is the expected result.
I tried to put margin-bottom with a negative number,
Or tried to make them in FLEX layout.
None of them works.
Any ideas?

Parent container

#vote-buttons-section .iconic-button#upvote {
  background: #7f7f7f !important;
  width: 75px;
  height: 55px; }
#vote-buttons-section .iconic-button#downvote {
  background: #7f7f7f;
  height: 55px;
  width: 75px; }

Font-awesome icons appear on the BEFORE attribute

.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f087";
  font-size: 55px;
  color: white;
  vertical-align: middle;
  line-height: 55px;
  }

.ui-button.iconic-button.iconic-button-downvote:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f088";
  font-size: 64px;
  color: white;
  vertical-align: middle; }

Body:
Seems like the heights of the containers are 55px. What you can do is to add the rule line-height: 55px; to the part that's handling the icons. It seems like you should add it to the selectors

.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before

Then it should be centered. You can adjust the font-size if you want, as long as the line-height is correct, it will be centered.


问:
jQuery Sort and MVC Stopped Working
I am getting the following error when JQuery Sort calls my sort action:

The parameters dictionary contains an invalid entry for parameter 'DonationIDS' for method 'System.Web.Mvc.EmptyResult SortDonations(System.Collections.Generic.List1[System.Int32])' in 'Vol.Web.Areas.ActivityArea.Controllers.DonationController'. The dictionary contains a value of type 'System.Collections.Generic.List1[Vol.Models.Token]', but the parameter requires a value of type 'System.Collections.Generic.List`1[System.Int32]'.
Parameter name: parameters

jQuery:

```<code>$("#dlist").sortable({
        handle: '.sorthandle',
        update: function () {
            var order = $('#dlist').sortable('toArray');
            $.ajax({
                url: '/activity/donation/sortdonations',

                data: { DonationIDS: order },
                type: 'POST',
                traditional: true
            });
        }
    });
</code>```

Post Values:

```<code>Parametersapplication/x-www-form-urlencoded
DonationIDS 1
DonationIDS 8
Source
DonationIDS=1&DonationIDS=8
</code>```

MVC Action:

```<code> public EmptyResult SortDonations(List<int> DonationIDS)
        {

            int order = 0;
            foreach (int i in DonationIDS)
            {
                donationRepository.UpdateSortOrder(i, order);
                order++;
            }

            return new EmptyResult();
        }
</code>```

It was working perfectly but now it seems to reference another class, Token.  Any ideas what is going on or where to start looking?

答:
enter code hereI changed by action to use a string and it resolved the issue.

```<code>     [HttpPost]
        public EmptyResult SortDonations(string[] donationorder)

{

    int order = 0;
    foreach (var i in donationorder)
    {
        donationRepository.UpdateSortOrder(Convert.ToInt32(i), order);
        order++;
    }

    return new EmptyResult();
}
</code>```

Title: jQuery Sort and MVC Stopped Working

Body:
I am getting the following error when JQuery Sort calls my sort action:

The parameters dictionary contains an invalid entry for parameter 'DonationIDS' for method 'System.Web.Mvc.EmptyResult SortDonations(System.Collections.Generic.List1[System.Int32])' in 'Vol.Web.Areas.ActivityArea.Controllers.DonationController'. The dictionary contains a value of type 'System.Collections.Generic.List1[Vol.Models.Token]', but the parameter requires a value of type 'System.Collections.Generic.List`1[System.Int32]'.
Parameter name: parameters

jQuery:

$("#dlist").sortable({
        handle: '.sorthandle',
        update: function () {
            var order = $('#dlist').sortable('toArray');
            $.ajax({
                url: '/activity/donation/sortdonations',

                data: { DonationIDS: order },
                type: 'POST',
                traditional: true
            });
        }
    });

Post Values:

Parametersapplication/x-www-form-urlencoded
DonationIDS 1
DonationIDS 8
Source
DonationIDS=1&DonationIDS=8

MVC Action:

 public EmptyResult SortDonations(List<int> DonationIDS)
        {

            int order = 0;
            foreach (int i in DonationIDS)
            {
                donationRepository.UpdateSortOrder(i, order);
                order++;
            }

            return new EmptyResult();
        }

It was working perfectly but now it seems to reference another class, Token.  Any ideas what is going on or where to start looking?

Body:
enter code hereI changed by action to use a string and it resolved the issue.

     [HttpPost]
        public EmptyResult SortDonations(string[] donationorder)

{

    int order = 0;
    foreach (var i in donationorder)
    {
        donationRepository.UpdateSortOrder(Convert.ToInt32(i), order);
        order++;
    }

    return new EmptyResult();
}


问:
How to customize tab bar with icons?
Can someone explain to me what I should add exactly to this code from this website:

```<code>III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

...
//after initialization TabLayout and ViewPager
TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);
tabCall.setIcon(R.drawable.selector_call);

//repeat this code for all your tabs
...
</code>```

Because I get tabLayout and ITEM_CALL in red!

答:
declare this as a constant in your MainActivity class

```<code>private static final Striing ITEM_CALL = 0;
</code>```

do this declaration on your onCreate() :

```<code>TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
</code>```

then create selector_call.xml in the drawable folder with this code :

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/ic_call_selected" />

    <item
        android:state_selected="false"
        android:drawable="@drawable/ic_call_unselected" />

</selector>
</code>```

Title: How to customize tab bar with icons?

Body:
Can someone explain to me what I should add exactly to this code from this website:

III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

...
//after initialization TabLayout and ViewPager
TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);
tabCall.setIcon(R.drawable.selector_call);

//repeat this code for all your tabs
...

Because I get tabLayout and ITEM_CALL in red!

Body:
declare this as a constant in your MainActivity class

private static final Striing ITEM_CALL = 0;

do this declaration on your onCreate() :

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);

then create selector_call.xml in the drawable folder with this code :

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/ic_call_selected" />

    <item
        android:state_selected="false"
        android:drawable="@drawable/ic_call_unselected" />

</selector>


问:
May I have remote git repository on my hosting?
I had been using free github account as a remote repository. Now I am wondering if I can create a github repository on my hosting. There is a git command present on it, but is it enough? I am not permitted to install anything on my hosting. How to check if I can place github repository there.

If it was the posibility to have github a repository there, how to create it? What internet address would it have?

答: you can try Bitbucket host on your server its free for a team less than 5 members but more than it, won't, and also you can have it on your host.</p>


问:
I can send form data using GET method but not POST, why?
So I'm trying to learn html+php but it seems like I've hit a wall. If I use the GET method in my html form, parameters are sent to my php file just fine, but if I try to do the same using the POST method no parameters are sent.

@Edit: I've taken down the initial code sample displayed here as I found out its not a problem specific to that code. Instead I'm posting a basic form and a basic php script that have the same problem:

HTML FILE:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="testingForm.php" method="POST">
        INPUT: <input type="text" id="iTesting" name="nTesting"/><br/>
        <input type="submit" value="SUBMIT"/>
    </form>
</body>
</html>
</code>```

PHP FILE:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
<?php
    /* THIS WORKS: */
    /*if (isset($_GET["nTesting"]))
        echo "It is working! ".$_GET["nTesting"];
    else
        echo "It is NOT working! input: ".$_GET["nTesting"];
    echo "<br/>".$_SERVER['REQUEST_METHOD']."<br/>";
    echo "<br/>".var_dump($_GET);//*/

    /* THIS DOESN'T: */
    if (isset($_POST["nTesting"]))
        echo "It is working! ".$_POST["nTesting"];
    else
        echo "It is NOT working! input: ".$_POST["nTesting"];
    echo "<br/>".$_SERVER['REQUEST_METHOD']."<br/>";
    echo "<br/>".var_dump($_POST);//*/
?>
</body>
</html>
</code>```

As stated before, if I change the form method to GET, I get no problem at all. However, data doesn't seem to be sent when using POST method.

This is the output using the GET method:

It is working! input: test

GET

array(1) { ["nTesting"]=> string(4) "test" }

This is the output using the POST method:

It is NOT working! input:

POST

array(0) { }

Also, using the developers tool I can see there is a parameter nTesting:test in the formData section of the network tab. Yet, nothing is displayed.

答:
If you're using Chrome

Go to index.html

Press f12. Developer tools will show up

Click Network

Tick Preserve Log and Disable Cache (I usually just do it that way)

From index.html click the submit button (do not close dev tools)

Go back to developer tools click 'teste.php'

Click headers, then expand general. You will see 'Request Method'. It should be POST

After working with @MuriloRM we ended up with the fundamental bug with PHPStorm

Please vote up the resolution of the issue
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000097930-Can-not-use-POST-method-in-PhpStorm

Body:
So I'm trying to learn html+php but it seems like I've hit a wall. If I use the GET method in my html form, parameters are sent to my php file just fine, but if I try to do the same using the POST method no parameters are sent.

@Edit: I've taken down the initial code sample displayed here as I found out its not a problem specific to that code. Instead I'm posting a basic form and a basic php script that have the same problem:

HTML FILE:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <form action="testingForm.php" method="POST">
        INPUT: <input type="text" id="iTesting" name="nTesting"/>

        <input type="submit" value="SUBMIT"/>
    </form>

PHP FILE:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title></title>

<?php
    /* THIS WORKS: */
    /*if (isset($_GET["nTesting"]))
        echo "It is working! ".$_GET["nTesting"];
    else
        echo "It is NOT working! input: ".$_GET["nTesting"];
    echo "
".$_SERVER['REQUEST_METHOD']."
";
    echo "
".var_dump($_GET);//*/

    /* THIS DOESN'T: */
    if (isset($_POST["nTesting"]))
        echo "It is working! ".$_POST["nTesting"];
    else
        echo "It is NOT working! input: ".$_POST["nTesting"];
    echo "
".$_SERVER['REQUEST_METHOD']."
";
    echo "
".var_dump($_POST);//*/
?>

As stated before, if I change the form method to GET, I get no problem at all. However, data doesn't seem to be sent when using POST method.

This is the output using the GET method:

It is working! input: test

GET

array(1) { ["nTesting"]=> string(4) "test" }

This is the output using the POST method:

It is NOT working! input:

POST

array(0) { }

Also, using the developers tool I can see there is a parameter nTesting:test in the formData section of the network tab. Yet, nothing is displayed.


问:
Angular-Datatables wrong sorting on date
I'm using the angular-datatables plugin in my project, which works fine on all types, except for dates.

Example DESC:

01/01/2016

01/08/2015

01/08/2015

01/09/2015

Example ASC:

31/12/2015

31/10/2015

22/10/2015

I'm using the Angular Way with a date filter in my ng-repeat. I have a suspicion that it sorts with a wrong date format. I would like it to sort based on the day. How can I fix this?

```<code><table class="table table-hover" datatable="ng">
        <thead>
            <tr>
                <th>Client</th>
                <th>Project</th>
                <th>ID</th>
                <th>Inv. Date</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>DKK ex VAT</th>
                <th>CIG</th>
                <th>Attention</th>
                <th>Cust. Manager</th>
                <th>Regarding</th>
                <th>Due Date</th>
                <th>Finalized</th>
                <th>Paid</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="invoice in vm.latestInvoices.LatestInvoices">
                <td>{{invoice.CompanyName}}</td>
                <td>{{invoice.ProjectName}}</td>
                <td>{{invoice.InvoiceID}}</td>
                <td>{{invoice.InvoiceDate | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceStart | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceEnd | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.DKKexVAT}}</td>
                <td>{{invoice.CustomerInvoiceGroup}}</td>
                <td>{{invoice.Attention}}</td>
                <td>Customer Manager</td>
                <td>{{invoice.Regarding}}</td>
                <td>{{invoice.DueDate | date: 'dd/MM/yyyy'}}</td>
                <td>No</td>
                <td>{{invoice.Paid}}</td>
            </tr>
        </tbody>
    </table>
</code>```

答:
I solved this issue creating a filter

daterFilter.js

```<code>angular.module("app").filter("dateFilter", function(){
  return function(input) {
    var o = input.replace(/-/g, "/"); // Replaces hyphens with slashes if dd/mm/YYYY format
    return Date.parse(o + " -0000");
  };
});
</code>```

In html file

```<code><span>[[ ::created_at | dateFilter | date:"dd/MM/yyyy HH:mm"]]</span>
</code>```

I saw this answer some time ago in this stack:

AngularJS: How to format ISO8601 date format?

Body:
I'm using the angular-datatables plugin in my project, which works fine on all types, except for dates.

Example DESC:

01/01/2016

01/08/2015

01/08/2015

01/09/2015

Example ASC:

31/12/2015

31/10/2015

22/10/2015

I'm using the Angular Way with a date filter in my ng-repeat. I have a suspicion that it sorts with a wrong date format. I would like it to sort based on the day. How can I fix this?

                Client
                Project
                ID
                Inv. Date
                Start Date
                End Date
                DKK ex VAT
                CIG
                Attention
                Cust. Manager
                Regarding
                Due Date
                Finalized
                Paid

                {{invoice.CompanyName}}
                {{invoice.ProjectName}}
                {{invoice.InvoiceID}}
                {{invoice.InvoiceDate | date: 'dd/MM/yyyy'}}
                {{invoice.InvoiceStart | date: 'dd/MM/yyyy'}}
                {{invoice.InvoiceEnd | date: 'dd/MM/yyyy'}}
                {{invoice.DKKexVAT}}
                {{invoice.CustomerInvoiceGroup}}
                {{invoice.Attention}}
                Customer Manager
                {{invoice.Regarding}}
                {{invoice.DueDate | date: 'dd/MM/yyyy'}}
                No
                {{invoice.Paid}}

Body:
I solved this issue creating a filter

daterFilter.js

angular.module("app").filter("dateFilter", function(){
  return function(input) {
    var o = input.replace(/-/g, "/"); // Replaces hyphens with slashes if dd/mm/YYYY format
    return Date.parse(o + " -0000");
  };
});

In html file

<span>[[ ::created_at | dateFilter | date:"dd/MM/yyyy HH:mm"]]</span>

I saw this answer some time ago in this stack:

AngularJS: How to format ISO8601 date format?


问:
Uniformly update jQueryUI Progressbar over N seconds
Given a variable N, reflecting a number of seconds, I'd like to have a jQueryUI Progressbar smoothly update from being empty to reflecting completion over that period of time.

In other words, I'd like a function n_sec_progressbar(n) { ... } that shows a progressbar, and over n seconds the progressbar uniformly advances from a value of 0 to 100.

Before I go ahead and start fiddling with setTimeout on my own, I'd be grateful for any suggestions or direction towards something like this that's already been done.

Thank you for reading.

Brian

答: I would think it would be easier just to write your own custom progress bar using the callback of animate() (jQuery core API). That would give you the most control for a loading animation like that.