问:
Stylecop tells me to add this keyword, but it's redundant - any performance implications?
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?

Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.

Thanks

答:
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.

Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).

Of course, in most cases, you would simply add a regular instance method to the class or a base-class...

```<code>class Foo {
    void Test() {
        this.Bar(); // fine
        Bar(); // compiler error
    }
}
static class FooExt {
    public static void Bar(this Foo foo) { }
}
</code>```

OwnerDisplayName: GSS

Body:
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.

Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).

Of course, in most cases, you would simply add a regular instance method to the class or a base-class...

class Foo {
    void Test() {
        this.Bar(); // fine
        Bar(); // compiler error
    }
}
static class FooExt {
    public static void Bar(this Foo foo) { }
}

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


来源: stackexchange

问:
Convert cell array of numbers to matrix (cell2mat) while converting empties to zeros
I have a function that uses strfind in a cellfun call to find which string items in a cell array match a specified string. For example:

```<code>cellfun( @(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)
</code>```

The original cell matrix is like this:

```<code>fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};
</code>```

The result for this looks like this:

```<code>[10]    []    [10]    []    [9]    []
</code>```

I am trying to find a function that will convert this to:

```<code>10  0  10  0  9  0
</code>```

Using cell2mat I get:

```<code>10  10  9
</code>```

So I have to use this currently:

```<code>x(cellfun('isempty', x))={0};
cell2mat(x);
</code>```

Is there a function that is cleaner than this (i.e. a one-liner solution)?

Thanks.

答:
This works even if there are several occurrences of the sought string. It finds the first such occurrence if there's any, or gives 0 otherwise:

```<code>result = cellfun(@(x) sum(min(strfind(x, 'openmask'))), fileNames);
</code>```

The code uses min to keep the first occurrence. This will give either a number or []. Then sum transforms [] into 0.

If you prefer to keep the last occurrence,  change min to max or use Sardar Usama's suggestion:

```<code>result = cellfun(@(x) max([0 strfind(x, 'openmask')]), fileNames);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function that uses strfind in a cellfun call to find which string items in a cell array match a specified string. For example:

cellfun( @(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)

The original cell matrix is like this:

fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};

The result for this looks like this:

[10]    []    [10]    []    [9]    []

I am trying to find a function that will convert this to:

10  0  10  0  9  0

Using cell2mat I get:

10  10  9

So I have to use this currently:

x(cellfun('isempty', x))={0};
cell2mat(x);

Is there a function that is cleaner than this (i.e. a one-liner solution)?

Thanks.

Body:
This works even if there are several occurrences of the sought string. It finds the first such occurrence if there's any, or gives 0 otherwise:

result = cellfun(@(x) sum(min(strfind(x, 'openmask'))), fileNames);

The code uses min to keep the first occurrence. This will give either a number or []. Then sum transforms [] into 0.

If you prefer to keep the last occurrence,  change min to max or use Sardar Usama's suggestion:

result = cellfun(@(x) max([0 strfind(x, 'openmask')]), fileNames);


问:
Incorrect number of threads shown from node.js os.cpus() when clustering in AWS EC2
Is there a way to get access to all 324 threads in the AWS c4.8xlarge instance from node.js? Is there another way to get the number of threads besides os.cpus() ?

We are using a CPU-optimized AWS instance of size c4.8xlarge which has 36 virtual CPUs each with 9 cores, which is a total of 324 threads (36 x 9).

When we run this script to measure the number of threads, it shows 36, but it does not show any information about the 9 cores on each vCPU.

```<code> const cluster = require('cluster');
 const numCPUs = require('os').cpus().length;

 if (cluster.isMaster) {
   console.log(`Master ${process.pid} is running`);

   // Fork workers.
   for (let i = 0; i < numCPUs; i++) {
     cluster.fork();
   }

   cluster.on('exit', (worker, code, signal) => {
     console.log(`worker ${worker.process.pid} died`);
   });
 } else {
     console.log("Number of cores: " + numCPUs);
     process.exit(0);
 }
</code>```

This is a problem because we run this script on another machine that has 1 CPU and 8 hyper-threaded cores and it reports 16 CPUs (which is correct).

答: According to various sources (including a blog article on Amazon's site), a 'c4.8xlarge' has 18 hyperthreaded cores, totalling 36 vCPUs (which are hyperthreaded cores).

Body:
Is there a way to get access to all 324 threads in the AWS c4.8xlarge instance from node.js? Is there another way to get the number of threads besides os.cpus() ?

We are using a CPU-optimized AWS instance of size c4.8xlarge which has 36 virtual CPUs each with 9 cores, which is a total of 324 threads (36 x 9).

When we run this script to measure the number of threads, it shows 36, but it does not show any information about the 9 cores on each vCPU.

 const cluster = require('cluster');
 const numCPUs = require('os').cpus().length;

 if (cluster.isMaster) {
   console.log(`Master ${process.pid} is running`);

   // Fork workers.
   for (let i = 0; i < numCPUs; i++) {
     cluster.fork();
   }

   cluster.on('exit', (worker, code, signal) => {
     console.log(`worker ${worker.process.pid} died`);
   });
 } else {
     console.log("Number of cores: " + numCPUs);
     process.exit(0);
 }

This is a problem because we run this script on another machine that has 1 CPU and 8 hyper-threaded cores and it reports 16 CPUs (which is correct).


问:
Iterate AWS json response python
Trying to iterate thru an AWS json output and check if a specific version exist in ECR using the below code. But I am always getting "Image does not exist in ECR!" even when the image tag exist.    </p>

```<code>client = boto3.client('ecr')
response = client.list_images(registryId='my_account_number', repositoryName='my_app')

for i in response['imageIds']:
    if i['imageTag'] != version:
        print(response)
        print('Image does not exist in ECR!')
        quit()
    else:
        pass
</code>```

答:
Change your code to run until it finds the version you are expecting:

```<code>client = boto3.client('ecr')
response = client.list_images(registryId='my_account_number', repositoryName='my_app')

for i in response['imageIds']:
    if i['imageTag'] == version:
        print('Found matching version!')
        print(i)
        break
else:
    print('Image does not exist in ECR!')
</code>```

If the correct version is not found, 'Image does not exist in ECR!' will be printed.

Title: Iterate AWS json response python

Body:
Trying to iterate thru an AWS json output and check if a specific version exist in ECR using the below code. But I am always getting "Image does not exist in ECR!" even when the image tag exist.

client = boto3.client('ecr')
response = client.list_images(registryId='my_account_number', repositoryName='my_app')

for i in response['imageIds']:
    if i['imageTag'] != version:
        print(response)
        print('Image does not exist in ECR!')
        quit()
    else:
        pass

Body:
Change your code to run until it finds the version you are expecting:

client = boto3.client('ecr')
response = client.list_images(registryId='my_account_number', repositoryName='my_app')

for i in response['imageIds']:
    if i['imageTag'] == version:
        print('Found matching version!')
        print(i)
        break
else:
    print('Image does not exist in ECR!')

If the correct version is not found, 'Image does not exist in ECR!' will be printed.


问:
Create product in Microsoft Dynamics 365 for Financials
I try to create a product (item) using OData V4 URL available in Web Services section in Microsoft Dynamics 365 for Financials as shown below.

I use Postman to execute the POST request. Each request is proceed with an authenticated and valid account.

The POST OData V4 URL is taken from the Web Services sections example: https://xyz.financials.dynamics.com:7048/MS/ODataV4/Company('my-company')/Items

I also tried the entity "Item_Card", same result.

Here is the config set in Postman:

Headers

Body

When I execute the request, I get the following error:

What is the missing "Data object"? Is this a standard of OData V4 protocol? Do I must supply a "Data object" into the body?

Is there anyone encountered that error and could explain what is missing/not working?

Update 2017-05-10

It seems that the REST endpoint is not available for Microsoft Dynamics Financials build < 16552. I currenly use build 16259.

Update 2017-05-23

I am now running on build 16552. I still get the same error. The update seems to have no effect on the POST request.

答:
I receive this error as well. In my case I was adding a vendor and I missed the NO. (this field is not on the interface'vendor card', but it appears in the listing and is mandatory in the service, however no documentation about it). So my guess you probable is missing a mandatory field.

PS:I used OData v4 Client Code Generator to generate my proxy from the metadata.


问:
Calling a controller function from onchange event in html view
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

```<code>@Html.DropDownList("selectList", Model.ReverseMonthsLists())
</code>```

View Model Code

```<code>public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}
</code>```

Controller function

```<code>    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }
</code>```

答:
You Can Use The OnChange EventHandler For The HTML Select Option
(The DropDownList ) To Start An Ajax Call To Your Controller , Simply Create a JavaScript Function That Preforms a Jquery Ajax Request Containing The User Selected Data To The Controller and Retrieve JSON From The Controller Using Return Json() Instead Of Return View() , Then Handle The Retrieved Data Using JavaScript , Your Controller Will Need To Accept a Parameter In Order To Receive The Data From The Ajax Request

Body:
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

@Html.DropDownList("selectList", Model.ReverseMonthsLists())

View Model Code

public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}

Controller function

    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }


问:
Entity Framework Inheritance
I have looked at several possible solutions to my issue but did not find the right one.

I need a full set, that is, I need to fetch the types that are also of a base type. i.e. the ActionHistory type, as well as all others, which inherit from the ActionHistory base class. My problem was that I was getting all entities but those of the ActionUpdate type did not have the ActionUpdateDetails collection filled.

My problem is that I am unable to retrieve the ActionUpdateDetails data within the derived ActionUpdate class.

There are three classes in the model:

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

public class ActionUpdate : ActionHistory
{
public ICollection<ActionUpdateDetail> ActionUpdateDetails{get;set;}
}

public class ActionUpdateDetail
{
int Id{get;set;}
public string Field{get;set;}
public string Value{get;set;}
}
</code>```

