问:
Suppress HTML name of a character (like quotes or &) in ColdFusion form
I have a ColdFusion form that I need to scrub some offending code from and still keep some basic punctuation.

In my development I've set up a function with ReReplaceNoCase() and a pile of RegEx to clean just about everything and leave me with 3 different variables. one is used to rename a photo, the other ecomes the alt ad title and the third becomes the headline for the product in an
 tag

But I've encountered a strange problem. In my input I get the HTML name for some things like " for double quotes but not for single quotes.

For example, when I have a string like ""Great" leather harnesses & More!" I get back 3 strings useable for my project:

_Great_leather_harnesses_and_more_ - which concats with .jpg to become the file name

Great leather harnesses and more - which become alt and title attributes

and Great leather harnesses and more! - becomes my

The trouble is my form submits " for the double quotes and & for the & but ! for the exclamation point.

What can I do to force my form to post ONLY the character to my function so I don't have to go through every character with an HTML name and zap it? By the way, I'm getting the same results with either <input type="text"... and <textarea>.

Here's my scrubing bubles of RegEx:

```<code><cfset string = #form.product_name#>
    <cfset replaceQuotes = ReReplaceNoCase(string, "(&quo;)", "", "all")>
    <cfset replaceAnd = ReReplaceNoCase(replaceQuotes, "(&)|(&)|(amp;)", " and ", "all")>
    <cfset replacePercent = ReReplaceNoCase(replaceAnd, "\%", " Percent ", "all")>
    <cfset scrubName = ReReplaceNoCase(replacePercent, "[^a-zA-Z0-9]", "_", "all")>
    <cfset cleanFileName = ReReplaceNoCase(scrubName, "[_]{2,}", "_", "all")>
    <cfset cleanAlt = ReReplaceNoCase(scrubName, "[_]", " ", "all")>
    <cfset headlinetoClean = ReReplaceNoCase(replacePercent, "[^a-zA-Z0-9.,!'\-\+]", " ", "all")>
    <cfset cleanHeadline = ReReplaceNoCase(headlinetoClean, "[\s]{2,}", " ", "all")>
</code>```

If it matters I'm declaring <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> in the head of the page...

Edit - Added form and validation code -

And my form:

```<code><cfform name="newProduct" id="newProduct" >
<label for="product_name">Product Name: </label><cfinput name="product_name" id="product_name" style="width:300px;"/>
<cfinput name="submit" id="submit" type="submit" value="Create Page" />
</cfform>
</code>```

Some validation - I suspect this may be the issue? :

```<code><cfif not len(trim(form.product_name))>
    <cfset arrayAppend( errors, "You forgot to name the product")>
<cfelse>
    <cfset form.product_name = htmlEditFormat(trim(form.product_name))>
</cfif>
</code>```

I'm pretty fresh at this RegEx so I'm sure there's a smarter way to go about this. But, this mechanism does seem to work, mostly.

答: Your suspicion is correct, HTMLEditFormat() is the problem - http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7847.html - it escapes <>&".

Body:
I have a ColdFusion form that I need to scrub some offending code from and still keep some basic punctuation.

In my development I've set up a function with ReReplaceNoCase() and a pile of RegEx to clean just about everything and leave me with 3 different variables. one is used to rename a photo, the other ecomes the alt ad title and the third becomes the headline for the product in an
 tag

But I've encountered a strange problem. In my input I get the HTML name for some things like " for double quotes but not for single quotes.

For example, when I have a string like ""Great" leather harnesses & More!" I get back 3 strings useable for my project:

_Great_leather_harnesses_and_more_ - which concats with .jpg to become the file name

Great leather harnesses and more - which become alt and title attributes

and Great leather harnesses and more! - becomes my

The trouble is my form submits " for the double quotes and & for the & but ! for the exclamation point.

What can I do to force my form to post ONLY the character to my function so I don't have to go through every character with an HTML name and zap it? By the way, I'm getting the same results with either <input type="text"... and <textarea>.

Here's my scrubing bubles of RegEx:

<cfset string = #form.product_name#>
    <cfset replaceQuotes = ReReplaceNoCase(string, "(&quo;)", "", "all")>
    <cfset replaceAnd = ReReplaceNoCase(replaceQuotes, "(&)|(&)|(amp;)", " and ", "all")>
    <cfset replacePercent = ReReplaceNoCase(replaceAnd, "\%", " Percent ", "all")>
    <cfset scrubName = ReReplaceNoCase(replacePercent, "[^a-zA-Z0-9]", "_", "all")>
    <cfset cleanFileName = ReReplaceNoCase(scrubName, "[_]{2,}", "_", "all")>
    <cfset cleanAlt = ReReplaceNoCase(scrubName, "[_]", " ", "all")>
    <cfset headlinetoClean = ReReplaceNoCase(replacePercent, "[^a-zA-Z0-9.,!'\-\+]", " ", "all")>
    <cfset cleanHeadline = ReReplaceNoCase(headlinetoClean, "[\s]{2,}", " ", "all")>

If it matters I'm declaring <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> in the head of the page...

Edit - Added form and validation code -

And my form:

<cfform name="newProduct" id="newProduct" >
Product Name: <cfinput name="product_name" id="product_name" style="width:300px;"/>
<cfinput name="submit" id="submit" type="submit" value="Create Page" />
</cfform>

Some validation - I suspect this may be the issue? :

<cfif not len(trim(form.product_name))>
    <cfset arrayAppend( errors, "You forgot to name the product")>
<cfelse>
    <cfset form.product_name = htmlEditFormat(trim(form.product_name))>
</cfif>

I'm pretty fresh at this RegEx so I'm sure there's a smarter way to go about this. But, this mechanism does seem to work, mostly.


来源: stackexchange

问:
Where does local variables actually allocated within CLR?
I'm just going inside the CLR and IL and I'm confused by this thing.

I have the following C# code:

```<code>int x = 1;
object obj = x;
int y = (int)obj;
</code>```

And IL disassemble for this

```<code>      // Code size       18 (0x12)
  .maxstack  1
  .locals init ([0] int32 x,
           [1] object obj,
           [2] int32 y)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  box        [mscorlib]System.Int32
  IL_0009:  stloc.1
  IL_000a:  ldloc.1
  IL_000b:  unbox.any  [mscorlib]System.Int32
  IL_0010:  stloc.2
  IL_0011:  ret
</code>```

So, the ldloc.0 instruction "Loads the local variable at index 0 onto stack.". But where does the locals really stored and where does they loaded from. Because I thought that there are two places where the memory can be allocated: thread stack and heap. And variables should be stored in the stack.

Now, I suppose, that the stack is just an "evaluation stack", while the memory allocation for variables is an implementation detail and depend on platform and JIT compiler. And we actually can split the memory used by our programm on evaluation stack, managed heap, and locals allocated memory.

Is this true? Or there are some other mechanism here?

答:
And IL disassemble for this

That's unoptimised code, typically produced by debug builds. Optimised code, typically produced by release builds would more likely be something like:

```<code>        // Code size 10 (0xD)
.maxstack 1
IL_0000:  ldc.i4.1
IL_0001:  box         [mscorlib]System.Int32
IL_0006:  unbox.any   [mscorlib]System.Int32
IL_000B:  pop
IL_000C:  ret
</code>```

The two most obvious differences between your version and mine are:

Mine doesn't have the nop instruction. That "do nothing" instruction serves no purpose in the running code, but it does give a point to hang a breakpoint on in the IL if you put a breakpoint on the opening { of the C# you compiled from.

Yours does some busy-work storing and loading copies of variables that mine doesn't bother with.

