问:
Remove automatic naming of variables in visualizations in Power BI
I have two columns with dates and daily currency observations. In a chart, the default title looks like this:

If you change the valuetype to Average like this:

Then the title changes as well:

Is there any way to override this functionality?
There is a suggestion on community.powerbi.com to add another measure with the desired name, but that is not a very feasible solution when you have a lot of variables.

Thank you for any suggestions!

Edit in response to a comment below where @user5226582 correctly points out that the title can be easily edited. Here's another example with two variables and labels in addition to a title:

The title, as you pointed out, can easily be changed here:

So that we end up with this:

However, the problem  with the automatic addition of Average of... still persist in the legend:

And as far as i can tell you don't have the same felxibility with the legend as you do with the title:

答:
The solution, as mentioned in your question, is to define a measure. That way, you can name it whatever makes the most sense.

You mention that it's not very feasible to create measures when you have a lot of variables, but I'm not aware of a fixed limit. You don't have to create a measure for everything: you could just create measures for numbers you want to average, for example. Personally, I recommend measures for all the main metrics. I usually hide the underlying columns, so no-one is confused.

There are a few benefits of using measures (in no particular order):

You can name a measure whatever you want since the measure is not coupled to the underlying column

You can change the definition of a measure at any time and it will update everywhere (e.g. change it to average a different column, for example)

You don't have to switch from 'sum' to 'average' every time you use the measure, as you've pre-defined it

There's no risk you use the wrong type of aggregation (e.g. sum when you don't intend to)

You can define a specific format (number of decimal places, thousands separator, etc), which can vary from the underlying column. Further, you can standardize that format for that measure, saving you having to apply the format every time you use it

You can use simple measures (sums and averages) as building blocks in more complex measures, making those more complex measures easier to read, along with all the benefits of being able to change the underlying base measure definition should you ever need to

It might sound silly that you'd ever want to change the definition of a basic averaging measure, but such things can happen and it's a pain if you have to update a dozen or more charts & visuals & complex measures to make the change.

I'm sure there are other benefits I'm not thinking of too, but in general, using measures isn't something to avoid. Quite the opposite: measures are the foundation of advanced modeling in Power BI.


来源: stackexchange

问:
How to set up Spark cluster on laptop?
I am completely new at Spark and try to run a tutorial example, which counts the number of lines containing 'a' and 'b' in a text file in the local file system.

I am running it with SparkContext with master = "local", i.e. Spark is running in the same JVM. Now I would like to try it in "cluster mode".

So I would like to run a Spark cluster of a cluster manager and two worker nodes locally on my Mac laptop. What is the easiest way to do that ?

答:
If you are looking to learn various ways to use SPARK I would suggest you to download the CLOUDERA quick start VM's which will give a simple cluster setup.

All you need to do is download the quick start VM and play around with the settings accordingly.

The quick start VM can be found here

Reference:Cloudera VM

ContentLicense: CC BY-SA 3.0

Title: How to set up Spark cluster on laptop?


问:
Progress Bar not showing in screen but showing in debugger
I am adding a Progress Bar when the user does a search query, and it will not show up in the screen. Here are the snippets:

```<code>    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button searchButton = (Button) findViewById(R.id.searchButton);
        setContentView(R.layout.activity_main); //main layout, which has a child layout called resultsLayout
        searchButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            EditText searchString = (EditText) findViewById(R.id.searchString);
            search(searchString.getText().toString());
        }
    });

    protected void search(String searchString){
        LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
        resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
        //do search
        resultLayout.removeAllViews();
    }

    public static ProgressBar getLoadBar(Context context){
        ProgressBar loadBar = new ProgressBar(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        loadBar.setLayoutParams(params);
        loadBar.setVisibility(View.VISIBLE);
        return loadBar;
    }
</code>```

I know some of it might not be needed, like the setVisibility right when creating, but I have tried several things and it not works. Perhaps there wasn't enough time to show up the bar?(It takes about 1.5sec for the search)

I have also debugged the application, and it shows the ProgressBar as a child of the layout, but I still cannot see it in the screen.

答: I realized that android does not update the screen for every instruction in the code, apparently it does so only when a function ends. That being said, I had to do my search in a separate thread in order for the loading to appear between the time the searched started and before it ended.</p>