I tried implementing the solution from this suggestion:
Entity Framework: Inheritance and Include

Like this:

```<code>var result = from actionHistory in ActionHistories
select new {
actionHistory,
actionUpdateDetails = actionHistory is ActionUpdate ?
(actionHistory as ActionUpdate).ActionUpdateDetails : null
};
</code>```

All I get is the exception message:

Unable to create a constant value of type 'System.Collections.Generic.ICollection`1'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

Then I tried to simulate the situation outside the EF and it worked. I am using a POCO model and have extracted the involved classes into a separate project, filled the structure sample with data, and tested it with a success, i.e. ActionUpdateDetails collection was filled with the data.

Any help on this will be appreciated!

N.

答:
```<code>var result = from actionHistory in ActionHistories
select new
{
    actionHistory,
    ActionUpdateDetails = (actionHistory as ActionUpdate).ActionUpdateDetails
};
</code>```

ContentLicense: CC BY-SA 2.5

Title: Entity Framework Inheritance

Body:
I have looked at several possible solutions to my issue but did not find the right one.

I need a full set, that is, I need to fetch the types that are also of a base type. i.e. the ActionHistory type, as well as all others, which inherit from the ActionHistory base class. My problem was that I was getting all entities but those of the ActionUpdate type did not have the ActionUpdateDetails collection filled.

My problem is that I am unable to retrieve the ActionUpdateDetails data within the derived ActionUpdate class.

There are three classes in the model:

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

public class ActionUpdate : ActionHistory
{
public ICollection<ActionUpdateDetail> ActionUpdateDetails{get;set;}
}

public class ActionUpdateDetail
{
int Id{get;set;}
public string Field{get;set;}
public string Value{get;set;}
}

I tried implementing the solution from this suggestion:
Entity Framework: Inheritance and Include

Like this:

var result = from actionHistory in ActionHistories
select new {
actionHistory,
actionUpdateDetails = actionHistory is ActionUpdate ?
(actionHistory as ActionUpdate).ActionUpdateDetails : null
};

All I get is the exception message:

Unable to create a constant value of type 'System.Collections.Generic.ICollection`1'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

Then I tried to simulate the situation outside the EF and it worked. I am using a POCO model and have extracted the involved classes into a separate project, filled the structure sample with data, and tested it with a success, i.e. ActionUpdateDetails collection was filled with the data.

Any help on this will be appreciated!

N.


问:
C - int and malloc
Okay, I'm pretty new to those things. From what I've learned:

an int (signed int) is in range [−32,767; 32,767]

and a long long int (signed) is in range [-9,223,372,036,854,775,807; 9,223,372,036,854,775,807].

I also learnt that with malloc() function I can temporarily allocate memory for a variable.

I was thinking: if I use malloc() to allocate memory for a long long int, but with a larger size, can I store values bigger than 9,223,372,036,854,775,807 and smaller than -9,223,372,036,854,775,807?

答:
an int (signed int) is in range [−32,767; 32,767]
  and a long long int (signed) is in range [-9,223,372,036,854,775,807; 9,223,372,036,854,775,807].

Partially true.   Those are the minimum ranges that the standard requires an int and long long int to be able to represent.

The ranges are formally "implementation defined" i.e. fixed by the implementation (compiler, host system, standard library, etc), although they may vary between implementations.   An implementation is permitted, but not required, to support a larger range of values for both types.

I also learnt that with malloc() function I can temporarily allocate memory for a variable.

Also approximately true.

malloc() can be used to dynamically allocate memory, which will remain allocated until a corresponding call of free() or on program termination (assuming a modern operating system that releases memory resources on program termination).

I was thinking: if I use malloc() to allocate memory for a long long int, but with a larger size, can I store values bigger than
  9,223,372,036,854,775,807 and smaller than -9,223,372,036,854,775,807

This is an incorrect conclusion.

The size of all types (except char types, which are defined to have a size of 1) is also implementation-defined.

Yes, it is possible to allocate more memory using malloc().   But something like

```<code>int *p = malloc(2*sizeof(int));    /* assume the allocation succeeds */
</code>```

does not create a bigger int, and does not affect the range of values an int can represent.   It dynamically creates an array of TWO integers, which can be accessed as p[0] and p[1]  (or, equivalently, *p and *(p+1)) respectively.

Title: C - int and malloc

Body:
an int (signed int) is in range [−32,767; 32,767]
  and a long long int (signed) is in range [-9,223,372,036,854,775,807; 9,223,372,036,854,775,807].

Partially true.   Those are the minimum ranges that the standard requires an int and long long int to be able to represent.

The ranges are formally "implementation defined" i.e. fixed by the implementation (compiler, host system, standard library, etc), although they may vary between implementations.   An implementation is permitted, but not required, to support a larger range of values for both types.

I also learnt that with malloc() function I can temporarily allocate memory for a variable.

Also approximately true.

malloc() can be used to dynamically allocate memory, which will remain allocated until a corresponding call of free() or on program termination (assuming a modern operating system that releases memory resources on program termination).

I was thinking: if I use malloc() to allocate memory for a long long int, but with a larger size, can I store values bigger than
  9,223,372,036,854,775,807 and smaller than -9,223,372,036,854,775,807

This is an incorrect conclusion.

The size of all types (except char types, which are defined to have a size of 1) is also implementation-defined.

Yes, it is possible to allocate more memory using malloc().   But something like

int *p = malloc(2*sizeof(int));    /* assume the allocation succeeds */

does not create a bigger int, and does not affect the range of values an int can represent.   It dynamically creates an array of TWO integers, which can be accessed as p[0] and p[1]  (or, equivalently, *p and *(p+1)) respectively.


问:
Collapsing toolbar blur image when collapsed
i need some help with my toolbar.

Right now i use a collapsing toolbar with image wich collapsed when i scroll up.
I know i can use contentScrim to make the Toolbar transparent and therefore see the image as "toolbar background".

However, i want the image to blur(/fade) when the toolbar is collapsed.

Any suggestions how to achieve this?

答:
You can use this library. (RealTimeBlurView)

For the blur effect, just put the imageview behind the blurview.
To achieve what you want just change blurview's alpha when the app bar is scrolled.

```<code>appbar.addOnOffsetChangedListener(new OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {
        float offsetAlpha = (appBarLayout.getY() / appbar.getTotalScrollRange());
        blurView.setAlpha( 1 - (offsetAlpha * -1));
    }
});
</code>```

UPDATE

FastBlur

Here's another benchmarking project to showcase all the possible blurring methods in android.
 Just get the fastest algorithm from the demo and use it in your project.

Hope this helps!

Body:
You can use this library. (RealTimeBlurView)

For the blur effect, just put the imageview behind the blurview.
To achieve what you want just change blurview's alpha when the app bar is scrolled.

appbar.addOnOffsetChangedListener(new OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {
        float offsetAlpha = (appBarLayout.getY() / appbar.getTotalScrollRange());
        blurView.setAlpha( 1 - (offsetAlpha * -1));
    }
});

UPDATE

FastBlur

Here's another benchmarking project to showcase all the possible blurring methods in android.
 Just get the fastest algorithm from the demo and use it in your project.

Hope this helps!


问:
How to open and manipulate pictures fast and efficiently?
Recently I have tried my hand at machine learning with Tensorflow in Python, as my first project with both these products, to prepare for my next semester, but I have run into an issue regarding runtimes, and perhaps with my general understanding.

I want to create a program that:

Loads a picture (From a path)

Uses a loss function and gradient decent to turn all the pixels more green

Outputs the picture again.

The good news is I did manage to do just that:

```<code>import tensorflow as tf
import numpy as np
from PIL import Image
input = "pic.png"
output = "output.png"

file = Image.open(path)
picture = np.array(file, np.float16)
tenarray = tf.Variable(picture) #takes 20+ sec to run

greenPic = np.empty([len(picture[:, 1]), len(picture[1]), 3], dtype=np.float16)
greenPic[:, :, 1] = 250
comparisonPic = tf.Variable(greenPic) #takes 20+ sec to run

picComparison = tf.reduce_mean(-tf.reduce_sum(comparisonPic * tf.log(tenarray)))

rate = 0.05
trainingStep = tf.train.GradientDescentOptimizer(rate).minimize(picComparison)

with tf.Session() as sesh:
    sesh.run(tf.global_variables_initializer()) #Sets our variables, gets ready to run.
    for i in range(100):
        sesh.run(trainingStep)

resultArray = sesh.run(tenarray)

#Save picture
</code>```

Problem is, that code takes 45 secounds to run, which is basically 2*22 sec of idling and ~1 sec of actual computation.

I have made faster versions but they all fail to manipulate the picture, or refuse to compile.
Does anyone have a good idea how to do this, that is more efficient?

答:
I managed to solve this myself, so I will comment here if anyone happens to run into the same problem for some reason.

The problem was using tf.float16's instead of tf.float32's for the image tensors, changing this has made the code above run 50 times faster for me.

So:

```<code>picture = tf.Variable(np.asarray(file, np.float32), tf.float32)
...
comparisonPic = tf.Variable(np.asarray(greenPic), tf.float32)
</code>```

Body:
Recently I have tried my hand at machine learning with Tensorflow in Python, as my first project with both these products, to prepare for my next semester, but I have run into an issue regarding runtimes, and perhaps with my general understanding.

I want to create a program that:

Loads a picture (From a path)

Uses a loss function and gradient decent to turn all the pixels more green

Outputs the picture again.

The good news is I did manage to do just that:

import tensorflow as tf
import numpy as np
from PIL import Image
input = "pic.png"
output = "output.png"

file = Image.open(path)
picture = np.array(file, np.float16)
tenarray = tf.Variable(picture) #takes 20+ sec to run