(This isn't the most optimal version possible, incidentally).

It's important to consider that not only does the treatment of C# locals to IL locals vary according to types of build, but that the same thing also applies to the jitting stage.

There are even bigger differences when it comes to something like:

```<code>public static void Stuff()
{
    int x = 2;
    Func<int> f = () => x * 2;
}
</code>```

Here x and f are both locals in the C#, but in the IL there's actually a heap object with a field and a method.

Local mean different things depending on the context, both as an adjective and a noun.

In C# local means method arguments and local variables within methods, both as a noun and an adjective. They are generally allocated on "the stack" (though in the case of reference types that stack allocated variable is referring to a heap-allocated object) for several meanings of "the stack" (we'll come to that later) but not always (captured locals and locals within yielding or awaiting methods that are maintained between calls [and sometimes when they aren't] are two examples). Most of the time we don't need to think too much about this fact, but the few times when we do can tend to lead to an overemphasis on the concept in how we talk about it.

In IL local as a noun refers to a set of strongly-typed locations initialised at the start of the method. As an adjective it refers to both those locals and to the locations on the stack that we push to and pop from (in IL we do need to think about the stack, a lot). These are both local locations, in so much as they can be thought of as "near by" but only one of them is generally referred to as locals when we're talking CIL. (If we were talking theory more generally we might call all of them locals, or not, depending on the point of view we were talking theory from).

But where does the locals really stored and where does they loaded from.

It depends on what you really mean by "really". But consider what the reason we use stacks for is anyway; it's a handy (but not the only) way to implement methods calling methods. You put some values on the stack, along with information about where you are now, and move into that method. Then when it is done it you have any return value on the stack and can do the next thing.

And the IL locals are a chunk of space after the arguments and before the chunk of stack you are working with, just as is reflected by the way the IL is laid out; arguments, locals, pushing and popping.

And that's sort of how things work in the actual machine too, as we can most easily seen when it doesn't work:

```<code>public static void Overflow()
{
    Overflow();
    Overflow();
}
</code>```

Call that and we get a StackOverflowException (I have it call itself twice because then tail-call optimisation can't turn that exception into just never returning, which is just about possible). Which means an actual real chunk of memory being used as a stack got all used up.

And it won't be surprising that the actual stack and the IL stack have a definite relationship and so the method arguments, locals (in the IL noun sense) and the values pushed and popped can all relate to values stored in that chunk of memory.

But they can also be implemented as registers in the CPU, so a local might never be in memory at all.

And they might also not even be there. Consider my release-build version of your code. Actually, let's make it a full C# method:

```<code>public static void DoStuff()
{
    int x = 1;
    object obj = x;
    int y = (int)obj;
}
</code>```

Now let's have something call it:

```<code>public static void CallDoStuff()
{
    DoStuff();
}
</code>```

So the compiler has turned DoStuff() into the code at the top of this answer, along with turning CallDoStuff() into:

```<code>call DoStuff
ret
</code>```

We run our application and come to where CallDoStuff() is first called, so the jitter has to compile it. It very likely sees that DoStuff() is very small and (along with a few other factors weighing on this decision) doesn't produce a function call at all but inlines all of those instructions into the code it's producing for CallDoStuff. Then it may see that the unboxed int (y) isn't used so it can leave that out, which means it can leave boxing the int out, which means it can leave producing the int out, which means we don't need any actual code for x, obj and y at all.

In which case the answer at that level as to where the values "really" are, is "nowhere".

ContentLicense: CC BY-SA 3.0

Body:
I'm just going inside the CLR and IL and I'm confused by this thing.

I have the following C# code:

int x = 1;
object obj = x;
int y = (int)obj;

And IL disassemble for this

      // Code size       18 (0x12)
  .maxstack  1
  .locals init ([0] int32 x,
           [1] object obj,
           [2] int32 y)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  box        [mscorlib]System.Int32
  IL_0009:  stloc.1
  IL_000a:  ldloc.1
  IL_000b:  unbox.any  [mscorlib]System.Int32
  IL_0010:  stloc.2
  IL_0011:  ret

So, the ldloc.0 instruction "Loads the local variable at index 0 onto stack.". But where does the locals really stored and where does they loaded from. Because I thought that there are two places where the memory can be allocated: thread stack and heap. And variables should be stored in the stack.

Now, I suppose, that the stack is just an "evaluation stack", while the memory allocation for variables is an implementation detail and depend on platform and JIT compiler. And we actually can split the memory used by our programm on evaluation stack, managed heap, and locals allocated memory.

Is this true? Or there are some other mechanism here?

Body:
And IL disassemble for this

That's unoptimised code, typically produced by debug builds. Optimised code, typically produced by release builds would more likely be something like:

        // Code size 10 (0xD)
.maxstack 1
IL_0000:  ldc.i4.1
IL_0001:  box         [mscorlib]System.Int32
IL_0006:  unbox.any   [mscorlib]System.Int32
IL_000B:  pop
IL_000C:  ret

The two most obvious differences between your version and mine are:

Mine doesn't have the nop instruction. That "do nothing" instruction serves no purpose in the running code, but it does give a point to hang a breakpoint on in the IL if you put a breakpoint on the opening { of the C# you compiled from.

Yours does some busy-work storing and loading copies of variables that mine doesn't bother with.

(This isn't the most optimal version possible, incidentally).

It's important to consider that not only does the treatment of C# locals to IL locals vary according to types of build, but that the same thing also applies to the jitting stage.

There are even bigger differences when it comes to something like:

public static void Stuff()
{
    int x = 2;
    Func<int> f = () => x * 2;
}

Here x and f are both locals in the C#, but in the IL there's actually a heap object with a field and a method.

Local mean different things depending on the context, both as an adjective and a noun.

In C# local means method arguments and local variables within methods, both as a noun and an adjective. They are generally allocated on "the stack" (though in the case of reference types that stack allocated variable is referring to a heap-allocated object) for several meanings of "the stack" (we'll come to that later) but not always (captured locals and locals within yielding or awaiting methods that are maintained between calls [and sometimes when they aren't] are two examples). Most of the time we don't need to think too much about this fact, but the few times when we do can tend to lead to an overemphasis on the concept in how we talk about it.

In IL local as a noun refers to a set of strongly-typed locations initialised at the start of the method. As an adjective it refers to both those locals and to the locations on the stack that we push to and pop from (in IL we do need to think about the stack, a lot). These are both local locations, in so much as they can be thought of as "near by" but only one of them is generally referred to as locals when we're talking CIL. (If we were talking theory more generally we might call all of them locals, or not, depending on the point of view we were talking theory from).

But where does the locals really stored and where does they loaded from.

It depends on what you really mean by "really". But consider what the reason we use stacks for is anyway; it's a handy (but not the only) way to implement methods calling methods. You put some values on the stack, along with information about where you are now, and move into that method. Then when it is done it you have any return value on the stack and can do the next thing.

And the IL locals are a chunk of space after the arguments and before the chunk of stack you are working with, just as is reflected by the way the IL is laid out; arguments, locals, pushing and popping.

And that's sort of how things work in the actual machine too, as we can most easily seen when it doesn't work:

public static void Overflow()
{
    Overflow();
    Overflow();
}

Call that and we get a StackOverflowException (I have it call itself twice because then tail-call optimisation can't turn that exception into just never returning, which is just about possible). Which means an actual real chunk of memory being used as a stack got all used up.

And it won't be surprising that the actual stack and the IL stack have a definite relationship and so the method arguments, locals (in the IL noun sense) and the values pushed and popped can all relate to values stored in that chunk of memory.

But they can also be implemented as registers in the CPU, so a local might never be in memory at all.

And they might also not even be there. Consider my release-build version of your code. Actually, let's make it a full C# method:

public static void DoStuff()
{
    int x = 1;
    object obj = x;
    int y = (int)obj;
}

Now let's have something call it:

public static void CallDoStuff()
{
    DoStuff();
}

So the compiler has turned DoStuff() into the code at the top of this answer, along with turning CallDoStuff() into:

call DoStuff
ret

We run our application and come to where CallDoStuff() is first called, so the jitter has to compile it. It very likely sees that DoStuff() is very small and (along with a few other factors weighing on this decision) doesn't produce a function call at all but inlines all of those instructions into the code it's producing for CallDoStuff. Then it may see that the unboxed int (y) isn't used so it can leave that out, which means it can leave boxing the int out, which means it can leave producing the int out, which means we don't need any actual code for x, obj and y at all.

In which case the answer at that level as to where the values "really" are, is "nowhere".


问:
Stored procedure calculating tax rate
I was learning stored procedure using some example.

Create a table Employee with the columns social security no. (primary key), name, position, no. of dependents, annual salary.

Write and execute a T-SQL stored procedure Compute_Tax to do the following:

Create a new table Tax with columns social security no., income tax

Fill the table Tax with data by computing the income tax for each person in the Employee table

The income tax is computed from the annual salary S and the number of dependents D.

```<code>Net Salary:  S - (7000 + D*950)
Tax Computed as follows:
10% of the first 15,000 of net salary;
plus 15% of the next 15,000 of net salary;
plus 28% of any net salary over 30,000.

    CREATE DEFINER=`root`@`localhost` PROCEDURE `computeTax`()
BEGIN
    DECLARE ssn NCHAR(20);
    DECLARE noOfDependent INT;
    DECLARE annualSalary DOUBLE;
    DECLARE netSalary DOUBLE;
    DECLARE tax DOUBLE;

    DECLARE empCur CURSOR FOR
        SELECT socialSecurityNumber, noOfDependents, annualSalary FROM `dbTest`.Employee;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN empCur;
    FETCH empCur
        INTO ssn, noOfDependent, annualSalary;

     CREATE TABLE IF NOT EXISTS TAX
        (ssn VARCHAR(20),
        incomeTax DOUBLE
        );

        myLoop: LOOP

            SET netSalary = annualSalary - (7000 + noOfDependent * 950);

            IF (netSalary < 0 ) THEN
                LEAVE myLoop;
             END IF;

            IF (netSalary < 15000) THEN
                SET tax = 0.1 * netSalary;

            ELSE IF (netSalary > 15000) THEN

                    IF (netSalary > 30000) THEN

                        SET tax = 0.10 * 15000 + 0.15 * 15000 + 0.28 * (netSalary - 30000);
                    ELSE

                    SET tax = 0.10 * 15000 + 0.15 * (netSalary -15000);

                  END IF;
           END IF;
      END LOOP myLoop;
      INSERT INTO TAX(ssn, incomeTax) VALUES(ssn, tax);

    FETCH empCur
        INTO ssn, noOfDependent, annualSalary;
    CLOSE empCur;
  END;
</code>```

I am getting some syntax error on the last END and END Loop myLoop above code.

答:
I see at least two problems:

You use SET done = true but you don't DECLARE a variable called done.

You start a nested IF / THEN / END IF statement inside your ELSE block, but you have only one END IF.

Note that ELSE IF is different from ELSIF in the stored procedure language. The former starts a new IF statement nested within the ELSE block of the outer statement. The latter continues the existing IF/THEN/END IF statement.

You need to structure it like one of the following:

```<code>IF ... THEN
  <code>
ELSE
  <code>
  IF ... THEN
    <code>
  END IF;
  <code>
END IF;
</code>```

Or alternatively:

```<code>IF ... THEN
  <code>
ELSIF ... THEN
  <code>
END IF;
</code>```

For what it's worth, I don't use MySQL stored procedures. They're terribly inefficient in most cases, and they don't support packages, or a debugger, or many other good features of stored procedures in other RDBMS products like Oracle or Microsoft SQL Server.

I don't recommend using stored procedures in MySQL just because you're accustomed to using them in other database platforms. It's much easier to develop in a scripting language like Ruby or Python.

Title: Stored procedure calculating tax rate

Body:
I was learning stored procedure using some example.

Create a table Employee with the columns social security no. (primary key), name, position, no. of dependents, annual salary.

Write and execute a T-SQL stored procedure Compute_Tax to do the following:

Create a new table Tax with columns social security no., income tax

Fill the table Tax with data by computing the income tax for each person in the Employee table

The income tax is computed from the annual salary S and the number of dependents D.

Net Salary:  S - (7000 + D*950)
Tax Computed as follows:
10% of the first 15,000 of net salary;
plus 15% of the next 15,000 of net salary;
plus 28% of any net salary over 30,000.

    CREATE DEFINER=`root`@`localhost` PROCEDURE `computeTax`()
BEGIN
    DECLARE ssn NCHAR(20);
    DECLARE noOfDependent INT;
    DECLARE annualSalary DOUBLE;
    DECLARE netSalary DOUBLE;
    DECLARE tax DOUBLE;

    DECLARE empCur CURSOR FOR
        SELECT socialSecurityNumber, noOfDependents, annualSalary FROM `dbTest`.Employee;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN empCur;
    FETCH empCur
        INTO ssn, noOfDependent, annualSalary;

     CREATE TABLE IF NOT EXISTS TAX
        (ssn VARCHAR(20),
        incomeTax DOUBLE
        );

        myLoop: LOOP

            SET netSalary = annualSalary - (7000 + noOfDependent * 950);

            IF (netSalary < 0 ) THEN
                LEAVE myLoop;
             END IF;

            IF (netSalary < 15000) THEN
                SET tax = 0.1 * netSalary;

            ELSE IF (netSalary > 15000) THEN

                    IF (netSalary > 30000) THEN

                        SET tax = 0.10 * 15000 + 0.15 * 15000 + 0.28 * (netSalary - 30000);
                    ELSE

                    SET tax = 0.10 * 15000 + 0.15 * (netSalary -15000);

                  END IF;
           END IF;
      END LOOP myLoop;
      INSERT INTO TAX(ssn, incomeTax) VALUES(ssn, tax);

    FETCH empCur
        INTO ssn, noOfDependent, annualSalary;
    CLOSE empCur;
  END;

I am getting some syntax error on the last END and END Loop myLoop above code.

Body:
I see at least two problems:

You use SET done = true but you don't DECLARE a variable called done.

You start a nested IF / THEN / END IF statement inside your ELSE block, but you have only one END IF.

Note that ELSE IF is different from ELSIF in the stored procedure language. The former starts a new IF statement nested within the ELSE block of the outer statement. The latter continues the existing IF/THEN/END IF statement.

You need to structure it like one of the following:

IF ... THEN
  <code>
ELSE
  <code>
  IF ... THEN
    <code>
  END IF;
  <code>
END IF;

Or alternatively:

IF ... THEN
  <code>
ELSIF ... THEN
  <code>
END IF;

For what it's worth, I don't use MySQL stored procedures. They're terribly inefficient in most cases, and they don't support packages, or a debugger, or many other good features of stored procedures in other RDBMS products like Oracle or Microsoft SQL Server.

I don't recommend using stored procedures in MySQL just because you're accustomed to using them in other database platforms. It's much easier to develop in a scripting language like Ruby or Python.


问:
Python 3 regex to split list of items?
I'm reading in some data in the form a list of items, space separated. Each item has a name, which may be one or more words, and a quantity which can either be a single integer or a fraction of integers.

Ex.

```<code>'12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'
</code>```

I want this split into the following list:

```<code>['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']
</code>```

Here is my Python regex:

```<code>import re
re.findall(r'\d+(/\d+)?\D+', "12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank")
</code>```

This produces the following result, which is obviously not right:

```<code>['', '/5', '', '/18']
</code>```

What is the proper regex here?

Title: Python 3 regex to split list of items?

Body:
I'm reading in some data in the form a list of items, space separated. Each item has a name, which may be one or more words, and a quantity which can either be a single integer or a fraction of integers.

Ex.

'12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'

I want this split into the following list:

['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']

Here is my Python regex:

import re
re.findall(r'\d+(/\d+)?\D+', "12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank")

This produces the following result, which is obviously not right:

['', '/5', '', '/18']

What is the proper regex here?

Body:
So here is what i came up with:

/(?:\d+\/\d+|\d+)\s(?:[[:word:]]+\s*){1,2}(?=\d|$)/g

demo on regex101.com


问:
Force user to log in when making an in app purchase on iphone
There are many reports of children being able to make in app purchases due to the fact that there is a 15 minute window of opportunity after logging into itunes where a user does not have to log into itunes again.  For instance, a parent downloads an application and then hands the phone to their child.  The child then has 15minutes to make in-app-purchases without having to enter a password.  And yes, I know there are parental control settings that can be set so that no in-app-purchases can be made.  But lets face it, most people are not involved enough to know about this.(Lets please not argue about how parents should be more involved, we all know they should be)  The real questions is:

Is there a way to force the iTunes login?  Or force a log out before running any in app purchase commands?

答: No. The API to the Store Kit works at a higher level than tracking authentication. You have no programmatic control over it, sorry.</p>

ContentLicense: CC BY-SA 2.5


问:
How to generate files in a docker container for having the same owner as the host's user
I use docker containers to get some development tasks done in my git repositories.

The containers I use are built specifically for each project, that way each contributor only need docker CLI to get things done.

The bad side is the container run as root, thus generated files are owned by root once the container stops, and that's bad..

I can't change the owner in the container before exiting because there isn't the required user in the container /etc/passwd file.

I would create a user in the container before compiling the docker image but then the container won't be universal (for all my dev team).

What is the best practice(s) about that ?

答:
A solution is to create a new dockerfile in the repository which is based on the former image (pre-installed with devtools but with no user created but root).

In a such dockerfile, write something like the following:

```<code>FROM <ABSTRACT_FORMER_IMAGE>
ARG username=developer
RUN useradd -r -u 1001 -g $username $username
USER $username
</code>```

Then, before starting to work, each developer in the team should use the dockerfile to build its own base image for new project+developer specific containers, passing its username.

```<code>$ docker build --build-arg username=$USER Dockerfile
</code>```

Some better practices out there ?

Body:
A solution is to create a new dockerfile in the repository which is based on the former image (pre-installed with devtools but with no user created but root).

In a such dockerfile, write something like the following:

FROM <ABSTRACT_FORMER_IMAGE>
ARG username=developer
RUN useradd -r -u 1001 -g $username $username
USER $username

Then, before starting to work, each developer in the team should use the dockerfile to build its own base image for new project+developer specific containers, passing its username.

$ docker build --build-arg username=$USER Dockerfile

Some better practices out there ?


问:
I am trying to print but not being able to figure out the right command
```<code>struct Name {                                  // structure
  char firstName[31];
};

int main(void) {
  struct Name name;                            // structure type variable
  void getName(struct Name *name);
  printf("First name: %s\n", name->firstName); //printing error occurring
}

void getName(struct Name *name) {               //function definition
  printf("Please enter the contact’s first name: ");
  scanf("%s", name->firstName);                //taking the input from user
}
</code>```

In my code I am trying to create a contact management system. I have structure a function and a main function. What I am doing is I have a structure, I am passing that structure to a function. The function gets an input for the structure member and stores it. But there's something wrong with my syntax while calling the getName() function and while printing the structure member input that I took from the user.

答:
The error is in the way you are accessing member of the object. It should be accessed like:
name.firstName instead of with -> operator. This is because you have an object and not a reference (pointer) to an object.

So the correct prints call is:

```<code>printf(“First Name: %s\n”, name.firstName);
</code>```

Body:
struct Name {                                  // structure
  char firstName[31];
};

int main(void) {
  struct Name name;                            // structure type variable
  void getName(struct Name *name);
  printf("First name: %s\n", name->firstName); //printing error occurring
}

void getName(struct Name *name) {               //function definition
  printf("Please enter the contact’s first name: ");
  scanf("%s", name->firstName);                //taking the input from user
}

In my code I am trying to create a contact management system. I have structure a function and a main function. What I am doing is I have a structure, I am passing that structure to a function. The function gets an input for the structure member and stores it. But there's something wrong with my syntax while calling the getName() function and while printing the structure member input that I took from the user.

Body:
The error is in the way you are accessing member of the object. It should be accessed like:
name.firstName instead of with -> operator. This is because you have an object and not a reference (pointer) to an object.

So the correct prints call is:

printf(“First Name: %s\n”, name.firstName);


问:
Difference between HTTP redirect codes
The differences between the various HTTP 3XX redirect codes are not clear to me.  Yes, I've read the spec, but there seems to be some discrepancy between the standard and actual practice here.

The 301 redirect code seems clear enough: This means the resource was permanently moved to another URI, and future requests should use that URI.

And the 307 redirect code also seems clear: it means the redirect is temporary, and future requests should still use the original URI.

But I can't tell what the difference is between 302 and 303, or why either of them are really different from 301.  It seems that 302 was originally intended to be a temporary redirect, (like 307), but in practice, most browsers treated it like a 303.  But what's the difference between a 303 and a 301?  Is 301 supposed to mean the redirect is more permanent?

答:
301: Permanent redirect.  Clients making subsequent requests for this resource should use the new URI.  Clients should not follow the redirect automatically for POST/PUT/DELETE requests.

302: Redirect for undefined reason.  Clients making subsequent requests for this resource should not use the new URI.  Clients should not follow the redirect automatically for POST/PUT/DELETE requests.

303: Redirect for undefined reason.  Typically, 'Operation has completed, continue elsewhere.'  Clients making subsequent requests for this resource should not use the new URI.  Clients should follow the redirect for POST/PUT/DELETE requests, but use GET for the follow-up request.

307: Temporary redirect.  Resource may return to this location at a later point.  Clients making subsequent requests for this resource should use the old URI.  Clients should not follow the redirect automatically for POST/PUT/DELETE requests.

I personally recommend avoiding 302 if you have the choice.  Many clients do not follow the spec when they encounter a 302.  For temporary redirects, you should use either 303 or 307, depending on what type of behavior you want on non-GET requests.  Prefer 307 to 303 unless you need the alternate behavior on POST/PUT/DELETE.

Title: Difference between HTTP redirect codes


问:
How can I fade in text with toggle when clicking on an image?
I would like to fade in and out text when clicking on an image. I'm pretty new to JS, so thank you for answering my question!

Here's my jsfiddle: http://jsfiddle.net/gSVfV/

Here's what I have for JS:

```<code>$(function() {
    $('.block img.info').click(function(e) {
        e.preventDefault();
        $('.caption-background').toggleClass('hidden');
    });
});
</code>```

For HTML:

```<code><div class="block">
<img class="info"/>
<div class="caption-background">
    Hello
</div>
</code>```

And for css:

```<code> .info {
    width: 200px;
    height: 100px;
    background-image:
url("http://ocean.nationalgeographic.com/u/TvyamNb-
BivtNwpvn7Sct0VFDulyAfA9wBcU0gVHVnqC5ghqXjggeitqtJ-
1ZIZ1rmCgor42TXOteIQU/");
}
.caption-background {
    height: 200px;
}
.hidden {
    display: none;
}
</code>```

答:
You can use the jQuery fadeToggle method.

Update your javascript with the following:

```<code>$(function() {
    $('.rsABlock img.info').click(function(e) {
        e.preventDefault();
        $('.caption-background').fadeToggle();
    });
});
</code>```

Check out http://api.jquery.com/fadetoggle/

Body:
I would like to fade in and out text when clicking on an image. I'm pretty new to JS, so thank you for answering my question!

Here's my jsfiddle: http://jsfiddle.net/gSVfV/

Here's what I have for JS:

$(function() {
    $('.block img.info').click(function(e) {
        e.preventDefault();
        $('.caption-background').toggleClass('hidden');
    });
});

For HTML:

    Hello

And for css:

 .info {
    width: 200px;
    height: 100px;
    background-image:
url("http://ocean.nationalgeographic.com/u/TvyamNb-
BivtNwpvn7Sct0VFDulyAfA9wBcU0gVHVnqC5ghqXjggeitqtJ-
1ZIZ1rmCgor42TXOteIQU/");
}
.caption-background {
    height: 200px;
}
.hidden {
    display: none;
}

Body:
You can use the jQuery fadeToggle method.

Update your javascript with the following:

$(function() {
    $('.rsABlock img.info').click(function(e) {
        e.preventDefault();
        $('.caption-background').fadeToggle();
    });
});

Check out http://api.jquery.com/fadetoggle/


问:
CASE in Eloquent Laravel not running the function
The following is my query and the CASE part is not executing:

```<code>$deposit = CurrentTransaction::select('current_transaction.id', 'user.name', 'current_transaction.amount', 'current_transaction.status', 'current_transaction.type', 'current_transaction.refer_id', 'current_transaction.msg', 'current_transaction.remarks', 'current_transaction.created_by', 'current_transaction.created_at')
->join('user', 'current_transaction.user_id', '=', 'user.id')
->where('current_transaction.amount', '>', '0')
->where(function ($query) {
    $query->select(DB::raw('CASE WHEN current_transaction.created_by = current_transaction.user_id THEN "true" ELSE "false" END AS "result"'))->where('result', 'false');
})->get();
</code>```

and the syntax error around where('result', 'false') part.

Update

The structure of database:

```<code>Schema::create('current_transaction', function (Blueprint $table){
        $table->increments('id');
        $table->integer('user_id');
        $table->decimal('amount', 30, 8);
        $table->boolean('status')->default(1);
        $table->integer('type')->default(1);
        $table->integer('refer_id');
        $table->integer('created_by');
        $table->integer('updated_by');
        $table->timestamps();
    });
</code>```

I want to find out the rows where created_by is not equal to user_id
join the user table, and get the user.name with user_id
and amount more than 0.

答:
The following part will need to use DB::raw:</p>

```<code> ->where('current_transaction.created_by' ,'!=', DB::raw('current_transaction.user_id'))
</code>```

Body:
The following is my query and the CASE part is not executing:

$deposit = CurrentTransaction::select('current_transaction.id', 'user.name', 'current_transaction.amount', 'current_transaction.status', 'current_transaction.type', 'current_transaction.refer_id', 'current_transaction.msg', 'current_transaction.remarks', 'current_transaction.created_by', 'current_transaction.created_at')
->join('user', 'current_transaction.user_id', '=', 'user.id')
->where('current_transaction.amount', '>', '0')
->where(function ($query) {
    $query->select(DB::raw('CASE WHEN current_transaction.created_by = current_transaction.user_id THEN "true" ELSE "false" END AS "result"'))->where('result', 'false');
})->get();

and the syntax error around where('result', 'false') part.

Update

The structure of database:

Schema::create('current_transaction', function (Blueprint $table){
        $table->increments('id');
        $table->integer('user_id');
        $table->decimal('amount', 30, 8);
        $table->boolean('status')->default(1);
        $table->integer('type')->default(1);
        $table->integer('refer_id');
        $table->integer('created_by');
        $table->integer('updated_by');
        $table->timestamps();
    });

I want to find out the rows where created_by is not equal to user_id
join the user table, and get the user.name with user_id
and amount more than 0.

Body:
The following part will need to use DB::raw:

 ->where('current_transaction.created_by' ,'!=', DB::raw('current_transaction.user_id'))


问:
phpunit test method with static methods inside
I want to mock Carbon::now() and Transaction::where... (eloquent model in laravel) with Mockery. Is it possible? I don't have any idea how can I do this when code is written without dependency injection

```<code>class SomeClass
{
   public function getLatest()
   {
        $cacheTime = Carbon::now();

        if ($cacheTime > 'xxxx') {
            return 'abcdefgh';
        }

        return Transaction::where('base', '=', 'asas')
            ->where('target', '=', 'bbbb')
            ->orderByDesc('created_at')
            ->first();
   }
}
</code>```

答:
You can easily mock Carbon:

http://carbon.nesbot.com/docs/#api-testing

```<code>$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
Carbon::setTestNow($knownDate);                        // set the mock (of course this could be a real mock object)
echo Carbon::now();                                    // 2001-05-21 12:00:00
</code>```

So in your unit test just call Carbon::setTestNow($knownDate); before your function call.
Something like that:

```<code>public function testGetLatest()
{
    $knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
    Carbon::setTestNow($knownDate);
    $someClass = new SomeClass;

    $result = $someClass->getLatest();

    ...
}
</code>```

I don't think you can mock Transaction::where in your code and there is no purpose of doing it. The where and orderByDesc functions just setting your query. The first function will actually return the Transaction object. Even if you could mock or stub the first function, then your test is kind of useless because you are testing that your getLatest function returns some kind of mock object created by you.

This is actually a good example of integration test and Laravel provides a variety of helpful tools to make it easier. Check out this link:

https://laravel.com/docs/5.5/database-testing#writing-factories

Body:
I want to mock Carbon::now() and Transaction::where... (eloquent model in laravel) with Mockery. Is it possible? I don't have any idea how can I do this when code is written without dependency injection

class SomeClass
{
   public function getLatest()
   {
        $cacheTime = Carbon::now();

        if ($cacheTime > 'xxxx') {
            return 'abcdefgh';
        }

        return Transaction::where('base', '=', 'asas')
            ->where('target', '=', 'bbbb')
            ->orderByDesc('created_at')
            ->first();
   }
}

Body:
You can easily mock Carbon:

http://carbon.nesbot.com/docs/#api-testing

$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
Carbon::setTestNow($knownDate);                        // set the mock (of course this could be a real mock object)
echo Carbon::now();                                    // 2001-05-21 12:00:00

So in your unit test just call Carbon::setTestNow($knownDate); before your function call.
Something like that:

public function testGetLatest()
{
    $knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
    Carbon::setTestNow($knownDate);
    $someClass = new SomeClass;

    $result = $someClass->getLatest();

    ...
}

I don't think you can mock Transaction::where in your code and there is no purpose of doing it. The where and orderByDesc functions just setting your query. The first function will actually return the Transaction object. Even if you could mock or stub the first function, then your test is kind of useless because you are testing that your getLatest function returns some kind of mock object created by you.

This is actually a good example of integration test and Laravel provides a variety of helpful tools to make it easier. Check out this link:

https://laravel.com/docs/5.5/database-testing#writing-factories


问:
Set service Startup type in WiX installer
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

```<code><ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />
</code>```

Now I would also like to set the startup type. I have tried the following (see answer):

```<code><ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />
</code>```

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)

答:
Solved by editing the registry via RegistryKey, see example:

```<code><RegistryKey Root="HKLM"
             Key="SYSTEM\CurrentControlSet\Services\[Service Name]"
             Action="create">
    <RegistryValue Type="integer" Name="Start" Value="2" />
    <RegistryValue Type="integer" Name="DelayedAutostart" Value="0" />
</RegistryKey>
</code>```

Note service may appear as Automatic (Delayed Start) in Services GUI. However, after restarting, Services GUI displayed the service startup type as Automatic.

Body:
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

<ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />

Now I would also like to set the startup type. I have tried the following (see answer):

<ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)

Body:
Solved by editing the registry via RegistryKey, see example:

<RegistryKey Root="HKLM"
             Key="SYSTEM\CurrentControlSet\Services\[Service Name]"
             Action="create">
    <RegistryValue Type="integer" Name="Start" Value="2" />
    <RegistryValue Type="integer" Name="DelayedAutostart" Value="0" />
</RegistryKey>

Note service may appear as Automatic (Delayed Start) in Services GUI. However, after restarting, Services GUI displayed the service startup type as Automatic.


问:
How do I make a function with an array output?
Let X be an array of shape (100,200,3)

When a 3-dimensional vector y is given, I want to define a function f such that f(y) is an array of shape (100,200) such that f(y)[i][j] is the l2 distance between X[i][j] and y.

Here is how I tried:

```<code>import numpy as np
def norm(n):
    return np.linalg.norm(n)

def sdistance(y,i,j):
    return norm(np.asarray(y)-X[i][j]

def distance(y):
    return ???
</code>```

I want to define the last function distance(y) so that distance(y) is an array of shape (100,200) such that distance(y)[i][j]=sdistance(y,i,j).

How do I properly define the function distance(y)?

答:
If we literally translate your description to code it would look something like follows:

```<code>import numpy as np

X = np.random.random((100,200,3))

def norm(n):
    return np.linalg.norm(n)

def sdistance(y,i,j):
    return norm(np.asarray(y)-X[i,j])

def distance(y):
    return np.linalg.norm(X - y,axis=2)
</code>```

The last function should be equivalent to the following which follows your description more literally.

```<code>def distance(y):
    output = np.zeros(X.shape[0:2])
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            output[i,j] = sdistance(y,i,j)
    return output
</code>```

Body:
Let X be an array of shape (100,200,3)

When a 3-dimensional vector y is given, I want to define a function f such that f(y) is an array of shape (100,200) such that f(y)[i][j] is the l2 distance between X[i][j] and y.

Here is how I tried:

import numpy as np
def norm(n):
    return np.linalg.norm(n)

def sdistance(y,i,j):
    return norm(np.asarray(y)-X[i][j]

def distance(y):
    return ???

I want to define the last function distance(y) so that distance(y) is an array of shape (100,200) such that distance(y)[i][j]=sdistance(y,i,j).

How do I properly define the function distance(y)?

Body:
If we literally translate your description to code it would look something like follows:

import numpy as np

X = np.random.random((100,200,3))

def norm(n):
    return np.linalg.norm(n)

def sdistance(y,i,j):
    return norm(np.asarray(y)-X[i,j])

def distance(y):
    return np.linalg.norm(X - y,axis=2)

The last function should be equivalent to the following which follows your description more literally.

def distance(y):
    output = np.zeros(X.shape[0:2])
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            output[i,j] = sdistance(y,i,j)
    return output


问:
Constructor getting called twice React Component
The constructor of my react component is getting called twice but I can't figure out why. I am using react-redux to store the language of my app. I have a function that set the default language base on browser's language. LoginPage is the first component that gets render so I called my function in its constructor. Basically what it does is compare and dispatch an action. When I checked my state with redux developer tools I saw that it was getting dispatched twice. I printed dummy data in the constructor and it gets printed twice too.

LoginPage.js

```<code>import React from 'react';
import {connect} from 'react-redux';
import {startLogin} from '../actions/auth';
import {setLanguage} from '../actions/lang';

export class LoginPage extends React.Component{

  constructor(props){
    super(props);
    this.setDefaultLanguage();
    console.log('i am constructor');
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render(){
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

export default connect(undefined, mapDispatchToProps)( LoginPage);
</code>```

App.js

```<code>import React from 'react';
import ReactDom from 'react-dom';
import {Router, Route, Switch} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ExpenseDashBoardPage from '../components/ExpenseDashBoardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import NotFoundPage from '../components/NotFoundPage';
import LoginPage from '../components/LoginPage';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>
    <div>
      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashBoardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>
    </div>

  </Router>
)

export default AppRouter;
</code>```

答:
First of all, you should not call Redux actions or any kind of AJAX from within the constructor. Those things should be done in componentDidMount().

Second, I would request the language from the store as part of props. If not defined, then in componentDidMount() call your setDefaultLanguage().

I would do at least the following:

```<code>export class LoginPage extends React.Component {
  componentDidMount() {
    if (!this.props.lang) {
        this.setDefaultLanguage();
    }
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render() {
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapStateToProps = state => ({
    // Assuming `steate.lang` is where you would set the language.
    lang: state.lang
});

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

const mergeProps = (stateProps, dispatchProps) => ({ ...stateProps, ...dispatchProps });

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(LoginPage);
</code>```

Body:
The constructor of my react component is getting called twice but I can't figure out why. I am using react-redux to store the language of my app. I have a function that set the default language base on browser's language. LoginPage is the first component that gets render so I called my function in its constructor. Basically what it does is compare and dispatch an action. When I checked my state with redux developer tools I saw that it was getting dispatched twice. I printed dummy data in the constructor and it gets printed twice too.

LoginPage.js

import React from 'react';
import {connect} from 'react-redux';
import {startLogin} from '../actions/auth';
import {setLanguage} from '../actions/lang';

export class LoginPage extends React.Component{

  constructor(props){
    super(props);
    this.setDefaultLanguage();
    console.log('i am constructor');
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render(){
    return(

Expensify

It\'s time to get your expenses under control.

          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>

    )
  };
}

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

export default connect(undefined, mapDispatchToProps)( LoginPage);

App.js

import React from 'react';
import ReactDom from 'react-dom';
import {Router, Route, Switch} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ExpenseDashBoardPage from '../components/ExpenseDashBoardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import NotFoundPage from '../components/NotFoundPage';
import LoginPage from '../components/LoginPage';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>

      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashBoardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>

  </Router>
)

export default AppRouter;

Body:
First of all, you should not call Redux actions or any kind of AJAX from within the constructor. Those things should be done in componentDidMount().

Second, I would request the language from the store as part of props. If not defined, then in componentDidMount() call your setDefaultLanguage().

I would do at least the following:

export class LoginPage extends React.Component {
  componentDidMount() {
    if (!this.props.lang) {
        this.setDefaultLanguage();
    }
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render() {
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapStateToProps = state => ({
    // Assuming `steate.lang` is where you would set the language.
    lang: state.lang
});

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

const mergeProps = (stateProps, dispatchProps) => ({ ...stateProps, ...dispatchProps });

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(LoginPage);


问:
How to stop swipe in ScrollView?
look this video of current scrolling behavior. i want, as soon as finger is lifted from screen, to disable scrolling.

Edit: the video shows a user scrolling through a list. When the finger is lifted from the screen, you see the scrolling continues up or down for a short time.

答:
I think what you need is:

<ScrollView
  bounces={false}
  />
```

This way when you scroll finished, the scroll animation will not continue and immediately stopped.

Title: How to stop swipe in ScrollView?

Body:
I think what you need is:

<ScrollView
  bounces={false}
  />

This way when you scroll finished, the scroll animation will not continue and immediately stopped.


问:
Defining a Type Alias in C# across multiple files
In C++, it's easy to write something along the lines of:

```<code>#ifdef FAST
typedef Real float;
#endif

#ifdef SLOW
typedef Real double;
#endif

#ifdef SLOWER
typedef Real quad;
#endif
</code>```

In some common header file so I could simply write one version of code and #define the appropriate version to get different binaries.

I know in C# you can do something similar along the lines of:

```<code>using Real = double;
</code>```

So that you can get the similar semantics to typedefs.
But is it possible to do something similar to the C++ code above that I wouldn't have to write in every single file?

答: closest thing would be partial classes. partial classes let you define one class across multiple files.</p>

Body:
In C++, it's easy to write something along the lines of:

#ifdef FAST
typedef Real float;
#endif

#ifdef SLOW
typedef Real double;
#endif

#ifdef SLOWER
typedef Real quad;
#endif

In some common header file so I could simply write one version of code and #define the appropriate version to get different binaries.

I know in C# you can do something similar along the lines of:

using Real = double;

So that you can get the similar semantics to typedefs.
But is it possible to do something similar to the C++ code above that I wouldn't have to write in every single file?


问:
Hana Sap B1: Execute query using hdbuserstore - * 10: invalid username or password SQLSTATE: 28000
Actually I'm working in Hana DB and Suse Enterprise Server, my objective is use the Scripting and Cronjob to automatize some tasks.

Using hdbuserstore located in /usr/sap/hdbclient I've created and profile for create a HANA command line secure connection, check this link.

My profile works perfect, I did:

Create a user backup into HanaDB, using

```<code>*create user backup password Aa12345678*
</code>```

Then, I've added BACKUPS PRIVILEGES to it:

```<code>*grant BACKUP ADMIN to backup*
</code>```

Later, I've used ./hdbuserstore to create a profile to use via command line:

```<code>./hdbuserstore SET back5prf localhost:30015 backup Aa12345678
</code>```

Then list the profile: ./hdbuserstore LIST

```<code>DATA FILE       : /root/.hdb/hanab1/SSFS_HDB.DAT
KEY BACK2PRF
  ENV : NDB@hanab1:30015
  USER: backups
KEY BACK3PRF
  ENV : hanab1:30015
  USER: backups
KEY BACK5PRF
  ENV : localhost:30015
  USER: backup
KEY BACKUPSTORE
  ENV : localhost:30015
  USER: backups
</code>```

How you guys can see, the profile is ready. Finally when I tried to use the following command:

```<code>./hdbsql -U BACK5PRF "SELECT * FROM SCHEMAS"
</code>```

The system returns the following message:

```<code>* 10: invalid username or password SQLSTATE: 28000
</code>```

Why I'm getting this error event the user and password are ok?

There is other way to execute HANA SQL query without enter into the hdbsql console to automate via Scripting?

答:
This error message can have several causes:

actual wrong user name/password

user account is locked (you need to unlock it in the user management)

user account is a restricted user and not allowed to connect via ODBC/JDBC or from anywhere "outside" SAP HANA

I suggest you make sure that the user works in SAP HANA studio and then setup the cron job.

Body:
Actually I'm working in Hana DB and Suse Enterprise Server, my objective is use the Scripting and Cronjob to automatize some tasks.

Using hdbuserstore located in /usr/sap/hdbclient I've created and profile for create a HANA command line secure connection, check this link.

My profile works perfect, I did:

Create a user backup into HanaDB, using

*create user backup password Aa12345678*

Then, I've added BACKUPS PRIVILEGES to it:

*grant BACKUP ADMIN to backup*

Later, I've used ./hdbuserstore to create a profile to use via command line:

./hdbuserstore SET back5prf localhost:30015 backup Aa12345678

Then list the profile: ./hdbuserstore LIST

DATA FILE       : /root/.hdb/hanab1/SSFS_HDB.DAT
KEY BACK2PRF
  ENV : NDB@hanab1:30015
  USER: backups
KEY BACK3PRF
  ENV : hanab1:30015
  USER: backups
KEY BACK5PRF
  ENV : localhost:30015
  USER: backup
KEY BACKUPSTORE
  ENV : localhost:30015
  USER: backups

How you guys can see, the profile is ready. Finally when I tried to use the following command:

./hdbsql -U BACK5PRF "SELECT * FROM SCHEMAS"

The system returns the following message:

* 10: invalid username or password SQLSTATE: 28000

Why I'm getting this error event the user and password are ok?

There is other way to execute HANA SQL query without enter into the hdbsql console to automate via Scripting?


问:
Coded UI - Asserting StartsWith( ) not working as expected (VS 2015)
Im trying to build a test case where i retrieve a list of data objects and populate it in a datagrid.

I want to verify (assert) that the 1st row has a field/column that StartsWith  "ABC".

I can see that the generated code produces an element that basically has the field's exact display value (in this case it is "ABCDEFG").

Of course, when i run this test, it validates just fine because the generated element ("ABCDEFG") definitely startswith "ABC".

The problem is that the datagrid could be populated with dynamic data, so the field display could be something like "ABC-FOO" or even "XYZ" for instance.

In short the automated code that is generated seems to not behaving as i expect.

I am expecting to do a StartsWith assertion against the real-time field display, not a generated (hard-coded) string which i used to build the test with.

Am i doing something wrong here?
Am i missing something critical?
Or should i be abandoning Coded UI altogether?

Here is the generated element:

```<code>public HtmlLabel generatedLabel
{
    get
    {
        if ((this.mUIgeneratedLabelLabel == null))
        {
            this.mUIgeneratedLabelLabel = new HtmlLabel(this);
            #region Search Criteria
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.Id] = "Control_42";
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.Name] = null;
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.LabelFor] = null;
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.InnerText] = "ABCDEF-FOO";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.Class] = "field-control";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.ControlDefinition] = "class=\"field-control\" id=\"ControlB";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.TagInstance] = "24";
            this.mUIgeneratedLabelLabel.WindowTitles.Add("MyTest");
            #endregion
        }
        return this.mUgeneratedLabelLabel;
    }
}
</code>```

---- Updated ----

To explain what my confusion is: I've setup my StartsWith() assertion on some text ("ABCD") that has been retrieved dynamically. I created the asserttion to check if the text StartsWith "ABC". Now, when i look at the generated assertion code, i see that the assertion will always pass because the code is comparing the text's string literal ("ABCD") with the assertion check string literal ("ABC"). What I am looking for is to do the assertion check with whatever dynamic text is retrieved during the test run-time. Hope this makes it clear where im getting stuck.

答:
To figure out where the problem is, you could first try doing
if (control.Text.Contains("ABC")), then try if(control.Text.StartsWith("ABS")), and see where the problem emerges.

Body:
Im trying to build a test case where i retrieve a list of data objects and populate it in a datagrid.

I want to verify (assert) that the 1st row has a field/column that StartsWith  "ABC".

I can see that the generated code produces an element that basically has the field's exact display value (in this case it is "ABCDEFG").

Of course, when i run this test, it validates just fine because the generated element ("ABCDEFG") definitely startswith "ABC".

The problem is that the datagrid could be populated with dynamic data, so the field display could be something like "ABC-FOO" or even "XYZ" for instance.

In short the automated code that is generated seems to not behaving as i expect.

I am expecting to do a StartsWith assertion against the real-time field display, not a generated (hard-coded) string which i used to build the test with.

Am i doing something wrong here?
Am i missing something critical?
Or should i be abandoning Coded UI altogether?

Here is the generated element:

public HtmlLabel generatedLabel
{
    get
    {
        if ((this.mUIgeneratedLabelLabel == null))
        {
            this.mUIgeneratedLabelLabel = new HtmlLabel(this);
            #region Search Criteria
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.Id] = "Control_42";
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.Name] = null;
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.LabelFor] = null;
            this.mUIgeneratedLabelLabel.SearchProperties[HtmlLabel.PropertyNames.InnerText] = "ABCDEF-FOO";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.Class] = "field-control";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.ControlDefinition] = "class=\"field-control\" id=\"ControlB";
            this.mUIgeneratedLabelLabel.FilterProperties[HtmlLabel.PropertyNames.TagInstance] = "24";
            this.mUIgeneratedLabelLabel.WindowTitles.Add("MyTest");
            #endregion
        }
        return this.mUgeneratedLabelLabel;
    }
}

---- Updated ----

To explain what my confusion is: I've setup my StartsWith() assertion on some text ("ABCD") that has been retrieved dynamically. I created the asserttion to check if the text StartsWith "ABC". Now, when i look at the generated assertion code, i see that the assertion will always pass because the code is comparing the text's string literal ("ABCD") with the assertion check string literal ("ABC"). What I am looking for is to do the assertion check with whatever dynamic text is retrieved during the test run-time. Hope this makes it clear where im getting stuck.


问:
Adding a UIView to a UITableViewController with NSLayoutConstraints programmatically with Swift 4
I'm attempting to add a UIView with NSLayoutConstraints but I keep getting an uncaught exception of type NSException error. The main reason I'm doing it with code instead of in the storyboard is I want it to be above the Navigation bar on the UITableViewController.

Here is the code I currently have.

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let mainWindow: UIWindow = UIApplication.shared.keyWindow!

    let newView = UIView()
    newView.backgroundColor = UIColor.darkAqua
    newView.translatesAutoresizingMaskIntoConstraints = false

    mainWindow.addSubview(newView)

    let viewHeight = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewWidth = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewLeft = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 40)
    let viewTop = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

    newView.addConstraints([viewHeight, viewWidth, viewLeft, viewTop])
}
</code>```