Body:
I am adding a Progress Bar when the user does a search query, and it will not show up in the screen. Here are the snippets:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button searchButton = (Button) findViewById(R.id.searchButton);
        setContentView(R.layout.activity_main); //main layout, which has a child layout called resultsLayout
        searchButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            EditText searchString = (EditText) findViewById(R.id.searchString);
            search(searchString.getText().toString());
        }
    });

    protected void search(String searchString){
        LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
        resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
        //do search
        resultLayout.removeAllViews();
    }

    public static ProgressBar getLoadBar(Context context){
        ProgressBar loadBar = new ProgressBar(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        loadBar.setLayoutParams(params);
        loadBar.setVisibility(View.VISIBLE);
        return loadBar;
    }

I know some of it might not be needed, like the setVisibility right when creating, but I have tried several things and it not works. Perhaps there wasn't enough time to show up the bar?(It takes about 1.5sec for the search)

I have also debugged the application, and it shows the ProgressBar as a child of the layout, but I still cannot see it in the screen.


问:
WPF Combobox in TableView can't show first item as default
I'm using Combobox in TableView, and i want to show the first item text as its default value, i tried to add SelectionIndex=0, but it didn't work, its default value is empty. Different with other question like

Comboxbox auto select first item when data is available

my combobox belongs to TableView, each item has a combobox(actually each grid item has many types of combobox), so i can't use some methods need to handle it one by one.

my code is as below, and the itemsource Cities is a Dictionary, and i use DisplayMemberPath="Value" SelectedValuePath="Value" to show its value(not key):

```<code><dxg:GridColumn FieldName="FloorSetUp" Header="Type" MinWidth="20"  HorizontalHeaderContentAlignment="Center" VisibleIndex="1">
  <dxg:GridColumn.CellTemplate>
      <DataTemplate>
           <ComboBox DisplayMemberPath="Value" SelectedValuePath="Value" ItemsSource="{Binding Data.Cities}" SelectedIndex="0"/>
      </DataTemplate>
  </dxg:GridColumn.CellTemplate>
</dxg:GridColumn>
</code>```

Anyone can solve this problem?thanks very much!

答:
Is FloorSetUp also KeyValuePair<T,R>?

becuse if not, thats your problem.

The ComboBox has to work with data of same types both in items source and in selected item property.

Body:
I'm using Combobox in TableView, and i want to show the first item text as its default value, i tried to add SelectionIndex=0, but it didn't work, its default value is empty. Different with other question like

Comboxbox auto select first item when data is available

my combobox belongs to TableView, each item has a combobox(actually each grid item has many types of combobox), so i can't use some methods need to handle it one by one.

my code is as below, and the itemsource Cities is a Dictionary, and i use DisplayMemberPath="Value" SelectedValuePath="Value" to show its value(not key):

<dxg:GridColumn FieldName="FloorSetUp" Header="Type" MinWidth="20"  HorizontalHeaderContentAlignment="Center" VisibleIndex="1">
  <dxg:GridColumn.CellTemplate>
      <DataTemplate>
           <ComboBox DisplayMemberPath="Value" SelectedValuePath="Value" ItemsSource="{Binding Data.Cities}" SelectedIndex="0"/>
      </DataTemplate>
  </dxg:GridColumn.CellTemplate>
</dxg:GridColumn>

Anyone can solve this problem?thanks very much!


问:
Get latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh
My requirement is simple , I have a repeater control webpart, and I want to apply a condition in the WHERE clause.

Condition : The latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh.

Means if record is more than 1 week , then it will show latest by , upon page refresh.

I made this query but it doesn't work:

```<code>(DocumentCreatedWhen >= dateadd(day, -7, convert(date, getdate())))
</code>```

答:
I'm a little confused on the "on page refresh" portion of your request.  You said in your first part that "after that it will show randomly upon page refresh" then on the 2nd part said "if the record is greater than 1 week, it will show upon page refresh"

Which do you want?

To filter out events that are at least 1 week old, you would do

DATEDIFF(day, DocumentCreatedWhen , GETDATE()) >= 7

from there you can do an ORDER BY DocumentCreateWhen asc, and a Top # of 1.

If you want to apply different logic on postback, you can use macros and the Visibility to make the "random" repeater visible on post back, and the other visible if it's not postback, or use macros to provide different WHERE conditions based on the postback status.

I could not find a default "IsPostback" macro available so you will have to create a custom macro that returns the current postback status.

Body:
My requirement is simple , I have a repeater control webpart, and I want to apply a condition in the WHERE clause.

Condition : The latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh.

Means if record is more than 1 week , then it will show latest by , upon page refresh.

I made this query but it doesn't work:

(DocumentCreatedWhen >= dateadd(day, -7, convert(date, getdate())))


问:
Find the time complexity of a recursive function
Why is the time complexity of this function O(n1*n2) when n1 is the length of s1 and n2 is the length of s2?   </p>

<p>I tried to build an equation but failed. </p>

```<code>#include <stdio.h>

int f(char* s1, int i1, char* s2, int i2) {
    if (s2[i2] == '\0')
        return 1;
    if (s1[i1] == '\0')
        return 0;
    if (s1[i1] != s2[i2])
        return f(s1, i1 + 1, s2, 0);
    return f(s1, i1+1, s2, i2+1);
}

void main() {
    printf("%d", f("hello", 0, "he", 0));
}
</code>```

答:
The function increments i1 by 1 for both tail call, hence the time complexity is O(n1).

Note that this function does not implement a variant of strstr() as it would fail to find a match for f("aab", 0, "ab", 0).

Body:
Why is the time complexity of this function O(n1*n2) when n1 is the length of s1 and n2 is the length of s2?

I tried to build an equation but failed.

#include <stdio.h>

int f(char* s1, int i1, char* s2, int i2) {
    if (s2[i2] == '\0')
        return 1;
    if (s1[i1] == '\0')
        return 0;
    if (s1[i1] != s2[i2])
        return f(s1, i1 + 1, s2, 0);
    return f(s1, i1+1, s2, i2+1);
}

void main() {
    printf("%d", f("hello", 0, "he", 0));
}


问:
Git log up to a certain commit
I know it's possible to use git log to get commit history between two commits, between two dates, since a date, before a date, and so on..but I've yet to see a way to get a log up to a certain commit.

I know this probably doesn't exist because of the problem of having multiple commits with the same parent/no parent (hard to find the definitive first commit), but is there a workaround?

I've been doing this...

Get the first commit:
FIRST_COMMIT=git rev-list HEAD | tail -n 1

Get between first and commit I want
git log FIRST_COMMIT..ff353d1

But is there a better way? Like using from the beginning of time up unto the time of the commit I want to use?

答: git log FIRST_COMMIT..ff353d1 shows (mostly) the same as git log ff353d1, you don't need to be too fancy. If you want it in reverse order - just use git log --reverse ff353d1.

Title: Git log up to a certain commit


问:
Simulating windows laptop in virtual machine?
I wonder if there is a way to simulate laptop in a virtual machine. Specifically, I would like to simulate the lid closing behavior. I checked virtual box and it doesn't seem to have this kind of feature.

Thanks!

答:
You will have to write an application to do that.

The message you are interested in broadcasting is WM_POWERBROADCAST.

Take a look here if you also need to catch it.

ContentLicense: CC BY-SA 2.5


问:
Tcpreplay parameter and CPU usage
I have created a UDP file using Scapy and I'm using tcpreplay to send the packet. I've faced two weird issues:

The number of packets sent is not identical to the (--pps) parameter. Not sure if the answer is (http://tcpreplay.appneta.com/wiki/faq.html#why-doesnt-tcpreplay-send-traffic-as-fast-as-i-told-it-to)

When I send less packets, i.e --pps=10, the CPU load is higher when I send more packets, i.e. --pps=200. I was expecting the other way around.

BTW, I'm using tcpreplay version 3.4.4

答:
Issue 1. many --pps issues fixed in latest Tcpreplay version

Issue 2. CPU utilization is improved with latest version, but you can still expect to see 100% CPU being reported. In reality CPU utilization is over reported when using -t or --mbps=0 options. In these cases Tcpreplay will yield the sending thread whenever the TX buffers are full. This causes Tcpreplay to become the scheduler for the CPU. The result is a reported 100% CPU, however other processes on the CPU remain responsive.

ContentLicense: CC BY-SA 4.0

Title: Tcpreplay parameter and CPU usage


问:
Multithreading - Calculations between all pairs in a set
I have n elements (e.g. A, B, C and D) and need to do calculations between all of those.

```<code>Calculation 1 = A with B
Calculation 2 = A with C
Calculation 3 = A with D
Calculation 4 = B with C
Calculation 5 = B with D
Calculation 6 = C with D
</code>```

In reality there are more than 1000 elements and I want to parallelise the process.

Note that I can't access an element from 2 threads simultaneously. This for example makes it impossible to do Calculation 1 and Calculation 2 at the same time because they both use the element A.

Edit: I could access an element from 2 threads but it makes everything very slow if i just split up the calculations and depend on locks for threadsafety.

Is there already an distribution algorithm for these kind of problems?

It seems like a lot of people must have had the same problem already but i couldn't find anything in the great internet. ;)

Single thread example code:

```<code>for (int i = 0; i < elementCount; i++)
{
   for (int j = i + 1; j < elementCount; j++)
   {
      Calculate(element[i], element[j]);
   }
}
</code>```

答:
It is simple enough to prove there is no way to distribute your calculations so that collisions never occur (that is, unless you manually order the computations and place round-boundaries, like @Mbo suggests), meaning that there is no distribution amongst multiple threads that will allow you to never lock.

Proof :
Given your requirement that any computation involving data object A should happen on a given thread T (only way to make sure you never lock on A).

Then it follows that thread T has to deal with at least one pair containing each other objects (B, C, D) of the input list.

It follows from the basic requirement that T is also to handle everything object-B related. And C. And D. So everything.

Therefore, only T can work.

QED. There is no possible parallelization that will never lock.

Way around #1 : map/reduce

That said... This is a typical case of divide and conquer. You are right that simple additions can require critical section locks, without the order of execution mattering. That is because your critical operation (addition) has a nice property, associativeness : A+(B+C) = (A+B)+C, on top of being commutative.

In other words, this operation is a candidate for a (parralel-friendly) reduce operation.

So the key here is probably :

Emit a stream of all interesting pairs

Map each pair to one or more partial results

Group each partial result by its master object (A, B, C)

Reduce each group by combining the partial results

A sample (pseudo) code

```<code>static class Data { int i = 0; }
static class Pair { Data d1; Data d2; }
static class PartialComputation { Data d; int sum; }

Data[] data = ...
Stream<Pair> allPairs = ... // Something like IntStream(0, data.length-1).flatMap(idx -> IntStream(idx+1 to data.length ).map(idx2 -> new Pair(data[idx], data[idx2])))
allPairs.flatMap(pair -> Stream.of(new ParticalComputation(pair.d1, pair.d1.i + pair.d2.i), new PartialComputation(pair.d2, pair.d2.i+pair.d1.i)) // Map everything, parallely, to partial results keyable by the original data object
allPairs.collect(Collectors.groupByParallel(
    partialComp -> partialComp.d, // Regroup by the original data object
    Collectors.reducing(0, (sum1, sum2) -> sum1.sum + sum2.sum)) // reduce by summing
))
</code>```

Way around 2 : trust the implementations

Fact is, uncontended locks in java have gotten cheaper. On top of that, pure locking sometimes has better alternatives, like Atomic types in Java (e.g. AtomicLong if you are summing stuff), that use CAS instead of locking, which can be faster (google for it, I usually refer to the Java Concurrency In Practice book for hard numbers.)

The fact is, if you have 1000 to 10k different elements (which translates to at least millions of pairs) and, like, 8 CPUs, the contention (or probability that at least 2 of your 8 threads will be processing the same element) is pretty low. And I would rather measure it first-hand rather than saying upfront "I can not affor the locks", especially if the operation can be implemented using Atomic types.

Body:
I have n elements (e.g. A, B, C and D) and need to do calculations between all of those.

Calculation 1 = A with B
Calculation 2 = A with C
Calculation 3 = A with D
Calculation 4 = B with C
Calculation 5 = B with D
Calculation 6 = C with D

In reality there are more than 1000 elements and I want to parallelise the process.

Note that I can't access an element from 2 threads simultaneously. This for example makes it impossible to do Calculation 1 and Calculation 2 at the same time because they both use the element A.

Edit: I could access an element from 2 threads but it makes everything very slow if i just split up the calculations and depend on locks for threadsafety.

Is there already an distribution algorithm for these kind of problems?

It seems like a lot of people must have had the same problem already but i couldn't find anything in the great internet. ;)

Single thread example code:

for (int i = 0; i < elementCount; i++)
{
   for (int j = i + 1; j < elementCount; j++)
   {
      Calculate(element[i], element[j]);
   }
}

Body:
It is simple enough to prove there is no way to distribute your calculations so that collisions never occur (that is, unless you manually order the computations and place round-boundaries, like @Mbo suggests), meaning that there is no distribution amongst multiple threads that will allow you to never lock.

Proof :
Given your requirement that any computation involving data object A should happen on a given thread T (only way to make sure you never lock on A).

Then it follows that thread T has to deal with at least one pair containing each other objects (B, C, D) of the input list.

It follows from the basic requirement that T is also to handle everything object-B related. And C. And D. So everything.

Therefore, only T can work.

QED. There is no possible parallelization that will never lock.

Way around #1 : map/reduce

That said... This is a typical case of divide and conquer. You are right that simple additions can require critical section locks, without the order of execution mattering. That is because your critical operation (addition) has a nice property, associativeness : A+(B+C) = (A+B)+C, on top of being commutative.

In other words, this operation is a candidate for a (parralel-friendly) reduce operation.

So the key here is probably :

Emit a stream of all interesting pairs

Map each pair to one or more partial results

Group each partial result by its master object (A, B, C)

Reduce each group by combining the partial results

A sample (pseudo) code

static class Data { int i = 0; }
static class Pair { Data d1; Data d2; }
static class PartialComputation { Data d; int sum; }

Data[] data = ...
Stream<Pair> allPairs = ... // Something like IntStream(0, data.length-1).flatMap(idx -> IntStream(idx+1 to data.length ).map(idx2 -> new Pair(data[idx], data[idx2])))
allPairs.flatMap(pair -> Stream.of(new ParticalComputation(pair.d1, pair.d1.i + pair.d2.i), new PartialComputation(pair.d2, pair.d2.i+pair.d1.i)) // Map everything, parallely, to partial results keyable by the original data object
allPairs.collect(Collectors.groupByParallel(
    partialComp -> partialComp.d, // Regroup by the original data object
    Collectors.reducing(0, (sum1, sum2) -> sum1.sum + sum2.sum)) // reduce by summing
))

Way around 2 : trust the implementations

Fact is, uncontended locks in java have gotten cheaper. On top of that, pure locking sometimes has better alternatives, like Atomic types in Java (e.g. AtomicLong if you are summing stuff), that use CAS instead of locking, which can be faster (google for it, I usually refer to the Java Concurrency In Practice book for hard numbers.)

The fact is, if you have 1000 to 10k different elements (which translates to at least millions of pairs) and, like, 8 CPUs, the contention (or probability that at least 2 of your 8 threads will be processing the same element) is pretty low. And I would rather measure it first-hand rather than saying upfront "I can not affor the locks", especially if the operation can be implemented using Atomic types.


问:
What should I do when one function finishes another one opens up?
I have a Problem. I'm Trying to make a regular Calculator and Shape's Area and Perimeter finder.It's a combination.  I didn't start on my Shape's Area and Perimeter Finder. This is My main.cpp.

```<code> #include <iostream>
 #include <string>
 #include "AAPO.h" // Its a Header File.

using namespace std;

void Calculators_Operation();

int main()
{
    string opera;
    cout << "Do you want Arithmetic Calculator or Area and Perimeter Calculator"
    << endl;

    cin >> opera;
    if (opera == "Arithmetic Calculator" or "arithmetic calculator" or "AC")
    {
        Calculators_Operation();
    }
    return 0;
}
</code>```

This is my Operation Chooser.

```<code>#include <iostream>
#include <string>
#include "Arithmetic Chooser.h"

using namespace std;

void Calculators_Addition();
void Calculators_Subtraction();
void Calculators_Multiplication();
void Calculators_Division();

void Calculators_Operation()
{
    string answera;
    cout << "What Operation do you Want?" << endl;
    cin >> answera;
    if (answera == "Addition" or "addition" or "+");
    {
        Calculators_Addition();
    };
    if (answera == "Subtraction" or "subtraction" or "-");
    {
        Calculators_Subtraction();
    };
    if (answera == "Multiplication" or "multiplication" or "*" or "x" or "X")
    {
        Calculators_Multiplication();
    };
    if (answera == "Division" or "division" or "/")
    {
        Calculators_Division();
    };
    return;
}
</code>```

This is my AAPO.h.

```<code>#ifndef AAPO_H_INCLUDED
#define AAPO_H_INCLUDED

void Calculators_Operation();

#endif // AAPO_H_INCLUDED
</code>```

My Addition.

```<code>#include <iostream>
#include <string>

using namespace std;

void calculators_Addition_2();
void calculators_Addition_3();
void calculators_Addition_4();
void calculators_Addition_5();

void Calculators_Addition()
{
    //ADDITION COMPLETE
    string numberadd;
    cout << "How much numbers do you want?" << endl;
    cin >> numberadd;
    if (numberadd == "2")
    {
        calculators_Addition_2();
        return;
    };
    if (numberadd == "3")
    {
        calculators_Addition_3();
        return;
    };
    if (numberadd == "4")
    {
        calculators_Addition_4();
        return;
    };
    if (numberadd == "5")
    {
        calculators_Addition_5();
        return;
    }
}

void calculators_Addition_2()
{
    int add11;
    int add12;
    int sum;
    cout << "Enter the first number" << endl;
    cin >> add11;
    cout << "Enter the second number" << endl;
    cin >> add12;
    sum = add11 + add12;
    cout << "The sum of the numbers are " << sum << endl;
    return;
}

void calculators_Addition_3()
{
    int add13;
    int add23;
    int add33;
    int sum2;
    cout << "Enter the First Number" << endl;
    cin >> add13;
    cout << "Enter the Second Number" << endl;
    cin >> add23;
    cout << "Enter the Third Number" << endl;
    cin >> add33;
    sum2 = add13 + add23 + add33;
    cout << "The Sum of the Numbers are " << sum2 << endl;
    return;
}

void calculators_Addition_4()
{
    int add14;
    int add24;
    int add34;
    int add44;
    int sum3;
    cout << "Enter the First Number" << endl;
    cin >> add14;
    cout << "Enter the Second Number" << endl;
    cin >> add24;
    cout << "Enter the Third Number" << endl;
    cin >> add34;
    cout << "Enter the Fourth Number" << endl;
    cin >> add44;
    sum3 = add14 + add24 + add34 + add44;
    cout << "The Sum of the Numbers are " << sum3 << endl;
    return;
}

void calculators_Addition_5()
{
    int a15;
    int a25;
    int a35;
    int a45;
    int a55;
    int sum4;
    cout << "Enter the First Number" << endl;
    cin >> a15;
    cout << "Enter the Second Number" << endl;
    cin >> a25;
    cout << "Enter the Third Number" << endl;
    cin >> a35;
    cout << "Enter the Fourth Number" << endl;
    cin >> a45;
    cout << "Enter the Fifth Number" << endl;
    cin >> a55;
    sum4 = a15 + a25 + a35 + a45 + a55;
    cout << "The Sum of the Numbers are " << sum4 << endl;
    return;
}
</code>```

My Subtraction.

```<code>#include <iostream>

using namespace std;

void Calculators_Subtraction()
{
    int subractify;
    int subracta;
    int differencea;
    cout << "Type in the First Number!" << endl;
    cin >> subractify;
    cout << "Type in the Second Number!" << endl;
    cin >> subracta;
    differencea = subractify - subracta;
    cout << "The Difference is " << differencea << endl;
    return;
}
</code>```

My Multiplication.

```<code>#include <iostream>
#include <string>

using namespace std;

void Calculators_Multiplication_2();
void Calculators_Multiplication_3();
void Calculators_Multiplication_4();
void Calculators_Multiplication_5();

void Calculators_Multiplication()
{
    string multicipia;
    cout << "How much numbers do you want?" << endl;
    cin >> multicipia;
    if (multicipia == "2" or "Two" or "two")
    {
        Calculators_Multiplication_2();
    };
    if (multicipia == "3" or "Three" or "three")
    {
        Calculators_Multiplication_3();
    };
    if (multicipia == "4" or "Four" or "four")
    {
        Calculators_Multiplication_4();
    };
    if (multicipia == "5" or "Five" or "five")
    {
        Calculators_Multiplication_5();
    };
    return;
}

void Calculators_Multiplication_2()
{
    int multi2a;
    int multi2b;
    int product2;
    cout << "Type in the First Number." << endl;
    cin >> multi2a;
    cout << "Type in the Second Number." << endl;
    cin >> multi2b;
    product2 = multi2a * multi2b;
    cout << "The Product is " << product2 << "." << endl;
    return;
}

void Calculators_Multiplication_3()
{
    int multi3a;
    int multi3b;
    int multi3c;
    int product3;
    cout << "Enter the First Number!" << endl;
    cin >> multi3a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi3b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi3c;
    product3 = multi3a * multi3b * multi3c;
    cout << "The Product is" << product3 << "." << endl;
    return;
}

void Calculators_Multiplication_4()
{
    int multi4a;
    int multi4b;
    int multi4c;
    int multi4d;
    int product4;
    cout << "Enter the First Number!" << endl;
    cin >> multi4a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi4b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi4c;
    cout << "Enter the Fourth Number!" << endl;
    cin >> multi4b;
    product4 = multi4a * multi4b * multi4c * multi4d;
    cout << "The Product of the Numbers are " << product4 << "!" << endl;
    return;
}

void Calculators_Multiplication_5()
{
    int multi5a;
    int multi5b;
    int multi5c;
    int multi5d;
    int multi5e;
    int product5;
    cout << "Enter the First Number!" << endl;
    cin >> multi5a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi5b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi5c;
    cout << "Enter the Fourth Number!" << endl;
    cin >> multi5d;
    cout << "Enter the Fifth Number!" << endl;
    cin >> multi5e;
    product5 = multi5a * multi5b * multi5c * multi5d * multi5e;
    cout << "The Product of the Numbers are" << product5 << "!" << endl;
    return;
}
</code>```

My Division.

```<code>#include <iostream>

using namespace std;

void Calculators_Division()
{
    float divisia;
    float divisiab;
    float quotient;
    cout << "Enter the Divisor" << endl;
    cin >> divisia;
    cout << "Enter the Dividend" << endl;
    cin >> divisiab;
    quotient = divisia / divisiab;
    cout << "The Quotient of the Numbers are " << quotient << endl;
    return;
}
</code>```

The Problem right now is that when addition finishes , subtraction starts. After Subtraction, Multiplication. After Multiplication, Division. After That the program ends. I'm sorry. Its just that I'm new to programming (Like one month).

答:
There are many things to improve (some of them already mentioned in comments), but exact answer to your question is:

you have semicolon after your if-statement lines in Calculators_Operation() function body, which makes if-statements useless and your "operation" functions are being called every time (what you already noticed).

you use "or" operator in incorrect way, if you use (answera == "addition" or "+"), you basically say: ((answera == "addition) or "+") and that evaluates to true (see here)

EDIT:
Your function Calculators_Operation may be changed to:

```<code>void Calculators_Operation()
{
   string answera;
   cout << "What Operation do you Want?" << endl;
   cin >> answera;

   if (answera == "Addition" || answera == "addition" || answera == "+")
   {
       Calculators_Addition();
   }
   else if (answera == "Subtraction" || answera == "subtraction" || answera == "-")
   {
       Calculators_Subtraction();
   }
   else if (answera == "Multiplication" || answera == "multiplication" || answera == "*" || answera == "x" || answera == "X")
   {
       Calculators_Multiplication();
   }
   else if (answera == "Division" || answera == "division" || answera == "/")
   {
       Calculators_Division();
   } else {
     cout << "Unknown operation entered!" << endl;
   }
}
</code>```

NOTE: all your if statements need to be changed according to this function.

If anything does not work, please either put in comments what exactly does not work or edit your question with new code posting and question.

Body:
I have a Problem. I'm Trying to make a regular Calculator and Shape's Area and Perimeter finder.It's a combination.  I didn't start on my Shape's Area and Perimeter Finder. This is My main.cpp.

 #include <iostream>
 #include <string>
 #include "AAPO.h" // Its a Header File.

using namespace std;

void Calculators_Operation();

int main()
{
    string opera;
    cout << "Do you want Arithmetic Calculator or Area and Perimeter Calculator"
    << endl;

    cin >> opera;
    if (opera == "Arithmetic Calculator" or "arithmetic calculator" or "AC")
    {
        Calculators_Operation();
    }
    return 0;
}

This is my Operation Chooser.

#include <iostream>
#include <string>
#include "Arithmetic Chooser.h"

using namespace std;

void Calculators_Addition();
void Calculators_Subtraction();
void Calculators_Multiplication();
void Calculators_Division();

void Calculators_Operation()
{
    string answera;
    cout << "What Operation do you Want?" << endl;
    cin >> answera;
    if (answera == "Addition" or "addition" or "+");
    {
        Calculators_Addition();
    };
    if (answera == "Subtraction" or "subtraction" or "-");
    {
        Calculators_Subtraction();
    };
    if (answera == "Multiplication" or "multiplication" or "*" or "x" or "X")
    {
        Calculators_Multiplication();
    };
    if (answera == "Division" or "division" or "/")
    {
        Calculators_Division();
    };
    return;
}

This is my AAPO.h.

#ifndef AAPO_H_INCLUDED
#define AAPO_H_INCLUDED

void Calculators_Operation();

#endif // AAPO_H_INCLUDED

My Addition.

#include <iostream>
#include <string>

using namespace std;

void calculators_Addition_2();
void calculators_Addition_3();
void calculators_Addition_4();
void calculators_Addition_5();

void Calculators_Addition()
{
    //ADDITION COMPLETE
    string numberadd;
    cout << "How much numbers do you want?" << endl;
    cin >> numberadd;
    if (numberadd == "2")
    {
        calculators_Addition_2();
        return;
    };
    if (numberadd == "3")
    {
        calculators_Addition_3();
        return;
    };
    if (numberadd == "4")
    {
        calculators_Addition_4();
        return;
    };
    if (numberadd == "5")
    {
        calculators_Addition_5();
        return;
    }
}

void calculators_Addition_2()
{
    int add11;
    int add12;
    int sum;
    cout << "Enter the first number" << endl;
    cin >> add11;
    cout << "Enter the second number" << endl;
    cin >> add12;
    sum = add11 + add12;
    cout << "The sum of the numbers are " << sum << endl;
    return;
}

void calculators_Addition_3()
{
    int add13;
    int add23;
    int add33;
    int sum2;
    cout << "Enter the First Number" << endl;
    cin >> add13;
    cout << "Enter the Second Number" << endl;
    cin >> add23;
    cout << "Enter the Third Number" << endl;
    cin >> add33;
    sum2 = add13 + add23 + add33;
    cout << "The Sum of the Numbers are " << sum2 << endl;
    return;
}

void calculators_Addition_4()
{
    int add14;
    int add24;
    int add34;
    int add44;
    int sum3;
    cout << "Enter the First Number" << endl;
    cin >> add14;
    cout << "Enter the Second Number" << endl;
    cin >> add24;
    cout << "Enter the Third Number" << endl;
    cin >> add34;
    cout << "Enter the Fourth Number" << endl;
    cin >> add44;
    sum3 = add14 + add24 + add34 + add44;
    cout << "The Sum of the Numbers are " << sum3 << endl;
    return;
}

void calculators_Addition_5()
{
    int a15;
    int a25;
    int a35;
    int a45;
    int a55;
    int sum4;
    cout << "Enter the First Number" << endl;
    cin >> a15;
    cout << "Enter the Second Number" << endl;
    cin >> a25;
    cout << "Enter the Third Number" << endl;
    cin >> a35;
    cout << "Enter the Fourth Number" << endl;
    cin >> a45;
    cout << "Enter the Fifth Number" << endl;
    cin >> a55;
    sum4 = a15 + a25 + a35 + a45 + a55;
    cout << "The Sum of the Numbers are " << sum4 << endl;
    return;
}

My Subtraction.

#include <iostream>

using namespace std;

void Calculators_Subtraction()
{
    int subractify;
    int subracta;
    int differencea;
    cout << "Type in the First Number!" << endl;
    cin >> subractify;
    cout << "Type in the Second Number!" << endl;
    cin >> subracta;
    differencea = subractify - subracta;
    cout << "The Difference is " << differencea << endl;
    return;
}

My Multiplication.

#include <iostream>
#include <string>

using namespace std;

void Calculators_Multiplication_2();
void Calculators_Multiplication_3();
void Calculators_Multiplication_4();
void Calculators_Multiplication_5();

void Calculators_Multiplication()
{
    string multicipia;
    cout << "How much numbers do you want?" << endl;
    cin >> multicipia;
    if (multicipia == "2" or "Two" or "two")
    {
        Calculators_Multiplication_2();
    };
    if (multicipia == "3" or "Three" or "three")
    {
        Calculators_Multiplication_3();
    };
    if (multicipia == "4" or "Four" or "four")
    {
        Calculators_Multiplication_4();
    };
    if (multicipia == "5" or "Five" or "five")
    {
        Calculators_Multiplication_5();
    };
    return;
}

void Calculators_Multiplication_2()
{
    int multi2a;
    int multi2b;
    int product2;
    cout << "Type in the First Number." << endl;
    cin >> multi2a;
    cout << "Type in the Second Number." << endl;
    cin >> multi2b;
    product2 = multi2a * multi2b;
    cout << "The Product is " << product2 << "." << endl;
    return;
}

void Calculators_Multiplication_3()
{
    int multi3a;
    int multi3b;
    int multi3c;
    int product3;
    cout << "Enter the First Number!" << endl;
    cin >> multi3a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi3b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi3c;
    product3 = multi3a * multi3b * multi3c;
    cout << "The Product is" << product3 << "." << endl;
    return;
}

void Calculators_Multiplication_4()
{
    int multi4a;
    int multi4b;
    int multi4c;
    int multi4d;
    int product4;
    cout << "Enter the First Number!" << endl;
    cin >> multi4a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi4b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi4c;
    cout << "Enter the Fourth Number!" << endl;
    cin >> multi4b;
    product4 = multi4a * multi4b * multi4c * multi4d;
    cout << "The Product of the Numbers are " << product4 << "!" << endl;
    return;
}

void Calculators_Multiplication_5()
{
    int multi5a;
    int multi5b;
    int multi5c;
    int multi5d;
    int multi5e;
    int product5;
    cout << "Enter the First Number!" << endl;
    cin >> multi5a;
    cout << "Enter the Second Number!" << endl;
    cin >> multi5b;
    cout << "Enter the Third Number!" << endl;
    cin >> multi5c;
    cout << "Enter the Fourth Number!" << endl;
    cin >> multi5d;
    cout << "Enter the Fifth Number!" << endl;
    cin >> multi5e;
    product5 = multi5a * multi5b * multi5c * multi5d * multi5e;
    cout << "The Product of the Numbers are" << product5 << "!" << endl;
    return;
}

My Division.

#include <iostream>

using namespace std;

void Calculators_Division()
{
    float divisia;
    float divisiab;
    float quotient;
    cout << "Enter the Divisor" << endl;
    cin >> divisia;
    cout << "Enter the Dividend" << endl;
    cin >> divisiab;
    quotient = divisia / divisiab;
    cout << "The Quotient of the Numbers are " << quotient << endl;
    return;
}

The Problem right now is that when addition finishes , subtraction starts. After Subtraction, Multiplication. After Multiplication, Division. After That the program ends. I'm sorry. Its just that I'm new to programming (Like one month).

Body:
There are many things to improve (some of them already mentioned in comments), but exact answer to your question is:

you have semicolon after your if-statement lines in Calculators_Operation() function body, which makes if-statements useless and your "operation" functions are being called every time (what you already noticed).

you use "or" operator in incorrect way, if you use (answera == "addition" or "+"), you basically say: ((answera == "addition) or "+") and that evaluates to true (see here)

EDIT:
Your function Calculators_Operation may be changed to:

void Calculators_Operation()
{
   string answera;
   cout << "What Operation do you Want?" << endl;
   cin >> answera;

   if (answera == "Addition" || answera == "addition" || answera == "+")
   {
       Calculators_Addition();
   }
   else if (answera == "Subtraction" || answera == "subtraction" || answera == "-")
   {
       Calculators_Subtraction();
   }
   else if (answera == "Multiplication" || answera == "multiplication" || answera == "*" || answera == "x" || answera == "X")
   {
       Calculators_Multiplication();
   }
   else if (answera == "Division" || answera == "division" || answera == "/")
   {
       Calculators_Division();
   } else {
     cout << "Unknown operation entered!" << endl;
   }
}

NOTE: all your if statements need to be changed according to this function.

If anything does not work, please either put in comments what exactly does not work or edit your question with new code posting and question.


问:
Upload file to s3 with POST
I'd like to upload a file to AWS S3 via the POST interface, but I fail to do so.

I've already made it work with PUT and getSignedUrl, but unfortunately that interface doesn't allow direct file size restrictions. So I tried to use the POST interface, because there I can use 'content-length-range' condition.

Here's my request signature:

```<code>const aws = require('aws-sdk');

aws.config.update({
    signatureVersion: 'v4',
    region: 'eu-central-1',
    accessKeyId: config.aws.keyId,
    secretAccessKey: config.aws.keySecret
});

const s3 = new aws.S3();

return new Promise((resolve, reject) => {
    const params = {
        Bucket: config.aws.bucket,
        Fields: {
            key: filePath
        },
        Expires: config.aws.expire,
        Conditions: [
            ['acl', 'public-read'],
            ['content-length-range', 0, 10000000] // 10 Mb
        ]
    };
    const postUrl = s3.createPresignedPost(params, (err, data) => {
        resolve(data);
    });
});
</code>```

This part seems to be OK, but I can't use the required signature to upload a file to S3.

Here are a few other attempts I made:

```<code>request.post({
    url: payload.url,
    body: payload,
    form: fs.createReadStream(__dirname + `/${filePath}`)
}, (err, response, body) => {});
</code>```

Another attempt:

```<code>let formData = payload;
formData.file = fs.createReadStream(__dirname + `/${filePath}`);
request.post({
    url: payload.url,
    formData: formData
}, (err, response, body) => {});
</code>```

With fetch:

```<code>const fetch = require('node-fetch');
const FormData = require('form-data');

const form = new FormData();
const fields = payload.fields;
for(const field in payload.fields) {
    form.append(field, payload.fields[field]);
}
form.append('file', fs.createReadStream(__dirname + `/${filePath}`));
fetch(payload.url, {
    method: 'POST',
    body: form.toString(),
    headers: form.getHeaders()
})
.then((response) => {})
.catch((err) => {});
</code>```

Neither of these work, they either say 'Bad request', or 'Badly formed request'. One of them uploaded something to the server, but the file was unreadable.

How can I add a max file size limit to an S3 bucket?

Update:
I think I move forward just a little. With this code, I get the error response: You must provide the Content-Length HTTP header.

```<code>const fetch = require('node-fetch');
const FormData = require('form-data');

const form = new FormData();
form.append('acl', 'public-read');
for(const field in payload.fields) {
    form.append(field, payload.fields[field]);
}
form.append('file', fs.createReadStream(__dirname + `/${filePath}`));

fetch(payload.url, {
    method: 'POST',
    body: form,
    headers: form.getHeaders()
})
.then((response) => { return response.text(); })
.then((payload) => { console.log(payload); })
.catch((err) => console.log(`Error: ${err}`));
</code>```

答:
Finally it works. Here's the code in case anyone has the same problem.

A few things to note:

Request or form-data libraries have a bug, one of them doesn't set the 'Content-Length' header. See the issue https://github.com/request/request/issues/316

The order of the form fields are important, acl later, it will fail.

There are different AWS protocols out there, you should check the ones available in your zone. In my case, I had to set signatureVersion to v4 even in the S3 constructor.

I'm not proud of the code quality, but at last it works.

const aws = require('aws-sdk');
const fs = require('fs');
const request = require('request');
const config = require('./config');

let s3;

const init = () => {
    aws.config.update({
        signatureVersion: 'v4',
        region: 'eu-central-1',
        accessKeyId: config.aws.keyId,
        secretAccessKey: config.aws.keySecret
    });

    s3 = new aws.S3({signatureVersion: 'v4'});
};

const signFile = (filePath) => {
    return new Promise((resolve, reject) => {
        const params = {
            Bucket: config.aws.bucket,
            Fields: {
                key: filePath
            },
            Expires: config.aws.expire,
            Conditions: [
                ['content-length-range', 0, 10000000], // 10 Mb
                {'acl': 'public-read'}
            ]
        };
        s3.createPresignedPost(params, (err, data) => {
            resolve(data);
        });
    });
};

const sendFile = (filePath, payload) => {
    const fetch = require('node-fetch');
    const FormData = require('form-data');

    const form = new FormData();
    form.append('acl', 'public-read');
    for(const field in payload.fields) {
        form.append(field, payload.fields[field]);
    }
    form.append('file', fs.createReadStream(__dirname + `/${filePath}`));
    form.getLength((err, length) => {
        console.log(`Length: ${length}`);
        fetch(payload.url, {
            method: 'POST',
            body: form,
            headers: {
                'Content-Type': false,
                'Content-Length': length
            }
        })
        .then((response) => {
            console.log(response.ok);
            console.log(response.status);
            console.log(response.statusText);
            return response.text();
        })
        .then((payload) => {
            console.log(payload);
            console.log(form.getHeaders());
        })
        .catch((err) => console.log(`Error: ${err}`));
    });

};

init();

const file = 'test.pdf';
const filePath = `files/new/${file}`;
signFile(filePath)
.then((payload) => { sendFile(file, payload); });
```

Title: Upload file to s3 with POST

Body:
I'd like to upload a file to AWS S3 via the POST interface, but I fail to do so.

I've already made it work with PUT and getSignedUrl, but unfortunately that interface doesn't allow direct file size restrictions. So I tried to use the POST interface, because there I can use 'content-length-range' condition.

Here's my request signature:

const aws = require('aws-sdk');

aws.config.update({
    signatureVersion: 'v4',
    region: 'eu-central-1',
    accessKeyId: config.aws.keyId,
    secretAccessKey: config.aws.keySecret
});

const s3 = new aws.S3();

return new Promise((resolve, reject) => {
    const params = {
        Bucket: config.aws.bucket,
        Fields: {
            key: filePath
        },
        Expires: config.aws.expire,
        Conditions: [
            ['acl', 'public-read'],
            ['content-length-range', 0, 10000000] // 10 Mb
        ]
    };
    const postUrl = s3.createPresignedPost(params, (err, data) => {
        resolve(data);
    });
});

This part seems to be OK, but I can't use the required signature to upload a file to S3.

Here are a few other attempts I made:

request.post({
    url: payload.url,
    body: payload,
    form: fs.createReadStream(__dirname + `/${filePath}`)
}, (err, response, body) => {});

Another attempt:

let formData = payload;
formData.file = fs.createReadStream(__dirname + `/${filePath}`);
request.post({
    url: payload.url,
    formData: formData
}, (err, response, body) => {});

With fetch:

const fetch = require('node-fetch');
const FormData = require('form-data');

const form = new FormData();
const fields = payload.fields;
for(const field in payload.fields) {
    form.append(field, payload.fields[field]);
}
form.append('file', fs.createReadStream(__dirname + `/${filePath}`));
fetch(payload.url, {
    method: 'POST',
    body: form.toString(),
    headers: form.getHeaders()
})
.then((response) => {})
.catch((err) => {});

Neither of these work, they either say 'Bad request', or 'Badly formed request'. One of them uploaded something to the server, but the file was unreadable.

How can I add a max file size limit to an S3 bucket?

Update:
I think I move forward just a little. With this code, I get the error response: You must provide the Content-Length HTTP header.

const fetch = require('node-fetch');
const FormData = require('form-data');

const form = new FormData();
form.append('acl', 'public-read');
for(const field in payload.fields) {
    form.append(field, payload.fields[field]);
}
form.append('file', fs.createReadStream(__dirname + `/${filePath}`));

fetch(payload.url, {
    method: 'POST',
    body: form,
    headers: form.getHeaders()
})
.then((response) => { return response.text(); })
.then((payload) => { console.log(payload); })
.catch((err) => console.log(`Error: ${err}`));


问:
how to sum variables with NA values using withColumn
I have a data frame with 4 numeric variables, and i need to create another variable with the sum from the other 4 variables.
This function works, sure:

df4.withColumn( "sumVariables", sum(df4[x] for x in df4.columns[1:5])).show()

the problem is the sum with Null values, because the result in a row with

0|   null|      1|      0 is Null

how can i solve it?

答:
This should work :    </p>

```<code>df4.withColumn( "sumVariables", sum(df4[x] for x in df4.columns[1:5] if x != "null") ).show()
</code>```

Body:
This should work :

df4.withColumn( "sumVariables", sum(df4[x] for x in df4.columns[1:5] if x != "null") ).show()


问:
How WhatsApp implements delivery receipts for messages pushed through Push Notifications in iOS?
An user X(Has Whatsapp in Android) tries to send a message to user Y(Has Whatsapp) in iOS when the user Y is offline. The user Y receives a push notification that he has a message from user X. As soon as the push notification is received, user X is able to see the double tick mark in his WhatsApp client. How WhatsApp is able to figure out that the push notification has been successfully delivered to the iOS client ?</p>

答:
It's not really possible to know what's going on without seeing at least a protocol dump of WhatsApp as this occurs, so on with the rampant speculation:

I'd guess that WhatsApp is using Message Delivery Receipts, which rely on the client responding to the message, rather than the server. Since push notifications talk to an intermediate service (e.g., APNS), which itself wouldn't send said receipt acknowledgements, the client running on the device, upon receiving the push notification, wakes up, analyzes the message, and sends the delivery acknowledgement to the initiator of the dialog.

At least, that's how I'd do it, if I were trying to leverage existing standards, which isn't necessarily what WhatsApp is doing.


问:
Are string literals const?
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

```<code>char *foo = "bar";
</code>```

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

答: They are const char*, but there is a specific exclusion for assigning them to char* for legacy code that existed before const did. And the command line arguments are definitely not literal, they are created at run-time.</p>

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?


问:
How to override a block template created using views
On Drupal 8 I'm trying to override the template of a block created using views. So far I've a file name as block--views-block--xxx.html.twig which gives me access to the view fields.

I've to do something like content.view_build['#rows'].0['#rows'] to get the rows which is pretty awful but I couldn't find any other way. Also I've to set "Show content" on the views settings.

I can not get the pager to work at all. Reading the documentation from Drupal I can not find any clues.

答:
I think you should rather override the view template rather than the view-block template.

View templates Naming conventions can be found here and the variables you can work with are listed here. you can now put the pager, header, rows and other view elements in different sections in template.

If you need to override the contents of the view rows then you will need to take action according to how you are displaying the content in the view.

If you use a teaser view of content you can override the content teaser template like "node--content_type--teaser.html.twig", or if you use fields in view then you will have to override the fields templates of each field.


问:
How to save a ncurses window in a structure?
I have the following struct:

```<code>typedef struct gameState {
    WINDOW *game;
    character *player;
    finalPosition positions[5];
    int level, found, timeSpent[3];
} gameState;
</code>```

How can I save in the gameState.game a ncurses window?

This is how I created the window.

```<code>WINDOW * game = newwin(20, 50, 2, 2);
</code>```

I think my problem is probably a pointer problem, I'm trying to save a pointer to a struct and whenever I leave the function that created this pointer, it deletes the content of which the pointer points to.

My final objective with this is to save the whole struct into a binary file. I know ncurses have the function putwin(), which saves a window to a binary file, but I need to save the window AND the rest of the content of this struct in the same binary file, so the putwin() doesn't solve my problem.

答:
Although it is quite likely that you would be better off serialising the state of the game which produces the window rather than the window itself, there is no problem using putwin and getwin to serialise and retrieve an ncurses Window.

putwin just writes a description of the window to the given FILE. It doesn't rewind the file stream, nor does it require it to be rewound. It doesn't close the file stream, either. Similarly, getwin just reads the window description from the given FILE starting at the current read point.

So you can use putwin/getwin as part of a serialisation procedure:

```<code>int serialiseWindow(Window* game, FILE* file) {
  return putwin(game, file);
}

int serialiseGameState(gameState *state, FILE* file) {
  int status;
  status = serialiseWindow(state->game, file);
  if (status != OK) return status;
  status = serialisePositionArray(state->positions,
                                  (sizeof state->positions)/(sizeof *state->positions),
                                  file);
  if (status != OK) return status;
  status = serialiseInteger(state->level, file);
  if (status != OK) return status;
  status = serialiseInteger(state->found, file);
  if (status != OK) return status;
  status = serialiseIntegerArray(state->timeSpent,
                                 (sizeof state->timeSpent)/(sizeof *state->timeSpent),
                                 file);
  return status;
}
</code>```

And, to get it back:

```<code>int retrieveWindow(Window** game, FILE* file) {
  Window* win = getwin(file);
  *game = win;
  return win ? OK : ERR;
}

int retrieveGameState(gameState *state, FILE* file) {
  int status;
  status = retrieveWindow(&state->game, file);
  if (status != OK) return status;
  status = retrievePositionArray(state->positions,
                                 (sizeof state->positions)/(sizeof *state->positions),
                                 file);
  if (status != OK) return status;
  status = retrieveInteger(&state->level, file);
  if (status != OK) return status;
  status = retrieveInteger(&state->found, file);
  if (status != OK) return status;
  status = retrieveIntegerArray(state->timeSpent,
                                (sizeof state->timeSpent)/(sizeof *state->timeSpent),
                                file);
  return status;
}
</code>```

Body:
I have the following struct:

typedef struct gameState {
    WINDOW *game;
    character *player;
    finalPosition positions[5];
    int level, found, timeSpent[3];
} gameState;

How can I save in the gameState.game a ncurses window?

This is how I created the window.

WINDOW * game = newwin(20, 50, 2, 2);

I think my problem is probably a pointer problem, I'm trying to save a pointer to a struct and whenever I leave the function that created this pointer, it deletes the content of which the pointer points to.

My final objective with this is to save the whole struct into a binary file. I know ncurses have the function putwin(), which saves a window to a binary file, but I need to save the window AND the rest of the content of this struct in the same binary file, so the putwin() doesn't solve my problem.

Body:
Although it is quite likely that you would be better off serialising the state of the game which produces the window rather than the window itself, there is no problem using putwin and getwin to serialise and retrieve an ncurses Window.

putwin just writes a description of the window to the given FILE. It doesn't rewind the file stream, nor does it require it to be rewound. It doesn't close the file stream, either. Similarly, getwin just reads the window description from the given FILE starting at the current read point.

So you can use putwin/getwin as part of a serialisation procedure:

int serialiseWindow(Window* game, FILE* file) {
  return putwin(game, file);
}

int serialiseGameState(gameState *state, FILE* file) {
  int status;
  status = serialiseWindow(state->game, file);
  if (status != OK) return status;
  status = serialisePositionArray(state->positions,
                                  (sizeof state->positions)/(sizeof *state->positions),
                                  file);
  if (status != OK) return status;
  status = serialiseInteger(state->level, file);
  if (status != OK) return status;
  status = serialiseInteger(state->found, file);
  if (status != OK) return status;
  status = serialiseIntegerArray(state->timeSpent,
                                 (sizeof state->timeSpent)/(sizeof *state->timeSpent),
                                 file);
  return status;
}

And, to get it back:

int retrieveWindow(Window** game, FILE* file) {
  Window* win = getwin(file);
  *game = win;
  return win ? OK : ERR;
}

int retrieveGameState(gameState *state, FILE* file) {
  int status;
  status = retrieveWindow(&state->game, file);
  if (status != OK) return status;
  status = retrievePositionArray(state->positions,
                                 (sizeof state->positions)/(sizeof *state->positions),
                                 file);
  if (status != OK) return status;
  status = retrieveInteger(&state->level, file);
  if (status != OK) return status;
  status = retrieveInteger(&state->found, file);
  if (status != OK) return status;
  status = retrieveIntegerArray(state->timeSpent,
                                (sizeof state->timeSpent)/(sizeof *state->timeSpent),
                                file);
  return status;
}


问:
Fragment cannot show when call from navigationdrawer
The Fragment cannot show when call from NavigationDrawer.When I click an item in navigation drawer Fragment cannot load or show code works perfectly there is no error in the code .And also code is executed the transaction on Fragment

```<code> <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/my_toolbar"
            style="@style/MyAppTheme"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#ffffff"
            app:tabIndicatorColor="@color/black" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:layout_marginBottom="?attr/actionBarSize"
        android:layout_marginTop="105dp"
        android:layout_below="@id/appBar"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true">

    </android.support.v4.view.ViewPager>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:elevation="16dp"
        android:id="@+id/design_bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        app:behavior_hideable="true"
        app:behavior_peekHeight="50dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <fragment android:name="com.techweblearn.musicplayer.BottomPlayer"

            android:id="@+id/bottom_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</RelativeLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

activity.java

```<code> @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.library) {
        Toast.makeText(MainActivity.this,"Library",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.equalizer) {

        FragmentManager fragmentManager=getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame,new EqualizerFragment()).commit();
        Toast.makeText(MainActivity.this,"Equalizer",Toast.LENGTH_SHORT).show();
    } else if (id == R.id.sleep_timer) {
        Toast.makeText(MainActivity.this,"Sleep Timer",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.setting) {
        Toast.makeText(MainActivity.this,"Setting",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.nav_share) {
        Log.d("Navigation","1");

    } else if (id == R.id.nav_send) {
        Log.d("Navigation","1");

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}
</code>```

答:
add setTranslationZ in your code to keep content_frame at the top of the viewpager as below :</p>

```<code>else if (id == R.id.equalizer) {

View content = findViewbyId(R.id.content_frame)
ViewCompat.setTranslationZ(content , 50);
        FragmentManager fragmentManager=getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame,new EqualizerFragment()).commit();
        Toast.makeText(MainActivity.this,"Equalizer",Toast.LENGTH_SHORT).show();
</code>```

Body:
The Fragment cannot show when call from NavigationDrawer.When I click an item in navigation drawer Fragment cannot load or show code works perfectly there is no error in the code .And also code is executed the transaction on Fragment

 <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/my_toolbar"
            style="@style/MyAppTheme"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#ffffff"
            app:tabIndicatorColor="@color/black" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:layout_marginBottom="?attr/actionBarSize"
        android:layout_marginTop="105dp"
        android:layout_below="@id/appBar"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true">

    </android.support.v4.view.ViewPager>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:elevation="16dp"
        android:id="@+id/design_bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        app:behavior_hideable="true"
        app:behavior_peekHeight="50dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <fragment android:name="com.techweblearn.musicplayer.BottomPlayer"

            android:id="@+id/bottom_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

activity.java

 @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.library) {
        Toast.makeText(MainActivity.this,"Library",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.equalizer) {

        FragmentManager fragmentManager=getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame,new EqualizerFragment()).commit();
        Toast.makeText(MainActivity.this,"Equalizer",Toast.LENGTH_SHORT).show();
    } else if (id == R.id.sleep_timer) {
        Toast.makeText(MainActivity.this,"Sleep Timer",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.setting) {
        Toast.makeText(MainActivity.this,"Setting",Toast.LENGTH_SHORT).show();

    } else if (id == R.id.nav_share) {
        Log.d("Navigation","1");

    } else if (id == R.id.nav_send) {
        Log.d("Navigation","1");

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

Body:
add setTranslationZ in your code to keep content_frame at the top of the viewpager as below :

else if (id == R.id.equalizer) {

View content = findViewbyId(R.id.content_frame)
ViewCompat.setTranslationZ(content , 50);
        FragmentManager fragmentManager=getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame,new EqualizerFragment()).commit();
        Toast.makeText(MainActivity.this,"Equalizer",Toast.LENGTH_SHORT).show();


问:
Coldfusion Looping
I need to use cfloop to insert records.

There's a form a customer fills out. They add an item from a dropdown list, and then enter in a quantity in a text box. Normally, the quantity is only between 1 and 5.

I need to run a loop to insert the records one at a time with a unique Item ID for each with a quantity of 1.

For example, if they add Specific Item 5 with a quantity of 4, I need 4 records inserted into the table  with a qty of 1 each. What I really want more than the answer here is the thought process of how I'd come to that going forward without having to ask.

答:
Which flavor of SQL are you using? Rather than make a db connection and inserting once for each item, you may be able to do something like this:

```<code><<<< sanitize FORM inputs >>>>

<cfquery name="insertRecords" datasource="#APPLICATION.DSN#">
    INSERT INTO <TheTable> ( ItemID, Qty, <OtherDetails> )
    VALUES
        <cfloop from="1" to="#sanitizedFORMQuantity# index="i">
            (
                <cfqueryparam cfsqltype="cf_sql_integer" value="#sanitizedItemID#">
                , 1
                , <cfqueryparam cfsqltype="cf_sql_varchar" value="#sanitizedOtherDetails#">
            )
            <cfif index NEQ sanitizedFORMQuantity>,</cfif>
        </cfloop>
</cfquery>
</code>```

This lets you build up the query and perform a single INSERT, making just one connection to the database. Even with just 5 items, it will be much faster.

NOTES:

ALWAYS sanitize FORM inputs (and any other data coming from any
source other than you). queryparam primarily handles SQLi, but may
allow other exploits to pass through.

Check that your cfsqltypes appropriately match up with the
datatypes of the columns in your database. Know which ones work
together to prevent unneeded background data conversions.
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-p-q/cfqueryparam.html

Try to minimize the number of times you need to connect to the
database. Especially if your application and database reside on
different servers (which they should).

Title: Coldfusion Looping

Body:
Which flavor of SQL are you using? Rather than make a db connection and inserting once for each item, you may be able to do something like this:

<<<< sanitize FORM inputs >>>>

<cfquery name="insertRecords" datasource="#APPLICATION.DSN#">
    INSERT INTO <TheTable> ( ItemID, Qty, <OtherDetails> )
    VALUES
        <cfloop from="1" to="#sanitizedFORMQuantity# index="i">
            (
                <cfqueryparam cfsqltype="cf_sql_integer" value="#sanitizedItemID#">
                , 1
                , <cfqueryparam cfsqltype="cf_sql_varchar" value="#sanitizedOtherDetails#">
            )
            <cfif index NEQ sanitizedFORMQuantity>,</cfif>
        </cfloop>
</cfquery>

This lets you build up the query and perform a single INSERT, making just one connection to the database. Even with just 5 items, it will be much faster.

NOTES:

ALWAYS sanitize FORM inputs (and any other data coming from any
source other than you). queryparam primarily handles SQLi, but may
allow other exploits to pass through.

Check that your cfsqltypes appropriately match up with the
datatypes of the columns in your database. Know which ones work
together to prevent unneeded background data conversions.
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-p-q/cfqueryparam.html

Try to minimize the number of times you need to connect to the
database. Especially if your application and database reside on
different servers (which they should).


问:
UIView not showing after being brought to the front
Currently I am trying to make a circle over a camera feed. To do so I have created another UIView, set the frame/color/cornerRadius, added it to the self.view's subviews, and then brought the circle UIView to the front. For some reason it is not showing up.

I have done this before and I have coded it exactly the same as I did before but it still isn't showing.

Here is where I make the view:

```<code>//----Circle View----------
    circleView = UIView(frame: CGRect(x: 150, y: 150, width: 100, height:  100))
    circleView.layer.cornerRadius = self.circleView.frame.width/2
    circleView.layer.borderColor = UIColor.green.cgColor
    circleView.layer.zPosition = 1
    //self.circleView.isHidden = true
    self.view.addSubview(circleView)
</code>```

Here is where I bring it to the front:

```<code> if (captureSession?.canAddOutput(dataOutput))!
    {

        captureSession?.addOutput(dataOutput)
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
        self.view.layer.addSublayer(previewLayer!)
        self.view.bringSubview(toFront: circleView)
        self.view.bringSubview(toFront: captureButton)
        self.view.bringSubview(toFront: stopButton)

        previewLayer?.frame = self.view.bounds

    }
</code>```

Is there a way I can get the circleView to show?

Thanks a lot.

答:
I solved the problem. </p>

<p>To fix this I added a UIView to my storyboard and then created an IBOutlet to the view controller. After that, the view showed up. I'm thinking it was because I had existing constraints on the views in my storyboard that interupted the viewing of the circleView. That's my guess. </p>

Body:
Currently I am trying to make a circle over a camera feed. To do so I have created another UIView, set the frame/color/cornerRadius, added it to the self.view's subviews, and then brought the circle UIView to the front. For some reason it is not showing up.

I have done this before and I have coded it exactly the same as I did before but it still isn't showing.

Here is where I make the view:

//----Circle View----------
    circleView = UIView(frame: CGRect(x: 150, y: 150, width: 100, height:  100))
    circleView.layer.cornerRadius = self.circleView.frame.width/2
    circleView.layer.borderColor = UIColor.green.cgColor
    circleView.layer.zPosition = 1
    //self.circleView.isHidden = true
    self.view.addSubview(circleView)

Here is where I bring it to the front:

 if (captureSession?.canAddOutput(dataOutput))!
    {

        captureSession?.addOutput(dataOutput)
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
        self.view.layer.addSublayer(previewLayer!)
        self.view.bringSubview(toFront: circleView)
        self.view.bringSubview(toFront: captureButton)
        self.view.bringSubview(toFront: stopButton)

        previewLayer?.frame = self.view.bounds

    }

Is there a way I can get the circleView to show?

Thanks a lot.

Body:
I solved the problem.

To fix this I added a UIView to my storyboard and then created an IBOutlet to the view controller. After that, the view showed up. I'm thinking it was because I had existing constraints on the views in my storyboard that interupted the viewing of the circleView. That's my guess.


问:
am I using EPOCH time? python
As I need to transform the time format hh:mm to the count of minutes. Doing the maths would be:

hh*60+mm

I came across with the method mktime, which I thought it was to get the EPOCH time in minutes of a given datetimeobject. In this way I convert from datetimeto integer.

I wrote this in order to calculate the time of the day in minutes:

(the outputs in the boxes below)

```<code>a = datetime.now()
print type(a)

print a
b= '2017-07-05 00:00:00.0'

b = datetime.strptime(b, "%Y-%m-%d %H:%M:%S.%f")
type(b)
</code>```

out: type 'datetime.datetime'

out: type 'datetime.datetime'

As both objects are datetime I used the method mktime that I found searching for a way to transform from timestamp to integer

```<code>timestamp = int(time.mktime(a.timetuple()))-int(time.mktime(b.timetuple()))
type(timestamp)
print timestamp
print a
print b
</code>```

And the output is:

```<code>out: 62189
out: 2017-07-05 17:16:29.134026
out: 2017-07-05 00:00:00
</code>```

So the value 62189is seconds? Am I using EPOCH time?

(sorry if the question is bit fool, I am quite beginner, that's why I need help)

Thanks!

答:
I would come with a solution like:

```<code>import time
t = time.strptime("02:24", "%H:%M") # Replace "02:24" with your string parameter
nb_minutes = t.tm_hour * 60 + t.tm_min
</code>```

This transforms the time format "hh:mm" to the count of minutes as requested in your OP.

Note that there is a distrinction between a date, a datetime and a time. Python offers more flexibility than Javascript Date() on this.

Basically:

date = YYYY-MM-DD

time = HH:MM:ss

datetime = YYYY-MM-DD HH:MM:ss

Depending of your calculations, using the correct object in the python library will save you efforts all while making your source code more semantically readable.

Title: am I using EPOCH time? python

Body:
As I need to transform the time format hh:mm to the count of minutes. Doing the maths would be:

hh*60+mm

I came across with the method mktime, which I thought it was to get the EPOCH time in minutes of a given datetimeobject. In this way I convert from datetimeto integer.

I wrote this in order to calculate the time of the day in minutes:

(the outputs in the boxes below)

a = datetime.now()
print type(a)

print a
b= '2017-07-05 00:00:00.0'

b = datetime.strptime(b, "%Y-%m-%d %H:%M:%S.%f")
type(b)

out: type 'datetime.datetime'

out: type 'datetime.datetime'

As both objects are datetime I used the method mktime that I found searching for a way to transform from timestamp to integer

timestamp = int(time.mktime(a.timetuple()))-int(time.mktime(b.timetuple()))
type(timestamp)
print timestamp
print a
print b

And the output is:

out: 62189
out: 2017-07-05 17:16:29.134026
out: 2017-07-05 00:00:00

So the value 62189is seconds? Am I using EPOCH time?

(sorry if the question is bit fool, I am quite beginner, that's why I need help)

Thanks!

Body:
I would come with a solution like:

import time
t = time.strptime("02:24", "%H:%M") # Replace "02:24" with your string parameter
nb_minutes = t.tm_hour * 60 + t.tm_min

This transforms the time format "hh:mm" to the count of minutes as requested in your OP.

Note that there is a distrinction between a date, a datetime and a time. Python offers more flexibility than Javascript Date() on this.

Basically:

date = YYYY-MM-DD

time = HH:MM:ss

datetime = YYYY-MM-DD HH:MM:ss

Depending of your calculations, using the correct object in the python library will save you efforts all while making your source code more semantically readable.


问:
SWT Virtual Keyboard implementation
I'm writing an application using SWT and JFace and it will be used on a machine without a physical keyboard. Do you know if there is something already done for that purpose?
I found a project that uses Swing: https://github.com/oxus20/Java-VirtualKeyboard.

I was wondering if I have to convert it to SWT by myself or there are already projects like that for SWT.

答:
I don't know of a ready to use library that implements a virtual keyboard in SWT.

My (untested) approach would be to use Display::post() with SWT.KeyDown and SWT.KeyUp events to simulate keystrokes.

Display::post() has subtle differences on different platforms. This forum post may help to work around some of them: https://www.eclipse.org/forums/index.php/t/1072641/

Title: SWT Virtual Keyboard implementation


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
This is an interesting question!  Try it this way.</p>

```<code>Sub InsertCharacter()

Dim Rng As Range
Dim InputRng As Range, OutRng As Range
Dim xRow As Integer
Dim xChar As String
Dim index As Integer
Dim arr As Variant
Dim xValue As String
Dim outValue As String
Dim xNum As Integer

Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
xRow = Application.InputBox("Number of characters :", xTitleId, Type:=1)
xChar = Application.InputBox("Specify a character :", xTitleId, Type:=2)
Set OutRng = Application.InputBox("Out put to (select range):", xTitleId, Type:=8)
Set OutRng = OutRng.Range("A1")
xNum = 1
For Each Rng In InputRng
    xValue = Rng.Value
    outValue = ""
    For index = 1 To VBA.Len(xValue)
        If index Mod xRow = 0 And index <> VBA.Len(xValue) Then
            outValue = outValue + VBA.Mid(xValue, index, 1) + xChar
        Else
            outValue = outValue + VBA.Mid(xValue, index, 1)
        End If
    Next
    OutRng.Cells(xNum, 1).Value = outValue
    xNum = xNum + 1
Next
End Sub
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
This is an interesting question!  Try it this way.

Sub InsertCharacter()

Dim Rng As Range
Dim InputRng As Range, OutRng As Range
Dim xRow As Integer
Dim xChar As String
Dim index As Integer
Dim arr As Variant
Dim xValue As String
Dim outValue As String
Dim xNum As Integer

Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
xRow = Application.InputBox("Number of characters :", xTitleId, Type:=1)
xChar = Application.InputBox("Specify a character :", xTitleId, Type:=2)
Set OutRng = Application.InputBox("Out put to (select range):", xTitleId, Type:=8)
Set OutRng = OutRng.Range("A1")
xNum = 1
For Each Rng In InputRng
    xValue = Rng.Value
    outValue = ""
    For index = 1 To VBA.Len(xValue)
        If index Mod xRow = 0 And index <> VBA.Len(xValue) Then
            outValue = outValue + VBA.Mid(xValue, index, 1) + xChar
        Else
            outValue = outValue + VBA.Mid(xValue, index, 1)
        End If
    Next
    OutRng.Cells(xNum, 1).Value = outValue
    xNum = xNum + 1
Next
End Sub


问:
Angular navigate to url by replacing an existing parameter
In our Angular App we have a DropDown component which is populated with years.

Once we select an year, we need to change the router url, to be something like:

url/customers/2015

url/customers/2016

url/customers/2017

OR

url/customers/some-other-page/2015

url/customers/some-other-page/2016

url/customers/some-other-page/2017

This works, but we delegate the change event of the dropdown to the components that need it. That is fine!

BUT we thoughtit would make our life easier, if the component makes the route change by itself.

We tried:

```<code>  public onChange(year): void {
    this.router.([this.router.url, year]);
  }
</code>```

This works only in the first time, the second time the url looks like this:

url/customers/some-other-page/2017/2018

The third time:

url/customers/some-other-page/2017/2018/2019

and so on...

Question:

So, how do I get the parameter of my router and replace it with the current paremeter?

答:
Here is some info on using query parameters:

You can then read the query parameters using syntax like this:

```<code>ngOnInit(): void {
    this.listFilter = this.route.snapshot.queryParamMap.get('filterBy') || '';
    this.showImage = this.route.snapshot.queryParamMap.get('showImage') === 'true';
    . . .
}
</code>```

Or if you want to be notified when the query parameters change, you can do something like this:

```<code>ngOnInit(): void {
    this.route.queryParamMap.subscribe(params => this.filterBy = params.get('filterBy'));
    . . .
}
</code>```

NOTE: From the docs:

Two older properties are still available. They are less capable than
  their replacements, discouraged, and may be deprecated in a future
  Angular version.

params — An Observable that contains the required and optional
  parameters specific to the route. Use paramMap instead.

queryParams — An Observable that contains the query parameters
  available to all routes. Use queryParamMap instead.

Body:
In our Angular App we have a DropDown component which is populated with years.

Once we select an year, we need to change the router url, to be something like:

url/customers/2015

url/customers/2016

url/customers/2017

OR

url/customers/some-other-page/2015

url/customers/some-other-page/2016

url/customers/some-other-page/2017

This works, but we delegate the change event of the dropdown to the components that need it. That is fine!

BUT we thoughtit would make our life easier, if the component makes the route change by itself.

We tried:

  public onChange(year): void {
    this.router.([this.router.url, year]);
  }

This works only in the first time, the second time the url looks like this:

url/customers/some-other-page/2017/2018

The third time:

url/customers/some-other-page/2017/2018/2019

and so on...

Question:

So, how do I get the parameter of my router and replace it with the current paremeter?

Body:
Here is some info on using query parameters:

You can then read the query parameters using syntax like this:

ngOnInit(): void {
    this.listFilter = this.route.snapshot.queryParamMap.get('filterBy') || '';
    this.showImage = this.route.snapshot.queryParamMap.get('showImage') === 'true';
    . . .
}

Or if you want to be notified when the query parameters change, you can do something like this:

ngOnInit(): void {
    this.route.queryParamMap.subscribe(params => this.filterBy = params.get('filterBy'));
    . . .
}

NOTE: From the docs:

Two older properties are still available. They are less capable than
  their replacements, discouraged, and may be deprecated in a future
  Angular version.

params — An Observable that contains the required and optional
  parameters specific to the route. Use paramMap instead.

queryParams — An Observable that contains the query parameters
  available to all routes. Use queryParamMap instead.


问:
Python Issue Making a Game
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

```<code>from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()
</code>```

for me i think everything i written as it should be but when i run my script i get an error :

```Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined```

couldn't figure out
Help me Please and thank you

答: You can actually rename your starting function into "start", because you are calling the start func</p>

Title: Python Issue Making a Game

Body:
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()

for me i think everything i written as it should be but when i run my script i get an error :

Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined

couldn't figure out
Help me Please and thank you


问:
How to delete only few rows if several rows are duplicated in SQL?
How to delete only few rows (more than 1) if several rows are duplicated? When I try to put condition all rows are getting deleted. I'm using SQL server 2008.</p>

答:
Use below query

```<code>-- Check : This query will give you unique records
SELECT MAX(ID)
FROM MyTable
GROUP BY Column1, Column2, Column3 ......

-- Now delete the record apart from unique record
DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY Column1, Column2, Column3 ......)
</code>```

Note : ID is primary key here. if ID does not exist in your table then first create the ID with AUTO_INCREMENT value then run the above query.

Example :

MyTable

```<code>col1  col2 col3 col4 col5 col6 col7
john  1    1    1    1    1    1
john  1    1    1    1    1    1
john  1    1    1    1    1    1
sally 2    2    2    2    2    2
sally 2    2    2    2    2    2
</code>```

if ID does not exist add ID with auto increment value. After adding ID

```<code>ID  col1  col2 col3 col4 col5 col6 col7
1   john  1    1    1    1    1    1
2   john  1    1    1    1    1    1
3   john  1    1    1    1    1    1
4   sally 2    2    2    2    2    2
5   sally 2    2    2    2    2    2
</code>```

-- Check : This query will give you unique records

```<code>SELECT MAX(ID) FROM MyTable
GROUP BY col1, col2, col3, col4, col5, col6, col7
</code>```

Query output
    Max(ID)

    3

    5

-- Now delete the record apart from unique record

```<code>DELETE
FROM MyTable
    WHERE ID NOT IN
    (
     SELECT MAX(ID) FROM MyTable
     GROUP BY col1, col2, col3, col4, col5, col6, col7)
</code>```

Body:
Use below query

-- Check : This query will give you unique records
SELECT MAX(ID)
FROM MyTable
GROUP BY Column1, Column2, Column3 ......

-- Now delete the record apart from unique record
DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY Column1, Column2, Column3 ......)

Note : ID is primary key here. if ID does not exist in your table then first create the ID with AUTO_INCREMENT value then run the above query.

Example :

MyTable

col1  col2 col3 col4 col5 col6 col7
john  1    1    1    1    1    1
john  1    1    1    1    1    1
john  1    1    1    1    1    1
sally 2    2    2    2    2    2
sally 2    2    2    2    2    2

if ID does not exist add ID with auto increment value. After adding ID

ID  col1  col2 col3 col4 col5 col6 col7
1   john  1    1    1    1    1    1
2   john  1    1    1    1    1    1
3   john  1    1    1    1    1    1
4   sally 2    2    2    2    2    2
5   sally 2    2    2    2    2    2

-- Check : This query will give you unique records

SELECT MAX(ID) FROM MyTable
GROUP BY col1, col2, col3, col4, col5, col6, col7

Query output
    Max(ID)

    3

    5

-- Now delete the record apart from unique record

DELETE
FROM MyTable
    WHERE ID NOT IN
    (
     SELECT MAX(ID) FROM MyTable
     GROUP BY col1, col2, col3, col4, col5, col6, col7)