greenPic = np.empty([len(picture[:, 1]), len(picture[1]), 3], dtype=np.float16)
greenPic[:, :, 1] = 250
comparisonPic = tf.Variable(greenPic) #takes 20+ sec to run

picComparison = tf.reduce_mean(-tf.reduce_sum(comparisonPic * tf.log(tenarray)))

rate = 0.05
trainingStep = tf.train.GradientDescentOptimizer(rate).minimize(picComparison)

with tf.Session() as sesh:
    sesh.run(tf.global_variables_initializer()) #Sets our variables, gets ready to run.
    for i in range(100):
        sesh.run(trainingStep)

resultArray = sesh.run(tenarray)

#Save picture

Problem is, that code takes 45 secounds to run, which is basically 2*22 sec of idling and ~1 sec of actual computation.

I have made faster versions but they all fail to manipulate the picture, or refuse to compile.
Does anyone have a good idea how to do this, that is more efficient?

Body:
I managed to solve this myself, so I will comment here if anyone happens to run into the same problem for some reason.

The problem was using tf.float16's instead of tf.float32's for the image tensors, changing this has made the code above run 50 times faster for me.

So:

picture = tf.Variable(np.asarray(file, np.float32), tf.float32)
...
comparisonPic = tf.Variable(np.asarray(greenPic), tf.float32)


问:
SQL Join two tables with same column names, and get sum of each column
I know that in the long run... the column names being the same is probably irrelevant.  But here's what I've got:

Master Table:

```<code>| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  100 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |   20 |
</code>```

Supplemental Table

```<code>| PersonID |   1972 |   1973 |
|----------|--------|--------|
|        1 |    100 | (null) |
|        2 | (null) | (null) |
|        3 | (null) |    200 |
</code>```

I'd like to have a table (a view, actually) that will join these two tables, and add the sum of the columns into a column with the same name

Combined Table:

```<code>| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  200 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |  220 |
</code>```

The resulting table needs to have both tables combined..  The years go all the way to 2017, and are the same name for each table.

SQLfiddle

答:
Unless you choose to use dynamic SQL (generally best to avoid to prevent SQL injection, bugs, and negative performance impacts), the column names being equivalent doesn't give us any shortcuts here.

The canonical way to do this would be to sum each column explicitly:

```<code>SELECT mt.PersonID, COALESCE(mt.[1970], 0) + COALESCE(st.[1970], 0), COALESCE(mt.[1971], 0) + COALESCE(st.[1971], 0), ... COALESCE(mt.[2017], 0) + COALESCE(st.[2017], 0)
FROM MasterTable mt
LEFT JOIN SupplementalTable st
    ON mt.PersonID = st.PersonID;
</code>```

However, this sucks with 40 columns (and it sounds like possibly more in the future). Dynamic SQL is generally best to avoid, but sometimes it's still the best tool for the job. Here's how you could solve the same problem with dynamic SQL:

```<code>DECLARE @dynamicSql NVARCHAR(MAX);
DECLARE @selectList NVARCHAR(MAX);

SELECT @selectList = COALESCE(@selectList + ', ', '') + 'COALESCE(mt.[' + mtColumns.COLUMN_NAME + '], 0)' + COALESCE(' + COALESCE(st.[' + stColumns.COLUMN_NAME + '], 0)', '')
FROM INFORMATION_SCHEMA.COLUMNS mtColumns
LEFT JOIN INFORMATION_SCHEMA.COLUMNS stColumns ON mtColumns.COLUMN_NAME = stColumns.COLUMN_NAME
WHERE mtColumns.TABLE_NAME = 'MasterTable'
      AND stColumns.TABLE_NAME = 'SupplementaryTable';

SET @dynamicSql = 'SELECT ' + @selectList + ' FROM MasterTable mt INNER JOIN SupplementaryTable st ON mt.PersonID = st.PersonID;';

EXECUTE sp_executesql @dynamicSql;
</code>```

I haven't generated the actual tables to test this, but it should be fairly close. The query should generate a list of SELECT field sums for each field and then run it. It should also skip non-existent fields in SupplementaryTable, and it will only operate for fields that do exist in MasterTable.

Using an ORM (like Hibernate) can do a great deal towards mitigating potential bugs or SQL injection vulnerabilities by validating column names ahead of time.

Body:
I know that in the long run... the column names being the same is probably irrelevant.  But here's what I've got:

Master Table:

| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  100 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |   20 |

Supplemental Table

| PersonID |   1972 |   1973 |
|----------|--------|--------|
|        1 |    100 | (null) |
|        2 | (null) | (null) |
|        3 | (null) |    200 |

I'd like to have a table (a view, actually) that will join these two tables, and add the sum of the columns into a column with the same name

Combined Table:

| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  200 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |  220 |

The resulting table needs to have both tables combined..  The years go all the way to 2017, and are the same name for each table.

SQLfiddle

Body:
Unless you choose to use dynamic SQL (generally best to avoid to prevent SQL injection, bugs, and negative performance impacts), the column names being equivalent doesn't give us any shortcuts here.

The canonical way to do this would be to sum each column explicitly:

SELECT mt.PersonID, COALESCE(mt.[1970], 0) + COALESCE(st.[1970], 0), COALESCE(mt.[1971], 0) + COALESCE(st.[1971], 0), ... COALESCE(mt.[2017], 0) + COALESCE(st.[2017], 0)
FROM MasterTable mt
LEFT JOIN SupplementalTable st
    ON mt.PersonID = st.PersonID;

However, this sucks with 40 columns (and it sounds like possibly more in the future). Dynamic SQL is generally best to avoid, but sometimes it's still the best tool for the job. Here's how you could solve the same problem with dynamic SQL:

DECLARE @dynamicSql NVARCHAR(MAX);
DECLARE @selectList NVARCHAR(MAX);

SELECT @selectList = COALESCE(@selectList + ', ', '') + 'COALESCE(mt.[' + mtColumns.COLUMN_NAME + '], 0)' + COALESCE(' + COALESCE(st.[' + stColumns.COLUMN_NAME + '], 0)', '')
FROM INFORMATION_SCHEMA.COLUMNS mtColumns
LEFT JOIN INFORMATION_SCHEMA.COLUMNS stColumns ON mtColumns.COLUMN_NAME = stColumns.COLUMN_NAME
WHERE mtColumns.TABLE_NAME = 'MasterTable'
      AND stColumns.TABLE_NAME = 'SupplementaryTable';

SET @dynamicSql = 'SELECT ' + @selectList + ' FROM MasterTable mt INNER JOIN SupplementaryTable st ON mt.PersonID = st.PersonID;';

EXECUTE sp_executesql @dynamicSql;

I haven't generated the actual tables to test this, but it should be fairly close. The query should generate a list of SELECT field sums for each field and then run it. It should also skip non-existent fields in SupplementaryTable, and it will only operate for fields that do exist in MasterTable.

Using an ORM (like Hibernate) can do a great deal towards mitigating potential bugs or SQL injection vulnerabilities by validating column names ahead of time.


问:
Jenkins - Pipeline access git branch name
Question: Is there any way to get the name of the branch that is checkout by the Pipeline in a jenkinsfile?

NOTE: I am not in a Multibranch Pipeline!

In my pipeline im using

```<code>checkout([$class: 'GitSCM',
          userRemoteConfigs: [[url:'https://github.com/repo',
                               credentialsId: 'xxxx',name: '1234']]])
</code>```

where name is the commit ID. I need to verify that this commit id is from the branch that a user has specified as parameter (user specifies both branch name and commit id and I need to check if there is no error before building the project).

Why is the branch name not exposed in Pipeline but only in Multibranch Pipeline? Doesn't make sense to me.

There are three reasons why I don't want to convert to the multi branch pipeline:

I am using another plugin Build Blocker Plugin in my pipeline that doesn't seem available in the multibranch pipeline.

I have a parameterized pipeline, I don't see that option in the multibranch pipeline.

A lot of time has gone into this pipeline, I simply don't want to set up this project again from scratch just for this branch name feature.

I have printed out all environment variables, branch name is not among them.

Thanks for the help!

答:
See Pipeline: Nodes and Processes, sh: Shell Script :

returnStdout (optional)

If checked, standard output from the task is returned as the step value as a String, rather than being printed to the build log. (Standard error, if any, will still be printed to the log.) You will often want to call .trim() on the result to strip off a trailing newline.

and see git-branch:

--contains [<commit>]

      Only list branches which contain the specified commit (HEAD if not specified). Implies --list.

Combine these with:

```<code>...
def branches = sh(returnStdout: true, script: "git branch --contains ${commitId}")
...
</code>```

and check whether branches contains the branch name given by the user.

BTW, I'd rename your variables since:

name is your commit ID, a.k.a. (commit) hash, so I'd call it commitId or commitHash

you actually have some other thing with a name, the branch, which can be called branchName then to make future maintainers' lifes easier

Body:
Question: Is there any way to get the name of the branch that is checkout by the Pipeline in a jenkinsfile?

NOTE: I am not in a Multibranch Pipeline!

In my pipeline im using

checkout([$class: 'GitSCM',
          userRemoteConfigs: [[url:'https://github.com/repo',
                               credentialsId: 'xxxx',name: '1234']]])

where name is the commit ID. I need to verify that this commit id is from the branch that a user has specified as parameter (user specifies both branch name and commit id and I need to check if there is no error before building the project).

Why is the branch name not exposed in Pipeline but only in Multibranch Pipeline? Doesn't make sense to me.

There are three reasons why I don't want to convert to the multi branch pipeline:

I am using another plugin Build Blocker Plugin in my pipeline that doesn't seem available in the multibranch pipeline.

I have a parameterized pipeline, I don't see that option in the multibranch pipeline.

A lot of time has gone into this pipeline, I simply don't want to set up this project again from scratch just for this branch name feature.