If I take out the viewLeft and viewTop it will run okay since the toItem: is nil in NSLayoutConstraint. But I think the problem has something to do with that toItem: I've tried using self.view and mainWindow but it keeps throwing the error.

I've seen lots of examples of how to do this and I'm pretty much copying them as far as I can tell, but none of them were Swift 4 so I'm wondering if something changed in Swift 4.

Any help would be great! Thank you.

Error Message:

libc++abi.dylib: terminating with uncaught exception of type NSException
  (lldb)

答:
I tried with self.view instead of main window and with the different style of layout constraints. Just try this Jason Brady.

override func viewDidLoad() {
    super.viewDidLoad()

    let newView = UIView()
    newView.backgroundColor = UIColor.red
    newView.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(newView)

    newView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 40).isActive = true
    newView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
    newView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
```

Body:
I'm attempting to add a UIView with NSLayoutConstraints but I keep getting an uncaught exception of type NSException error. The main reason I'm doing it with code instead of in the storyboard is I want it to be above the Navigation bar on the UITableViewController.

Here is the code I currently have.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let mainWindow: UIWindow = UIApplication.shared.keyWindow!

    let newView = UIView()
    newView.backgroundColor = UIColor.darkAqua
    newView.translatesAutoresizingMaskIntoConstraints = false

    mainWindow.addSubview(newView)

    let viewHeight = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewWidth = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewLeft = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 40)
    let viewTop = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

    newView.addConstraints([viewHeight, viewWidth, viewLeft, viewTop])
}

If I take out the viewLeft and viewTop it will run okay since the toItem: is nil in NSLayoutConstraint. But I think the problem has something to do with that toItem: I've tried using self.view and mainWindow but it keeps throwing the error.

I've seen lots of examples of how to do this and I'm pretty much copying them as far as I can tell, but none of them were Swift 4 so I'm wondering if something changed in Swift 4.

Any help would be great! Thank you.

Error Message:

libc++abi.dylib: terminating with uncaught exception of type NSException
  (lldb)


问:
Data returning from api call through service to component is an object and seems to need to be an Array for Angular
I have data returned to me that works just fine

working data is

data: Array(16)

Data that is NOT working is like this

data:  Menu1Items: Array(5)  > 0 { .... }    etc

I am using Angular 5, and so service returns data like this

```<code>  .map((response: Response) => {
            return response;
</code>```

Then the component intercepts it and console.log works fine

```<code>this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result;
                console.log('menu',result);
            })