I have printed out all environment variables, branch name is not among them.

Thanks for the help!

Body:
See Pipeline: Nodes and Processes, sh: Shell Script :

returnStdout (optional)

If checked, standard output from the task is returned as the step value as a String, rather than being printed to the build log. (Standard error, if any, will still be printed to the log.) You will often want to call .trim() on the result to strip off a trailing newline.

and see git-branch:

--contains [<commit>]

      Only list branches which contain the specified commit (HEAD if not specified). Implies --list.

Combine these with:

...
def branches = sh(returnStdout: true, script: "git branch --contains ${commitId}")
...

and check whether branches contains the branch name given by the user.

BTW, I'd rename your variables since:

name is your commit ID, a.k.a. (commit) hash, so I'd call it commitId or commitHash

you actually have some other thing with a name, the branch, which can be called branchName then to make future maintainers' lifes easier


问:
Querydsl - Could not determine data type for searched case statement
This question was sort-of answered a couple of years ago (with a similar title), but I am struggling mightily with it.  It seems that no matter what expression I put in the then() predicate, I keep getting a Hibernate error:

Could not determine data type for searched case statement

Basically here is a simplified code segment that is causing the issue:

```<code>SimpleExpression<String> adjustmentFlag =
        new CaseBuilder()
                .when(myObject.id.isNotNull())
                .then(Expressions.asString("true"))
                .otherwise(Expressions.asString("false"));
</code>```

When I use it in a simple select statment, the specific error I get is this:

Caused by: org.hibernate.QueryException: Could not determine data type for searched case statement [ select ...stuff...,  (case when (myObject.id is not null) then ?2 else ?3 end) from ....table list... ]

No matter what I put into the then() or otherwise() methods, nothing seems to work.  From other posts, they talk about using Expressions - I've tried all kinds, and come up with the same error each time.

Anyone else having issues like this?  It seems this would be such a common problem, but I'm stumped as to how to proceed next.  Any help would be appreciated.

Using Querydsl 4.1.3, Hibernate 5.0.10

Thanks!

答: Never mind - figured it out.  It actually wasn't the expressions in the then() or otherwise() methods - it was the literals I was using in the when() condition.  I changed them to use Expressions. and it is now working.</p>

Body:
This question was sort-of answered a couple of years ago (with a similar title), but I am struggling mightily with it.  It seems that no matter what expression I put in the then() predicate, I keep getting a Hibernate error:

Could not determine data type for searched case statement

Basically here is a simplified code segment that is causing the issue:

SimpleExpression<String> adjustmentFlag =
        new CaseBuilder()
                .when(myObject.id.isNotNull())
                .then(Expressions.asString("true"))
                .otherwise(Expressions.asString("false"));

When I use it in a simple select statment, the specific error I get is this:

Caused by: org.hibernate.QueryException: Could not determine data type for searched case statement [ select ...stuff...,  (case when (myObject.id is not null) then ?2 else ?3 end) from ....table list... ]

No matter what I put into the then() or otherwise() methods, nothing seems to work.  From other posts, they talk about using Expressions - I've tried all kinds, and come up with the same error each time.

Anyone else having issues like this?  It seems this would be such a common problem, but I'm stumped as to how to proceed next.  Any help would be appreciated.

Using Querydsl 4.1.3, Hibernate 5.0.10

Thanks!


问:
Which is the better way to insert HTML tags into PHP code?
I see two methods but I don't know which is better, should I insert a div tag like this :

```<code>echo "<div>";
</code>```

or like this ?

```<code>?> <div> <?php
</code>```

答:
There's no right answer to this.

When displaying a lot of HTML, I normally use ?>
 <?php. This is especially true for when looping over data from a database, I would use:

```<code><?php while ($row == $query->fetchObject() ) : ?>
  <div class="row-<?php echo $row->id ?>">
     //Some more of the data
  </div>
<? endwhile; ?>
</code>```

However, displaying only a little, I normally just echo it.

```<code><?php echo "Hello, my name is <strong>Joe Doe<strong>"; ?>
</code>```

I would encourage you to play with it and find what you like best.

Body:
I see two methods but I don't know which is better, should I insert a div tag like this :

echo "
";

or like this ?

?>
 <?php

Body:
There's no right answer to this.

When displaying a lot of HTML, I normally use ?> <div> <?php. This is especially true for when looping over data from a database, I would use:

<?php while ($row == $query->fetchObject() ) : ?>
  <div class="row-<?php echo $row->id ?>">
     //Some more of the data
  </div>
<? endwhile; ?>

However, displaying only a little, I normally just echo it.

<?php echo "Hello, my name is <strong>Joe Doe<strong>"; ?>

I would encourage you to play with it and find what you like best.


问:
Running javascript after page is fully rendered
I am trying to create a syntax highlighter script. I tried using my script on a code with 10 thousand lines, and all I see is a blank page while it is loading. Everything will just show up after the script has finished its task. By the way, I called my script inside the ready function of jQuery.

```<code>$(myFunction);
</code>```

The script should execute after the page is fully rendered, and the user can actually navigate through the page even if the script is not yet finished. The javascript will run in the background as it highlights the code one by one while not interfering with the responsiveness of the page. Thanks in advance.

EDIT:

To make this clearer, I would like to execute the code after everything is "rendered," not "loaded". Everything should already be visible in the screen and the user can actually see the code come to life as it is being highlighted. Thanks.

答:
Problem with window.onload approaches

Even if you use the $(window).load approach, your highlighter stuff could get run prior to something from $(document).ready completing, since there may be lots of asynchronous callback functions all over the place.

My approach

I use a combination of waiting for document.readyState == 'complete and setTimeout. The idea is that I want to wait until the page is fully rendered (hence the 'complete') and then further ensure that the $(document).ready JQuery wrapper content has completed (hence the setTimeout).

Here's how I would solve your problem, assuming that 200 milliseconds is ample time for everything inside $(document).ready(function(){ /*...*/ }); to complete.

```<code>function highlighterAction() {
    // actually do the highlighting stuff here
}

function highlighter() {
    /*
      The short pause allows any required callback functions
      to execute before actually highlighting, and allows
      the JQuery $(document).ready wrapper to finish.
     */
    setTimeout(function() {
        highlighterAction();
    }, 200);
}

/*
  Only trigger the highlighter after document fully loaded.  This is
  necessary for cases where page load takes a significant length
  of time to fully load.
*/
if (document.readyState == 'complete') {
    highlighter();
} else {
    document.onreadystatechange = function () {
        if (document.readyState === "complete") {
            highlighter();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a syntax highlighter script. I tried using my script on a code with 10 thousand lines, and all I see is a blank page while it is loading. Everything will just show up after the script has finished its task. By the way, I called my script inside the ready function of jQuery.

$(myFunction);

The script should execute after the page is fully rendered, and the user can actually navigate through the page even if the script is not yet finished. The javascript will run in the background as it highlights the code one by one while not interfering with the responsiveness of the page. Thanks in advance.

EDIT:

To make this clearer, I would like to execute the code after everything is "rendered," not "loaded". Everything should already be visible in the screen and the user can actually see the code come to life as it is being highlighted. Thanks.

Body:
Problem with window.onload approaches

Even if you use the $(window).load approach, your highlighter stuff could get run prior to something from $(document).ready completing, since there may be lots of asynchronous callback functions all over the place.

My approach

I use a combination of waiting for document.readyState == 'complete and setTimeout. The idea is that I want to wait until the page is fully rendered (hence the 'complete') and then further ensure that the $(document).ready JQuery wrapper content has completed (hence the setTimeout).

Here's how I would solve your problem, assuming that 200 milliseconds is ample time for everything inside $(document).ready(function(){ /*...*/ }); to complete.

function highlighterAction() {
    // actually do the highlighting stuff here
}

function highlighter() {
    /*
      The short pause allows any required callback functions
      to execute before actually highlighting, and allows
      the JQuery $(document).ready wrapper to finish.
     */
    setTimeout(function() {
        highlighterAction();
    }, 200);
}

/*
  Only trigger the highlighter after document fully loaded.  This is
  necessary for cases where page load takes a significant length
  of time to fully load.
*/
if (document.readyState == 'complete') {
    highlighter();
} else {
    document.onreadystatechange = function () {
        if (document.readyState === "complete") {
            highlighter();
        }
    }
}


问:
Can't run program because it asks me to attach on process
I'm new to C# Programming, and instead of just letting me run the code by pressing F5, "Attach..." appears where the Run button should be and it won't let me run the code.
This has happened me twice by now and I don't know how to make the "Run" button appear again, because I can't test any program I write.</p>

答: Go to %appdata% and delete the Visual Studio folder, this will reset Visual Studio and fix this error.


问:
How to put underline under button name
I have button with name "itemname", and now I want to put underline just under character "i" in "itemname", but I don't know how I should do this. Could anyone please tell me how?</p>

答:
You should add an "&" to left of the letter you want to underline.
So, a button with text "&itemname" will have the "i" underlined.</p>

Title: How to put underline under button name


问:
Typescript: "X" is not assignable to type, types of property "Y" are incompatible
Note: I am quite new to Angular2 and typescript, so I am sorry for my ignorance.

The issue:
What I'm trying to do is to subtract a start date/time from the end date/time then use that in a formula for my calculation to display as "calc". The problem is that I can give calc a static number which works, but if I try to use the math formula it gives all kinds of errors when transpiling:

1
  mock-orders.ts(4,14): error TS2322: Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order[]'.

Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order'.

Types of property 'checks' are incompatible.

Type 'string' is not assignable to type 'number'.

Below is the child component where I'm having these issues.
See line 28 this.calc:

```<code>     // order.ts
import { Component, OnInit } from '@angular/core';