</code>```

problem is with the data,  this screenshot shows the problem, i just don't understand how to fix it with the object vs array?

error message ONLY because of the HTML TEMPLATE

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML Template

```<code><li *ngFor="let item of testing">
</code>```

Image showing that a call that is similar in architecture with html template loop,  component , service  the working call is the BOTTOM , component  notice the different compared to the one called menu that I'm having trouble with?

答:
I think you need to set testing = result.data, and iterate through that.

```<code>this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result.data;

            })
</code>```

this will give you access to the array in 'data'

I tried to change the shape of the data, and this worked for me.  Hopefully it works for you...

```<code>var data={
      menu1Items:[{key:"boo", key2:"hoo"}],
      menu2Items:[{key:"boo2", key2:"hoo2"}]
    }
    var tempData:any[]=[];
    for(var key in data){
      if(data.hasOwnProperty(key)){
        tempData.push(data[key]);
      }
    }
    this.data = tempData;
}
</code>```

In your template:

```<code><ul *ngFor="let menu of data ">
  <li>
      <ng-container *ngFor="let menuItem of menu">
          {{menuItem.key}} / {{ menuItem.key2}}
      </ng-container>
  </li>
</ul>
</code>```

Body:
I have data returned to me that works just fine

working data is

data: Array(16)

Data that is NOT working is like this

data:  Menu1Items: Array(5)  > 0 { .... }    etc

I am using Angular 5, and so service returns data like this

  .map((response: Response) => {
            return response;

Then the component intercepts it and console.log works fine

this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result;
                console.log('menu',result);
            })

problem is with the data,  this screenshot shows the problem, i just don't understand how to fix it with the object vs array?

error message ONLY because of the HTML TEMPLATE

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML Template

Image showing that a call that is similar in architecture with html template loop,  component , service  the working call is the BOTTOM , component  notice the different compared to the one called menu that I'm having trouble with?

Body:
I think you need to set testing = result.data, and iterate through that.

this.arsSevice.getMenu()
        .subscribe(
            result => {
                this.testing = result.data;

            })

this will give you access to the array in 'data'

I tried to change the shape of the data, and this worked for me.  Hopefully it works for you...

var data={
      menu1Items:[{key:"boo", key2:"hoo"}],
      menu2Items:[{key:"boo2", key2:"hoo2"}]
    }
    var tempData:any[]=[];
    for(var key in data){
      if(data.hasOwnProperty(key)){
        tempData.push(data[key]);
      }
    }
    this.data = tempData;
}

In your template:

<ul *ngFor="let menu of data ">
  <li>
      <ng-container *ngFor="let menuItem of menu">
          {{menuItem.key}} / {{ menuItem.key2}}
      </ng-container>
  </li>
</ul>


问:
Search Form Styling CSS
So I have styled my search form on the top banner of my blog, but when I leave the home page to another page the background image search icon disappears!  Any suggestions as to why this is happening? Thanks ;-) http://demo.boxofficeboxing.co.uk</p>

```<code>#s {
   padding:8px 6px;
   background:rgba(0, 0, 0, 0);
   border-style: solid;
   border-color: #fff;
   border-width: 1px 0px 1px 1px;
   font-family:open sans;
   font-size:14px;
   color: #fff;
   }
   #searchsubmit {
   cursor:pointer;
   position:relative;
   padding:8px 16px;
   left:-9px;
   border-style: solid;
   border-color: #fff;
   border-width: 1px 1px 1px 0px;
   background-color: #a88f4b;
   font-family:open sans;
   font-size:14px;
   background-image: url('wp-content/uploads/2017/12/search.png');
   background-position: center center;
   background-repeat:no-repeat;
   text-indent: -9999px;
   }
   ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
   color: white;
   }
   ::-moz-placeholder { /* Firefox 19+ */
   color: white;
   }
   :-ms-input-placeholder { /* IE 10+ */
   color: white;
   }
   :-moz-placeholder { /* Firefox 18- */
   color: white;
   }
   input:focus {
   outline: none;
   }