export class Order {
    order_no: string;
    scheduled: string;
    lateral: string;
    start_time: string;
    checks: number;
    stop_time: string;
    status: string;
    approx_cfs: string;
    approx_hrs: string;
    approx_af: string;
    calc: number;

    constructor(data: {} = {}) {
    this.order_no = data["order_no"] || "";
    this.scheduled = data["scheduled"] || "";
    this.lateral = data["lateral"] || "";
    this.start_time = data["start_time"] || "";
    this.checks = data["checks"] || "";
    this.stop_time = data["stop_time"] || "";
    this.status = data["status"] || "";
    this.approx_cfs = data["approx_cfs"] || "";
    this.approx_hrs = data["approx_hrs"] || "";
    this.approx_af = data["approx_af"] || "";
    this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825);

    console.log(this.calc);
    };

};
</code>```

Part of the issue, I'm sure, is that I'm trying to use math operations on dates, then assign the result to a number type.

The following call this component for use in the service:

```<code>// order.service.ts
import { Injectable } from '@angular/core';

import { Order } from './order';
import { ORDERS } from './mock-orders';

@Injectable()
export class OrderService {
  getOrders(): Promise<Order[]> {
    return Promise.resolve(ORDERS);
  }
}
</code>```

The following file is the data arrays pulled each time the service runs, to depict what will be received from the database.

```<code>// mock-orders.ts
import { Order } from './order'

export const ORDERS: Order[] = [
    {order_no: '12345',
    scheduled: '08/16/16 13:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/16/16 15:45',
    checks: '23.25',
    stop_time: '08/17/16 15:30',
    status: 'Delivered',
    approx_cfs: '25.00',
    approx_hrs: '22',
    approx_af: '45.38',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    }
];
</code>```

答:
since Date.parse() first tries to cast the input into number and then get the equivalent date out of it, and in js casting strings with characters other than number like '-' or '/' will cause in NaN result the Date.parse will also return NaN. You can use new Date(str: String) in this case to make a date object from a valid date string. you can also use getTime() function for mathematical operations on dates.

let data = {
  order_no: '12346',
  scheduled: '08/17/16 11:45',
  lateral: 'L1-8-1-T7, L1-8-1-T6',
  start_time: '08/17/16 15:30',
  checks: '20.25',
  stop_time: '',
  status: 'Running',
  approx_cfs: '25.00',
  approx_hrs: '10',
  approx_af: '20.63',
 };
this.order_no = data["order_no"] || "";
this.scheduled = data["scheduled"] || "";
this.lateral = data["lateral"] || "";
this.start_time = data["start_time"] || "";
this.checks = data["checks"] || "";
this.stop_time = data["stop_time"] || "";
this.status = data["status"] || "";
this.approx_cfs = data["approx_cfs"] || "";
this.approx_hrs = data["approx_hrs"] || "";
this.approx_af = data["approx_af"] || "";
this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825);

console.log(calc);```

Body:
Note: I am quite new to Angular2 and typescript, so I am sorry for my ignorance.

The issue:
What I'm trying to do is to subtract a start date/time from the end date/time then use that in a formula for my calculation to display as "calc". The problem is that I can give calc a static number which works, but if I try to use the math formula it gives all kinds of errors when transpiling:

1
  mock-orders.ts(4,14): error TS2322: Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order[]'.

Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order'.

Types of property 'checks' are incompatible.

Type 'string' is not assignable to type 'number'.

Below is the child component where I'm having these issues.
See line 28 this.calc:

     // order.ts
import { Component, OnInit } from '@angular/core';

export class Order {
    order_no: string;
    scheduled: string;
    lateral: string;
    start_time: string;
    checks: number;
    stop_time: string;
    status: string;
    approx_cfs: string;
    approx_hrs: string;
    approx_af: string;
    calc: number;

    constructor(data: {} = {}) {
    this.order_no = data["order_no"] || "";
    this.scheduled = data["scheduled"] || "";
    this.lateral = data["lateral"] || "";
    this.start_time = data["start_time"] || "";
    this.checks = data["checks"] || "";
    this.stop_time = data["stop_time"] || "";
    this.status = data["status"] || "";
    this.approx_cfs = data["approx_cfs"] || "";
    this.approx_hrs = data["approx_hrs"] || "";
    this.approx_af = data["approx_af"] || "";
    this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825);

    console.log(this.calc);
    };

};

Part of the issue, I'm sure, is that I'm trying to use math operations on dates, then assign the result to a number type.

The following call this component for use in the service:

// order.service.ts
import { Injectable } from '@angular/core';

import { Order } from './order';
import { ORDERS } from './mock-orders';

@Injectable()
export class OrderService {
  getOrders(): Promise<Order[]> {
    return Promise.resolve(ORDERS);
  }
}

The following file is the data arrays pulled each time the service runs, to depict what will be received from the database.

// mock-orders.ts
import { Order } from './order'

export const ORDERS: Order[] = [
    {order_no: '12345',
    scheduled: '08/16/16 13:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/16/16 15:45',
    checks: '23.25',
    stop_time: '08/17/16 15:30',
    status: 'Delivered',
    approx_cfs: '25.00',
    approx_hrs: '22',
    approx_af: '45.38',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    }
];


问:
In a plot, how do I rename an axis values into a new value or string in r?
In a plot, how do I rename an axis value into a new value or string in r?

I have this simple data.frame and plot:

```<code>#rm(list=ls(all=TRUE))
x <- c(1,2,2.5,1.5)
y <- c(1,3,4,2.5)
mydata <- data.frame(x, y)
plot(x,y)
</code>```

which gives the following plot

In the Y-axis, for example, how would I change the value 1 into X, value 1.5 into Y, value 2 in Z, etc..

Thanks.

答:
suppress the axis labels first (with yaxt = "n" for example, Read more at ?par) and then write your own axis (See ?axis)

```<code>x <- c(1,2,2.5,1.5)
y <- c(1,3,4,2.5)
mydata <- data.frame(x, y)
plot(x,y, yaxt = "n")
axis(side = 2, at = c(1, 1.5, 2, 2.5, 3, 3.5, 4), labels = c(letters[1:7]))
</code>```

Body:
In a plot, how do I rename an axis value into a new value or string in r?

I have this simple data.frame and plot:

#rm(list=ls(all=TRUE))
x <- c(1,2,2.5,1.5)
y <- c(1,3,4,2.5)
mydata <- data.frame(x, y)
plot(x,y)

which gives the following plot

In the Y-axis, for example, how would I change the value 1 into X, value 1.5 into Y, value 2 in Z, etc..

Thanks.

Body:
suppress the axis labels first (with yaxt = "n" for example, Read more at ?par) and then write your own axis (See ?axis)

x <- c(1,2,2.5,1.5)
y <- c(1,3,4,2.5)
mydata <- data.frame(x, y)
plot(x,y, yaxt = "n")
axis(side = 2, at = c(1, 1.5, 2, 2.5, 3, 3.5, 4), labels = c(letters[1:7]))


问:
Accessing widgets inside QStackedWidget
I am developing a Qt app with QtDesigner.

Previously it was quite easy to access specific widgets to do something with them like connecting signals. After I added QStackedWidget I can no longer access specific widgets with something like ui->stack->page1->widget.

Is there a way to do it somehow? Or should I always call findChild method? Or maybe it is possible to at least assign some of the nested widgets in stack widget to properties of the main windwo class?

答:
QStackedWidget provides a method to get child widgets by index, as well as the current widget.

A quick example is as follows:

MOCed Header

```<code>class MyWidget: QWidget
{
    Q_OBJECT

public:
    using QWidget::QWidget

    QWidget *ptr;
};
</code>```

Source File

```<code>QStackedWidget *stackedWidget = new QStackedWidget;
stackedWidget->addWidget(new MyWidget);     // index 0
stackedWidget->addWidget(new QWidget);      // index 1
stackedWidget->addWidget(new MyWidget);     // index 2

QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(stackedWidget);
setLayout(layout);

// do something specific with the first widget's ptr element
auto* widget = stackedWidget->widget(0);
auto* mywidget = qobject_cast<MyWidget*>(widget);
if (mywidget) {
    mywidget->ptr->setObjectName("FirstPage");
}
</code>```

Now, Qt uses virtual interfaces by default, so if you have a custom subwidget you need to extract, you can use qobject_cast. qobject_cast is basically a fast dynamic_cast, and works even without RTTI. In template-driven code, dynamic_cast is a bit of a code-smell: it means you lost useful type information too early. With virtual interfaces, the exact opposite is true: you should use qobject_cast as needed.

Title: Accessing widgets inside QStackedWidget

Body:
QStackedWidget provides a method to get child widgets by index, as well as the current widget.

A quick example is as follows:

MOCed Header

class MyWidget: QWidget
{
    Q_OBJECT

public:
    using QWidget::QWidget

    QWidget *ptr;
};

Source File

QStackedWidget *stackedWidget = new QStackedWidget;
stackedWidget->addWidget(new MyWidget);     // index 0
stackedWidget->addWidget(new QWidget);      // index 1
stackedWidget->addWidget(new MyWidget);     // index 2

QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(stackedWidget);
setLayout(layout);

// do something specific with the first widget's ptr element
auto* widget = stackedWidget->widget(0);
auto* mywidget = qobject_cast<MyWidget*>(widget);
if (mywidget) {
    mywidget->ptr->setObjectName("FirstPage");
}

Now, Qt uses virtual interfaces by default, so if you have a custom subwidget you need to extract, you can use qobject_cast. qobject_cast is basically a fast dynamic_cast, and works even without RTTI. In template-driven code, dynamic_cast is a bit of a code-smell: it means you lost useful type information too early. With virtual interfaces, the exact opposite is true: you should use qobject_cast as needed.


问:
JavaScript. Creating a dynamic table based on a user input
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?</p>

```<code><!DOCTYPE HTML>

<html>
<head>
<title>jsLoopDemo</title>

<!--
Honor Code: I acknowledge that this code represents my own work: CC
Date:  July 6, 2017
-->

<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />

<script type="text/javascript">

    do{
       var numChose = prompt("Please enter an interger greater than zero.");
    }while (isNaN(numChose) || numChose % 1 !== 0 || numChose < 1 );

    function genTable(numChose)
    {
        var table = document.createElement("TABLE");
        var tableBody = document.createElement("TBODY");
        table.appendChild(tableBody);
        var myTableDiv = document.getElementById("mytable");

        for (var r = 0; r <= numChose; r++)
            {
                var tr = document.createElement("TR");
                tableBody.appendChild(tr);
                var td = document.createElement("TD");
                tr.appendChild(td);
                td.appendChild(document.createTextNode("Row " + r));
            }
     myTableDiv.appendChild(table);
    }

</script>

</head>

<body>

<div id="mytable">
</div>

</body>
</html>
</code>```

答:
Two things:

You need to actually call the function after the prompt, so you need to add a line after your do while:

```<code>genTable(numChose);
</code>```

That still won't work, since the DOM will not be ready (myTableDiv will be undefined), so you need to wrap your entire code in an event listener:

```<code>document.addEventListener("DOMContentLoaded", function(event) {
    //do work
});
</code>```

Body:
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?

<!DOCTYPE HTML>

<title>jsLoopDemo</title>

<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />

Body:
Two things:

You need to actually call the function after the prompt, so you need to add a line after your do while:

genTable(numChose);

That still won't work, since the DOM will not be ready (myTableDiv will be undefined), so you need to wrap your entire code in an event listener:

document.addEventListener("DOMContentLoaded", function(event) {
    //do work
});


问:
Magento rewrite headaches
Just need a bit of advice. i have just finish building a site, i have turned on the Web Server Rewrites in the backend to get rid of the index.php

But when i go to the frontend it keeps giving me 404 errors

I cant seem to figure it out ... Is there anything else i need to do?

Cheers

答: Enable mod rewrite logging , regenerate your indexes</p>

Title: Magento rewrite headaches


问:
Proguard enabling for only single java file- Android
I want to apply proguard tool only for a single class file from project which also contains other libraries.
So how can i achieve this.
Any kind of help will be appreciated.</p>

答:
ProGuard tries trim/obfuscate everything unless it's explicitly kept by a rule, so the trick you're looking for is create a rule that tells it to keep everything except for a particular class:

```<code>-keep class !com.yourpackage.example.class { *; }
</code>```

This definitely provides what you asked for but I'm also wondering if that'd be useful in the first place. ProGuard doesn't just provide code obfuscation - it also removed unused code to make the APK smaller, so we should always try to apply it to as many things as we can.

Body:
ProGuard tries trim/obfuscate everything unless it's explicitly kept by a rule, so the trick you're looking for is create a rule that tells it to keep everything except for a particular class:

-keep class !com.yourpackage.example.class { *; }

This definitely provides what you asked for but I'm also wondering if that'd be useful in the first place. ProGuard doesn't just provide code obfuscation - it also removed unused code to make the APK smaller, so we should always try to apply it to as many things as we can.


问:
Moving average over time series
I need help to get the mean of the variables E, N and Z, by 7 days per ID.

The data frame is 290512 x 5 which head looks like the following:

```<code>ID  Date        E           N       Z
1   2012-03-16  676620.5    4090699 26.827
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.827
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.828
</code>```

Statments:

ID <- 1:21;