</code>```

答:
It is simple enough to crack..

The path for your image icon is set to

```<code>wp-content/uploads/2017/12/search.png
</code>```

So when on home page - the url becomes

```<code>http://demo.boxofficeboxing.co.uk/wp-content/uploads/2017/12/search.png
</code>```

And when on inside page - say video highlights - the url turns to be

```<code>http://demo.boxofficeboxing.co.uk/videos-highlights/wp-content/uploads/2017/12/search.png
</code>```

One way to resolve the same will be set the URL in css to be

```<code>/wp-content/uploads/2017/12/search.png
</code>```

That should solve your issue / probelm.

Title: Search Form Styling CSS

Body:
So I have styled my search form on the top banner of my blog, but when I leave the home page to another page the background image search icon disappears!  Any suggestions as to why this is happening? Thanks ;-) http://demo.boxofficeboxing.co.uk

#s {
   padding:8px 6px;
   background:rgba(0, 0, 0, 0);
   border-style: solid;
   border-color: #fff;
   border-width: 1px 0px 1px 1px;
   font-family:open sans;
   font-size:14px;
   color: #fff;
   }
   #searchsubmit {
   cursor:pointer;
   position:relative;
   padding:8px 16px;
   left:-9px;
   border-style: solid;
   border-color: #fff;
   border-width: 1px 1px 1px 0px;
   background-color: #a88f4b;
   font-family:open sans;
   font-size:14px;
   background-image: url('wp-content/uploads/2017/12/search.png');
   background-position: center center;
   background-repeat:no-repeat;
   text-indent: -9999px;
   }
   ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
   color: white;
   }
   ::-moz-placeholder { /* Firefox 19+ */
   color: white;
   }
   :-ms-input-placeholder { /* IE 10+ */
   color: white;
   }
   :-moz-placeholder { /* Firefox 18- */
   color: white;
   }
   input:focus {
   outline: none;
   }

Body:
It is simple enough to crack..

The path for your image icon is set to

wp-content/uploads/2017/12/search.png

So when on home page - the url becomes

http://demo.boxofficeboxing.co.uk/wp-content/uploads/2017/12/search.png

And when on inside page - say video highlights - the url turns to be

http://demo.boxofficeboxing.co.uk/videos-highlights/wp-content/uploads/2017/12/search.png

One way to resolve the same will be set the URL in css to be

/wp-content/uploads/2017/12/search.png

That should solve your issue / probelm.


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
My "click" didn't happen directly in relationship to C#, but there were three instances that I believe relate to my ability to easily work within C#.

1) I was 8 years old, trying to write a seemingly simple assembly routine to clear the graphics screen on a Commodore 64.  At the point where I would have written a loop in Basic, I hit a wall.  As far as I understood things, there was no way to write a loop in assembly language that would cross the 256 (single-byte) barrier.  I hunted through the books that I had, and just couldn't find the solution.  (The answer certainly wasn't to write a 3-byte "line" of code for each group of 256 rows of pixels.)  Several days later, it just hit me.  (The solution was to write two loops, with the outer loop actually changing the code of the inner loop.)  This isn't something we need to do with our current languages, but I could almost feel my brain growing.

2) This happened sometime while I was pretty young, too. (Maybe 10?)  My piano lessons had progressed to a point where I had to play a song with different rhythms in each hand.  I struggled with that song for weeks (partly because I tended to avoid the necessary practice).  Practice helped, but not quite enough.  Then, one day, I sat down and it suddenly clicked.  Ever after that, the song was almost easy to play.

3) During college, and after I had been programming for fun for a few years, my instructor provided us with an entry-level OOP assignment.  We were to use an object, which contained several other objects.  Each of these drew themselves on-screen.  To complete the task, everything needed to rotate by 45 degrees.  Almost all the students (including myself) got partial credit because we rotated each object inside the containing object.  The ones who got full credit had simply rotated one thing: the containing object.  I didn't hear a "click", but this lesson definitely helped me to understand OOP.

To break your own barrier, you could follow the suggestions above.  Maybe find a simple project you clearly understand, and implement it in C#.  Or you could take a physical object you understand fairly well (like a car with steering wheel, wheels, engine, brakes, etc.), and model it with classes in C#.  Of course, you may also achieve the "click" by simply picking one feature or keyword whose purpose you don't get, and studying that until it clicks.  That one click may be enough to break into C# completely.

Either way, have fun!  (Fun things are always easier for your subconscious mind to analyze while you aren't focusing on it.)

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: John Fisher


答:
A somewhat cleaner and much faster version of @Wen. Still using reindex but with numpy.linalg.norm instead of scipy.spatial.distance.euclidean</p>

```<code>import numpy as np
dims = ['X','Y','Z']
df['distance'] = np.linalg.norm((df[dims].values)-(lookup.reindex(df['key']).values), axis = 1)
</code>```

Title: Calculate distance based on a lookup dataframe

Body:
I have a DataFrame and a lookup table. For a key in the DataFrame I would like to lookup the corresponding row in the lookup table and calculate the Euclidian distance for a number of columns. Mock data looks like

import pandas as pd
import numpy.random as rand

df = pd.DataFrame({'key':rand.randint(0, 5, 10),
                    'X': rand.randn(10),
                    'Y': rand.randn(10),
                    'Z': rand.randn(10)})

          X         Y         Z  key
0  0.163142  0.387871 -0.433157    3
1 -2.020957 -1.537615 -1.996704    0
2  1.249118  1.633246  0.028222    1
3 -0.019601  1.757136  0.787936    2
4 -0.039649  1.380557  0.123677    0
5  0.500814 -1.049591 -1.261868    3
6  1.175576 -0.310895  0.549420    0
7 -0.152696  0.139020  0.887219    2
8  0.491099  0.434652  0.791038    2
9 -0.231334  0.264414  0.913475    4

lookup = pd.DataFrame({'X': rand.randn(5),
                    'Y': rand.randn(5),
                    'Z': rand.randn(5)})

          X         Y         Z
0  0.242419 -0.630230 -0.254344
1  0.799573  0.354169  1.099456
2 -0.754582 -1.882192 -1.270382
3 -1.645707 -0.131905 -0.445954
4  0.743351  0.456220  0.975457
5  0.136197  0.278329 -2.336110

For example, the zeroth column has values

df.loc[0,'X':'Z'].values
[0.163142,0.387871,-0.433157]

the key is 3 so the row in the lookup is

lookup.iloc[3,:].values
[-1.645707 -0.131905 -0.445954]

The distance is

import numpy as np
np.linalg.norm(np.array([0.163142,0.387871,-0.433157]) - np.array([-0.754582, -1.882192, -1.270382]))
2.5877304853423202

I would like to do this for every row in df and return the value as a new column. Is there a slick way to do this?

Body:
A somewhat cleaner and much faster version of @Wen. Still using reindex but with numpy.linalg.norm instead of scipy.spatial.distance.euclidean

import numpy as np
dims = ['X','Y','Z']
df['distance'] = np.linalg.norm((df[dims].values)-(lookup.reindex(df['key']).values), axis = 1)


问:
Get data of specific node element on click
I'm trying to get specific data depending on which node element the user is clicking. I have 4 elements that I have targeted using the querySelectorAll code. What I want to accomplish is that if I click the first element I will console.log that specific data, and if I select the third element I will get that data logged. I've tried a couple of things, but haven't got it to work yet.

function selectedSplit() {
 var macroSplits = document.querySelectorAll(".card");
  console.log(macroSplits[0].childNodes[3].childNodes[1].innerHTML);
}```