Date from 2012-03-16 to 2016-12-31, without continuity (no NA's);

n. obs of E = N = Z;

The #obs can be different for each point.

E.g., If I get E for ID = 5, I also get N and Z on this obsertavion, but at the same time I cannot get an obs to ID = 12. This data is from soil deformation and over the soil mass are settled some total station targets.

My solution so far is

```<code>df_dm <- df %>%
group_by(ID, Date) %>%
summarise(E_dm = mean(E),
          N_dm = mean(N),
          Z_dm = mean(Z))
</code>```

to get the daily means and then,

```<code>m <- 7
df_wm <- sapply(df_dm, function(x) rollapply( x, width = m, by = m, align = "left", FUN = mean))
</code>```

which comes from an answer to a moving average question.

答:
Your example data only has a single date. Do you want to calculate the mean by separate windows of 7 days (for example, by week)? If so, you can create a new column, Week with a unique identifier for each week, and use that to group by rather than Date.

Alternatively, you might want to take a rolling average. Look to the function rollmean in the zoo package. For example:

```<code>x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-"))
x <- zoo(rnorm(12), x.Date)

rollmean(x, 3)

 2004-01-17  2004-01-23  2004-01-26  2004-02-07  2004-02-18  2004-02-24  2004-03-20  2004-03-27
 0.60112115  0.80818151  0.64316904  0.06831874 -0.03085218 -0.05787362  0.34177806 -0.40876877
</code>```

Title: Moving average over time series

Body:
I need help to get the mean of the variables E, N and Z, by 7 days per ID.

The data frame is 290512 x 5 which head looks like the following:

ID  Date        E           N       Z
1   2012-03-16  676620.5    4090699 26.827
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.827
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.828
1   2012-03-16  676620.5    4090699 26.828

Statments:

ID <- 1:21;

Date from 2012-03-16 to 2016-12-31, without continuity (no NA's);

n. obs of E = N = Z;

The #obs can be different for each point.

E.g., If I get E for ID = 5, I also get N and Z on this obsertavion, but at the same time I cannot get an obs to ID = 12. This data is from soil deformation and over the soil mass are settled some total station targets.

My solution so far is

df_dm <- df %>%
group_by(ID, Date) %>%
summarise(E_dm = mean(E),
          N_dm = mean(N),
          Z_dm = mean(Z))

to get the daily means and then,

m <- 7
df_wm <- sapply(df_dm, function(x) rollapply( x, width = m, by = m, align = "left", FUN = mean))

which comes from an answer to a moving average question.

Body:
Your example data only has a single date. Do you want to calculate the mean by separate windows of 7 days (for example, by week)? If so, you can create a new column, Week with a unique identifier for each week, and use that to group by rather than Date.

Alternatively, you might want to take a rolling average. Look to the function rollmean in the zoo package. For example:

x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-"))
x <- zoo(rnorm(12), x.Date)

rollmean(x, 3)

 2004-01-17  2004-01-23  2004-01-26  2004-02-07  2004-02-18  2004-02-24  2004-03-20  2004-03-27
 0.60112115  0.80818151  0.64316904  0.06831874 -0.03085218 -0.05787362  0.34177806 -0.40876877


问:
Javascript check dropdown value against textbox
I need to check textbox value against dropdown list, and if that value does not exist, add to the list.

I have this script:

```<code>            <select id="drop" onchange="ChooseContact(this)">
              <option value="Volvo Red">Volvo Red</option>
              <option value="Mers Blue">Mers Blue</option>
              <option value="Ferr red">Ferr red</option>
            </select>

function execute(data) {
    var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
        if ( document.createElement('option').value != txtbox ) {
            var categories = document.getElementById("drop");
            var newOption = document.createElement('option');
            newOption.innerText = txtbox ;
            newOption.setAttribute('value', txtbox );
            categories.appendChild(newOption);
        }
    document.getElementById("drop").value = txtbox ;
}
</code>```

But the new item is still created in the dropdown list, eventhough such item already there. Thanks.

答:
On your "if" sentence you are creating a new element "option" so always is going to be different your "value", so always is going to create a new element inside your "select" tag
You need to iterate for the elements of your "select" tag to find if its value exist or not</p>

Body:
I need to check textbox value against dropdown list, and if that value does not exist, add to the list.

I have this script:

            <select id="drop" onchange="ChooseContact(this)">
              <option value="Volvo Red">Volvo Red</option>
              <option value="Mers Blue">Mers Blue</option>
              <option value="Ferr red">Ferr red</option>
            </select>

function execute(data) {
    var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
        if ( document.createElement('option').value != txtbox ) {
            var categories = document.getElementById("drop");
            var newOption = document.createElement('option');
            newOption.innerText = txtbox ;
            newOption.setAttribute('value', txtbox );
            categories.appendChild(newOption);
        }
    document.getElementById("drop").value = txtbox ;
}

But the new item is still created in the dropdown list, eventhough such item already there. Thanks.


问:
Including images in survey monkey
I am trying to include an image as a survey question and it gives be the below error,

surveymonty.exceptions.SurveyMontyAPIError: {"error": {"docs": "https://developer.surveymonkey.com/api/v3/#error-codes", "message": "Failed to validate field 'headings' list schema: additional properties not defined by 'properties' are not allowed in field '_data'", "id": "1002", "name": "Bad Request", "http_status_code": 400}}

I am using the below JSON code,

```<code>payload ={
    "headings":
    [
            {
            "heading": "This is a monkey",
            "image":    {
                "img_url": "https://raw.githubusercontent.com/SurveyMonkey/public_api_docs/master/images/presentation.png"
                    }
             }
        ],
    "position": 4,
    "family": "presentation",
    "subtype": "descriptive_text"
    }
</code>```

Kindly help!

答:
You're probably looking for the image subtype, the payload should look more like:

```<code>{
    "headings": [{
        "heading": "This is a monkey",
        "image": {
            "url": "https://raw.githubusercontent.com/SurveyMonkey/public_api_docs/master/images/presentation.png"
        }
    }],
    "position": 4,
    "family": "presentation",
    "subtype": "image"
}
</code>```

Title: Including images in survey monkey

Body:
I am trying to include an image as a survey question and it gives be the below error,

surveymonty.exceptions.SurveyMontyAPIError: {"error": {"docs": "https://developer.surveymonkey.com/api/v3/#error-codes", "message": "Failed to validate field 'headings' list schema: additional properties not defined by 'properties' are not allowed in field '_data'", "id": "1002", "name": "Bad Request", "http_status_code": 400}}

I am using the below JSON code,

payload ={
    "headings":
    [
            {
            "heading": "This is a monkey",
            "image":    {
                "img_url": "https://raw.githubusercontent.com/SurveyMonkey/public_api_docs/master/images/presentation.png"
                    }
             }
        ],
    "position": 4,
    "family": "presentation",
    "subtype": "descriptive_text"
    }

Kindly help!

Body:
You're probably looking for the image subtype, the payload should look more like:

{
    "headings": [{
        "heading": "This is a monkey",
        "image": {
            "url": "https://raw.githubusercontent.com/SurveyMonkey/public_api_docs/master/images/presentation.png"
        }
    }],
    "position": 4,
    "family": "presentation",
    "subtype": "image"
}


问:
Why dont the divs appear inline-block in a html section?
So I am using a Html5 template. It is a onepager and I want a section with 'business hours' , with like three days - with their corresponding times- on each line. So I want a line with de divs mon-tue-wed, another beneath it with thu-fri-sat and below sunday.

I have divs like this:

```<code><div>
<strong> Monday </strong><br>
09.15 - 10.00 .. <br>
11.15 - 12:00 ..<br>
17:30 - 18:15 .. <br>
19:15- 20:00 ..
</div>
<br>
</code>```

etc.

All divs are children of :

```<code><section id="schedule" class="times">
</code>```

but whenever I refer to it in CSS using this:

```<code>        section.times> div {
            background-color: #e8edec;
            display: inline-block;

        }
</code>```

Why does it still display everything underneath eachother?

Body:
So I am using a Html5 template. It is a onepager and I want a section with 'business hours' , with like three days - with their corresponding times- on each line. So I want a line with de divs mon-tue-wed, another beneath it with thu-fri-sat and below sunday.

I have divs like this:

 Monday

09.15 - 10.00 ..

11.15 - 12:00 ..

17:30 - 18:15 ..

19:15- 20:00 ..

etc.

All divs are children of :

but whenever I refer to it in CSS using this:

        section.times> div {
            background-color: #e8edec;
            display: inline-block;

        }

Why does it still display everything underneath eachother?

Body:
hope it helps, delete the <bar>..
made css code for you.
Html:

<div class="c1">
<strong> Monday </strong><br>
09.15 - 10.00 .. <br>
11.15 - 12:00 ..<br>
17:30 - 18:15 .. <br>
19:15- 20:00 ..
</div>

<div class="c2">
<strong> Monday </strong><br>
09.15 - 10.00 .. <br>
11.15 - 12:00 ..<br>
17:30 - 18:15 .. <br>
19:15- 20:00 ..
</div>
<br>
</section>

Css code:

.times> .c1 {
float: left;
width: 33.33333%;}
.times> .c2{
float: left;
width: 33.33333%;}


问:
Using Sublime Text on Windows and eslint on windows linux subsystem
I have node, npm and eslint instaled on WSL.
Can't setup Sublimelinter in Sublime Text 3 in Windows to hook up with eslint installed via bash in WSL.
Which path's i should enter in linter settings in Sublime?</p>

答:
Sublimetext3 works inside WSL so you can install the Sublimetext3 linux binaries and use an Xserver on Windows side to launch it. With that method, plugins that need things installed inside WSL should work.

https://medium.com/@pck/how-to-use-sublime-text-3-from-command-line-with-ubuntu-bash-terminal-in-windows-10-subsystems-for-aa2ad59d088c

Edit: If the plugin is simple enough you can call linux binaries from Windows Sublimetext3 (32bit) with the command

bash.exe -c "bash command"

For example, you can try modifying ESLint.py with something like this

```<code>args = {
      'cmd': [
        'C:\\windows\\sysnative\\bash.exe',
        '-c',
        'node',
        linter_path,
        files[0],
        node_modules_path,
        config_file
      ],
</code>```

But then you will see is not that simple. You will have problems with paths like c:\myfolder being /mnt/c/myfolder on WSL and so on.
At the end It's easier to just use the Ubuntu binaries.

Body:
Sublimetext3 works inside WSL so you can install the Sublimetext3 linux binaries and use an Xserver on Windows side to launch it. With that method, plugins that need things installed inside WSL should work.

https://medium.com/@pck/how-to-use-sublime-text-3-from-command-line-with-ubuntu-bash-terminal-in-windows-10-subsystems-for-aa2ad59d088c

Edit: If the plugin is simple enough you can call linux binaries from Windows Sublimetext3 (32bit) with the command

bash.exe -c "bash command"

For example, you can try modifying ESLint.py with something like this

args = {
      'cmd': [
        'C:\\windows\\sysnative\\bash.exe',
        '-c',
        'node',
        linter_path,
        files[0],
        node_modules_path,
        config_file
      ],

But then you will see is not that simple. You will have problems with paths like c:\myfolder being /mnt/c/myfolder on WSL and so on.
At the end It's easier to just use the Ubuntu binaries.


答:
You need to use an ampersand character (&) to do that:

```<code>yourButton.Text = "&itemname";
</code>```

See http://msdn.microsoft.com/en-us/library/az5a73z1.aspx.

Title: How to put underline under button name

Body: I have button with name "itemname", and now I want to put underline just under character "i" in "itemname", but I don't know how I should do this. Could anyone please tell me how?

Body:
You need to use an ampersand character (&) to do that:

yourButton.Text = "&itemname";

See http://msdn.microsoft.com/en-us/library/az5a73z1.aspx.


问:
convert files enconding recursively
Here I found a wonderful solution for recursively change the encoding of the files of one folder Randomseed solution

```<code>$path = realpath('C:\\your\\path');

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach($iterator as $fileName => $file){
    if($file->isFile())
        file_put_contents(
            $fileName,
            iconv('ISO-8859-7', 'UTF-8', file_get_contents($fileName))
        );
}
</code>```

But there is a problem. Every file is changed, even images, and they are not shown later.
How to edit this for changing only .php files for example?

Thank you very much!

答:
If you only want to loop over .php files, Simply look at the extension of the file.</p>

```<code>    foreach($iterator as $fileName => $file){
    if($file->isFile() && $file->getExtension() == "php")
        file_put_contents(
            $fileName,
            iconv('ISO-8859-7', 'UTF-8', file_get_contents($fileName))
        );
   }
</code>```

Title: convert files enconding recursively

Body:
Here I found a wonderful solution for recursively change the encoding of the files of one folder Randomseed solution

$path = realpath('C:\\your\\path');

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach($iterator as $fileName => $file){
    if($file->isFile())
        file_put_contents(
            $fileName,
            iconv('ISO-8859-7', 'UTF-8', file_get_contents($fileName))
        );
}

But there is a problem. Every file is changed, even images, and they are not shown later.
How to edit this for changing only .php files for example?

Thank you very much!

Body:
If you only want to loop over .php files, Simply look at the extension of the file.

    foreach($iterator as $fileName => $file){
    if($file->isFile() && $file->getExtension() == "php")
        file_put_contents(
            $fileName,
            iconv('ISO-8859-7', 'UTF-8', file_get_contents($fileName))
        );
   }


问:
Find a deleted number from a list
Considering two lists (a sequence of numbers from 1 to N (arr) and the same sequence mixed but missing one number (mixed_arr)). The goal is to find the number that was deleted.

Example:

```<code>arr = [1,2,3,4,5]
mixed_arr = [3,4,1,5]
</code>```

The output should be 2.

Return 0 if no number was deleted and if there is no difference
If no number was deleted from the array and no difference with it, the function has to return 0. Note that N may be 1 or less (in the latter case, the first array will be []).

Testcases:

```<code>arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [1,9,7,4,6,2,3,8]
output = 5

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [5,7,6,9,4,8,1,2,3]
output = 0
</code>```

Here's my code:

```<code>def find_deleted_number(arr, mixed_arr):
    arr.sort()
    mixed_arr.sort()

    for x in range(arr):
        for y in range(mixed_arr):
            if arr[x] != mixed_arr[y]:
                return arr[x]
            elif arr[x] == mixed_arr[y]:
                return 0
</code>```

The error I get is:

```<code>Traceback:
   in <module>
   in find_deleted_number
TypeError: 'list' object cannot be interpreted as an integer
</code>```

答:
Why not to use set?

```<code>>>> arr = [1,2,3,4,5,6,7,8,9]
>>> mixed_arr = [1,9,7,4,6,2,3,8]
>>> list(set(arr) - set(mixed_arr))
[5]
</code>```

This general solution will handle arrays with no constraints on integers, or on the size of lists (or the size of the difference).

Edit. In your (very) specific case with positive integers, and only one missing in the other array, it's much more efficient to use the solution from comments below:

```<code>>>> abs(sum(arr) - sum(mixed_arr))
5
</code>```

Title: Find a deleted number from a list

Body:
Considering two lists (a sequence of numbers from 1 to N (arr) and the same sequence mixed but missing one number (mixed_arr)). The goal is to find the number that was deleted.

Example:

arr = [1,2,3,4,5]
mixed_arr = [3,4,1,5]

The output should be 2.

Return 0 if no number was deleted and if there is no difference
If no number was deleted from the array and no difference with it, the function has to return 0. Note that N may be 1 or less (in the latter case, the first array will be []).

Testcases:

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [1,9,7,4,6,2,3,8]
output = 5

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [5,7,6,9,4,8,1,2,3]
output = 0

Here's my code:

def find_deleted_number(arr, mixed_arr):
    arr.sort()
    mixed_arr.sort()

    for x in range(arr):
        for y in range(mixed_arr):
            if arr[x] != mixed_arr[y]:
                return arr[x]
            elif arr[x] == mixed_arr[y]:
                return 0

The error I get is:

Traceback:
   in <module>
   in find_deleted_number
TypeError: 'list' object cannot be interpreted as an integer

Body:
Why not to use set?

>>> arr = [1,2,3,4,5,6,7,8,9]
>>> mixed_arr = [1,9,7,4,6,2,3,8]
>>> list(set(arr) - set(mixed_arr))
[5]

This general solution will handle arrays with no constraints on integers, or on the size of lists (or the size of the difference).

Edit. In your (very) specific case with positive integers, and only one missing in the other array, it's much more efficient to use the solution from comments below:

>>> abs(sum(arr) - sum(mixed_arr))
5


问:
Remove shipping address option in PayPal Express Checkout
I am using the JS script recommended by PayPal. It's working well, however it is showing a "Ship to" address of the buyers.

I am trying to search the internet and found that https://api.sandbox.paypal.com/v1/payment-experience/web-profiles/ requested with "no_shipping": 1, can do the trick. But for that we need to make a curl request before the payment.create, so that we can pass it returned id in the function.

Is this possible in JS?

Or is there a much better and simpler way to remove it using the following JS?

```<code><script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<script>

    paypal.Button.render({
        env: 'sandbox', // Optional: specify 'sandbox' or 'production'
        client: {
            sandbox:    '{{$data['SandboxId']}}',
            production: '{{$data['ProductionId']}}'
        },

        payment: function() {
            var amount = document.getElementById("amount").value;
            var env    = this.props.env;
            var client = this.props.client;

            return paypal.rest.payment.create(env, client, {
                transactions: [
                    {
                        amount: {
                            total: amount,
                            currency: "USD",
                            details: {
                                subtotal: amount,
                                tax: "0.00",
                                shipping: "0.00"
                            }
                        },
                        description: "This is payment description.",
                        item_list: {
                            items:[
                                {
                                    quantity:"1",
                                    name:"Orders",
                                    price:amount,
                                    sku:"product12345",
                                    currency:"USD"
                                }
                            ],
                        },

                    }],

            });
        },

        commit: false, // Optional: show a 'Pay Now' button in the checkout flow

        onAuthorize: function(data, actions) {
                console.log(data);
                 alert('confirmation here');
                // Optional: display a confirmation page here

            return actions.payment.execute().then(function() {
                alert('Success here');
                // Show a success page to the buyer
            });
        },
    }, '#paypal-button');
</script><div id="paypal-button" ></div>
</code>```

答:
To expand on Bluepnume's answer, here is a complete example:</p>

```<code>  payment: function(data, actions) {
        return actions.payment.create({
            payment: {
                transactions: [
                    {
                        amount: { total: '1.00', currency: 'USD' }
                    }
                ]
            },

            experience: {
                input_fields: {
                    no_shipping: 1
                }
            }
        });
    },
</code>```

Body:
To expand on Bluepnume's answer, here is a complete example:

  payment: function(data, actions) {
        return actions.payment.create({
            payment: {
                transactions: [
                    {
                        amount: { total: '1.00', currency: 'USD' }
                    }
                ]
            },

            experience: {
                input_fields: {
                    no_shipping: 1
                }
            }
        });
    },


问:
Creating projects based on jupyter notebooks
Having learned to program in Python with Jupyter Notebooks, I've found this to be a very practical way of analyzing data, writing simple programs and even interacting with databases.

However, if one is working on a bigger project (with program and database that run automatically and should also eventually be deployed), is it still possible / reasonable to run the code from Notebooks? If so, do you have any advice on that?

Otherwise, I would of course resort to an IDE. Thanks!

答:
Jupyter Notebooks are awesome tools, and great for certain types of collaborative development, and creating interactive web apps.

The purpose of Jupyter Notebooks is to provide a framework for combining rich text elements and code together (perfect for data science projects, tutorials or interactive dashboards). Jupyter notebooks also allow you to run code in multiple languages, which is a neat feature if your project requires it.

You probably wouldn't want to run a large scale production application from a Jupyter notebook, but you could certainly use them to help you develop it.

Check out this presentation for using Jupyter notebooks with multiple users.
https://www.slideshare.net/mbussonn/jupyter-a-platform-for-data-science-at-scale

If you specified the type of project you were considering it might be easier to suggest alternatives to help complete it.


问:
Javascript loop through array asynchronous
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

```<code>function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}
</code>```

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.

答:
That is a good use case to the async functions of ES2017.

Please, try the following:

```<code>async function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        await scaffoldTo(blocksToMine[i]);
    }
    ...
}
</code>```

If ES2017 is out of the question, your best choice would be to make a recursive function that only calls itself again when the promise from scaffoldTo is resolved.

Body:
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.

Body:
That is a good use case to the async functions of ES2017.

Please, try the following:

async function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        await scaffoldTo(blocksToMine[i]);
    }
    ...
}

If ES2017 is out of the question, your best choice would be to make a recursive function that only calls itself again when the promise from scaffoldTo is resolved.


答:
Your problem is that you are trying to pass an list object to the range() function. But since range() only accepts integers, Python complains. You are also making the same mistake with mixed_arr.

But there are easier ways to accomplish this. In this case, you can use set()s to find the difference between two lists:

```<code>>>> set([1,2,3,4,5]) - set([3,4,1,5])
{2}
>>>
</code>```

Or this could be done using a simple list comprehension:

```<code>>>> arr = [1,2,3,4,5]
>>> mixed_arr = [3,4,1,5]
>>>
>>> [el for el in arr if el not in mixed_arr]
[2]
>>>
</code>```

Title: Find a deleted number from a list

Body:
Your problem is that you are trying to pass an list object to the range() function. But since range() only accepts integers, Python complains. You are also making the same mistake with mixed_arr.

But there are easier ways to accomplish this. In this case, you can use set()s to find the difference between two lists:

>>> set([1,2,3,4,5]) - set([3,4,1,5])
{2}
>>>

Or this could be done using a simple list comprehension:

>>> arr = [1,2,3,4,5]
>>> mixed_arr = [3,4,1,5]
>>>
>>> [el for el in arr if el not in mixed_arr]
[2]
>>>


问:
Getting the many-to-many fields of a many-to-many object
If I have the user-group relation as a ManyToMany relationship, and a group-team relation as a ManyToMany relationship, how would I find the user-team relation as a query object?

For example if I had a models.py like this:

```<code>class Group(models.Model):
    name = CharField(max_length=100)

class User(models.Model):
    username = models.CharField(max_length=100)
    groups = models.ManyToManyField(Group, blank=True)

class Team(models.Model):
    teamname = models.CharField(max_length=100)
    groups = models.ManyToManyField(Group, blank=True)
</code>```

I know I can do it by creating a for loop like follows, but it would be much more useful given django's architecture to have it as a query object.

My ugly solution:

```<code>user = User.objects.get(username="Ed")
users_teams = []
user_groups = Group.objects.filter(user=user)
for group in user_groups:
    group_teams = Team.objects.filter(group=group)
    for team in group_teams:
        user_teams.append(team)
</code>```

So this would give me a list query objects that I could associate with a user, but it isn't as easy to use as a single query set the contains query objects for each user-team relation.

I would prefer something that looks like this:

```<code>User.objects.get(username="Ed").groups.team_set.objects.all()
</code>```

which definitely doesn't work.
Any ideas?

答:
Team.objects.filter(groups__user__username="Ed")
```

<p>which generates you:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  `api_team`.`id`,
  `api_team`.`teamname`
FROM `api_team`
  INNER JOIN `api_team_groups` ON (`api_team`.`id` = `api_team_groups`.`team_id`)
  INNER JOIN `api_group` ON (`api_team_groups`.`group_id` = `api_group`.`id`)
  INNER JOIN `api_user_groups` ON (`api_group`.`id` = `api_user_groups`.`group_id`)
  INNER JOIN `api_user` ON (`api_user_groups`.`user_id` = `api_user`.`id`)
WHERE `api_user`.`username` = 'ed'
</code>```

Body:
If I have the user-group relation as a ManyToMany relationship, and a group-team relation as a ManyToMany relationship, how would I find the user-team relation as a query object?

For example if I had a models.py like this:

class Group(models.Model):
    name = CharField(max_length=100)

class User(models.Model):
    username = models.CharField(max_length=100)
    groups = models.ManyToManyField(Group, blank=True)

class Team(models.Model):
    teamname = models.CharField(max_length=100)
    groups = models.ManyToManyField(Group, blank=True)

I know I can do it by creating a for loop like follows, but it would be much more useful given django's architecture to have it as a query object.

My ugly solution:

user = User.objects.get(username="Ed")
users_teams = []
user_groups = Group.objects.filter(user=user)
for group in user_groups:
    group_teams = Team.objects.filter(group=group)
    for team in group_teams:
        user_teams.append(team)

So this would give me a list query objects that I could associate with a user, but it isn't as easy to use as a single query set the contains query objects for each user-team relation.

I would prefer something that looks like this:

User.objects.get(username="Ed").groups.team_set.objects.all()

which definitely doesn't work.
Any ideas?

Body:
Team.objects.filter(groups__user__username="Ed")

which generates you:

SELECT
  `api_team`.`id`,
  `api_team`.`teamname`
FROM `api_team`
  INNER JOIN `api_team_groups` ON (`api_team`.`id` = `api_team_groups`.`team_id`)
  INNER JOIN `api_group` ON (`api_team_groups`.`group_id` = `api_group`.`id`)
  INNER JOIN `api_user_groups` ON (`api_group`.`id` = `api_user_groups`.`group_id`)
  INNER JOIN `api_user` ON (`api_user_groups`.`user_id` = `api_user`.`id`)
WHERE `api_user`.`username` = 'ed'