答:
It's unclear where you are using selectedSplit - Wether or not it is being used as the event listener return function. But using an onClick event listener, you're return function will be passed the information you need.

If you want to accomplish this in the markup, you could do -

```<code><div class='card' onClick="selectedSplit"></div>
</code>```

Then you can simply access it via event.target

```<code>function selectedSplit(event) {
  var thisCard=event.target;
  console.log(thisCard.innerHTML);
}
</code>```

Body:
It's unclear where you are using selectedSplit - Wether or not it is being used as the event listener return function. But using an onClick event listener, you're return function will be passed the information you need.

If you want to accomplish this in the markup, you could do -

<div class='card' onClick="selectedSplit"></div>

Then you can simply access it via event.target

function selectedSplit(event) {
  var thisCard=event.target;
  console.log(thisCard.innerHTML);
}


问:
How to measure the area of a polygon in ggplot2?

Hi everyone,
I have a number of samples that I would like to draw a polygon for each of them to illustrate the shape of the data. My data look likes this:

```<code>01 0.31707317

02 0.12195122

03 0.09756098

04 0.07317073

05 0.07317073

06 0.07317073

07 0.07317073

08 0.07317073

09 0.04878049

10 0.04878049
</code>```

I can easily draw a radar chart using radarchart, which looks like this:

But I am trying to measure the area of the results shape and use that as a measure of data shape. This is where I struggle.

I tried to save the resulting figure as a vector and use the points there but it looks like I can not pass the chart into a vector. Then I tried rgdal package to exprt my figure as a shapefile and use the coordinates there:

```<code>coorddf <- SpatialPointsDataFrame(radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , pfcol=rgb(0.2,0.5,0.5, 0.2))
, data = radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , cglcol = "white", pfcol=rgb(0.2,0.5,0.5, 0.2))

writeOGR(coorddf, dsn = '.', layer = 'mypoints', driver = "ESRI Shapefile")
</code>```

Which was not a good idea because my data does not have values that can be used as lat and long points..

Any suggestions?

答:
It is possible to solve for the area of your shape analytically.
The area is made up of a bunch of triangles. For example, the wedge
between V1 & V2 looks like this.

This is a side-angle-side problem so the area is v1*v2*sin(pi/5)/2. The area for the second wedge will be v2*v3*sin(pi/5)/2.  Just add up the triangles around the circle.

Body:
Hi everyone,
I have a number of samples that I would like to draw a polygon for each of them to illustrate the shape of the data. My data look likes this:

01 0.31707317

02 0.12195122

03 0.09756098

04 0.07317073

05 0.07317073

06 0.07317073

07 0.07317073

08 0.07317073

09 0.04878049

10 0.04878049

I can easily draw a radar chart using radarchart, which looks like this:

But I am trying to measure the area of the results shape and use that as a measure of data shape. This is where I struggle.

I tried to save the resulting figure as a vector and use the points there but it looks like I can not pass the chart into a vector. Then I tried rgdal package to exprt my figure as a shapefile and use the coordinates there:

coorddf <- SpatialPointsDataFrame(radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , pfcol=rgb(0.2,0.5,0.5, 0.2))
, data = radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , cglcol = "white", pfcol=rgb(0.2,0.5,0.5, 0.2))

writeOGR(coorddf, dsn = '.', layer = 'mypoints', driver = "ESRI Shapefile")

Which was not a good idea because my data does not have values that can be used as lat and long points..

Any suggestions?


问:
Import-PFXCertificate: The specified network password is not correct
I've got some pretty simple code I'm trying to troubleshoot. The environment is an Azure Windows Server 2012 machine, and I'm logged in as a domain admin running a Powershell console with Administrator privileges.

I'm just trying to Import-PFXCertificate from a known location but it will not accept the network password.

Here's the code.

```<code>$SecurePWD = ConvertTo-SecureString -String 'iW@nt2die' -AsPlainText -Force
Import-PFXCertificate -Password $SecurePWD -CertStoreLocation "Cert:\LocalMachine\Root" -FilePath "C:\Certs\TestCert.pfx"
</code>```

When I run this beautiful block of code, with the password being absolutely correct (I tested by logging in using the password), it greets me with this error:

```<code>Import-PFXCertificate : The specified network password is not correct.
</code>```

WHYYYY.

I've tried escaping out the @, but that doesn't do anything. I've tried crying, but the computer is completely unmoved by my tears.

答:
Per documentation for Import-PfxCertificate, the -Password parameter is for the password of the certificate and not the user to login with.

-Password - Specifies the password for the imported PFX file in the form of a secure string.

Body:
I've got some pretty simple code I'm trying to troubleshoot. The environment is an Azure Windows Server 2012 machine, and I'm logged in as a domain admin running a Powershell console with Administrator privileges.

I'm just trying to Import-PFXCertificate from a known location but it will not accept the network password.

Here's the code.

$SecurePWD = ConvertTo-SecureString -String 'iW@nt2die' -AsPlainText -Force
Import-PFXCertificate -Password $SecurePWD -CertStoreLocation "Cert:\LocalMachine\Root" -FilePath "C:\Certs\TestCert.pfx"

When I run this beautiful block of code, with the password being absolutely correct (I tested by logging in using the password), it greets me with this error:

Import-PFXCertificate : The specified network password is not correct.

WHYYYY.

I've tried escaping out the @, but that doesn't do anything. I've tried crying, but the computer is completely unmoved by my tears.