问:
Passing function pointers & int references to another function
Just started working on a c project.  Need help with passing function pointers/macro functions/etc.  I'm a php & python OO guy, but new to c.  I tried to generalize the example for this post. I have a main.c with a lib for the Axon microcontroller I'm working with.  Works like a charm with everything in main.c.  I need to move some of the functionality out of main to more organized lib files as my code grows.  The base microcontroller lib creates a macro function that allows me to send data to the microcontroller to make a servo move left or right.  I now need to create a servo specific file (HS-422.c) that will will allow me to pass references/pointers(?) to a generic function that will execute for each servo to ease on code duplication.

Keep in mind I'm only focused on passing macros/functions/variable references to other functions and have them called / set.  The other basics of c I understand. I must have tried a 100 different ways to make this work today with no luck. So just wrote a simplified version hoping you might get an idea of what I'm attempting.

Thank you for your help!

```<code>/*
 * main.h
 * I'm trying to make a pointer or reference to the macro.
 * The original file had:
 * #define servo1(position) servo(PORTE,2,position);
 */

 // servo is a macro defined in another microcontroller file
 #define (void)(*servo1)(position) servo(PORTE,2,position);
 #define (void)(*servo2)(position) servo(PORTE,3,position);

/* main.c */

// init main functions
void servo_scan(void);

// init vars
int servo1_location = 0;
int servo2_location = 0;

int main(void)
{
  for(;;)
  {
     servo_turn();
  }
}

// get the servos to turn
void servo_turn(void)
{
  turn_servo( *servo1, &servo1_location, 200);
  turn_servo( *servo2, &servo2_location, 950);
}

/* HS-422.c */
void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation)
{
  // turning
  for(uint16_t  i=&currentLocation; i<newLocation; i=i+10)
  {
    // turn servo
    // hoping the specifc passed servo# pointer gets called
    *servo(i);

    // set value by reference to origional servo#_location var. making sure.
    &currentLocation = i;

    // pause
    delay_ms(20);
  }
}
</code>```

答:
It's not really clear to me exactly what you're trying to achieve, but what is clear is that you don't really understand the concept of pointers/references in C - so I'll try to clarify, and hopefully that will help you implement what you need.

Firstly, there is no such thing as a "reference" in C.  The only alternative to passing by value is to pass a pointer.  A pointer is basically just a memory address, and you can get a pointer (memory address) to a variable using the & (address of) operator.  When passing a pointer variable to a function, you do something like the following:

Given a function which takes a pointer:

int foo(int* pointer);

You would pass the memory address of an int variable to this function like so:

```<code>int x = 10;
foo(&x);
</code>```

So right off the bat, you can see that your function definition above is wrong:

```<code>void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation);
</code>```

This is simply a syntax error.  It will not compile because of the int &currentLocation.  The & operator is used to take the address of a variable.  It can't be used in a function parameter.  If you want a "reference" to currentLocation, you need to pass in a pointer, so your function parameters should be written as:

```<code>void turn_servo(void (*servo)(int position), int* currentLocation, int newLocation);
</code>```

Secondly, when you want to modify the value pointed to by the currentLocation pointer, you need to use the * operator to dereference the pointer.  So, the line where you set currentLocation is not correct.  What you want to say is:

```<code>// set value by to origional servo#_location var. making sure.
*currentLocation = i;
</code>```

And of course, the line:

```<code>  for(uint16_t i=&currentLocation; i<newLocation; i=i+10)
</code>```

should be:

```<code>  for(uint16_t i= *currentLocation; i<newLocation; i=i+10)
</code>```

Note that in your original code you use the & operator in both cases, which takes the address of a variable.  Since currentLocation is already a memory address, this would result in taking the address of an address, also known as a pointer-to-a-pointer, which is certainly not what you want here.

Finally, the phrase "pointer or reference to the macro" is completely nonsensical.  A macro is not a function.  It is more like a meta-function: essentially it is a template used by the C preprocessor to generate further source code.  The C preprocessor is invoked before the compilation phase, and basically acts as a find/replace mechanism in the source code.  You can't have a pointer to a macro, because for all intents and purposes macros don't even exist in the compilation phase.  They are only meaningful to the preprocessor.

There may be more here, but ultimately you seem to have a fundamental misunderstanding of pointers (as well as macros) in C, and short of providing a complete tutorial, the best I can do is point out the syntax problems.  I highly recommend you read a good introductory book to C, which will certainly go over pointers, macros, and functions.

Body:
Just started working on a c project.  Need help with passing function pointers/macro functions/etc.  I'm a php & python OO guy, but new to c.  I tried to generalize the example for this post. I have a main.c with a lib for the Axon microcontroller I'm working with.  Works like a charm with everything in main.c.  I need to move some of the functionality out of main to more organized lib files as my code grows.  The base microcontroller lib creates a macro function that allows me to send data to the microcontroller to make a servo move left or right.  I now need to create a servo specific file (HS-422.c) that will will allow me to pass references/pointers(?) to a generic function that will execute for each servo to ease on code duplication.

Keep in mind I'm only focused on passing macros/functions/variable references to other functions and have them called / set.  The other basics of c I understand. I must have tried a 100 different ways to make this work today with no luck. So just wrote a simplified version hoping you might get an idea of what I'm attempting.

Thank you for your help!

/*
 * main.h
 * I'm trying to make a pointer or reference to the macro.
 * The original file had:
 * #define servo1(position) servo(PORTE,2,position);
 */

 // servo is a macro defined in another microcontroller file
 #define (void)(*servo1)(position) servo(PORTE,2,position);
 #define (void)(*servo2)(position) servo(PORTE,3,position);

/* main.c */

// init main functions
void servo_scan(void);

// init vars
int servo1_location = 0;
int servo2_location = 0;

int main(void)
{
  for(;;)
  {
     servo_turn();
  }
}

// get the servos to turn
void servo_turn(void)
{
  turn_servo( *servo1, &servo1_location, 200);
  turn_servo( *servo2, &servo2_location, 950);
}

/* HS-422.c */
void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation)
{
  // turning
  for(uint16_t  i=&currentLocation; i<newLocation; i=i+10)
  {
    // turn servo
    // hoping the specifc passed servo# pointer gets called
    *servo(i);

    // set value by reference to origional servo#_location var. making sure.
    &currentLocation = i;

    // pause
    delay_ms(20);
  }
}

Body:
It's not really clear to me exactly what you're trying to achieve, but what is clear is that you don't really understand the concept of pointers/references in C - so I'll try to clarify, and hopefully that will help you implement what you need.

Firstly, there is no such thing as a "reference" in C.  The only alternative to passing by value is to pass a pointer.  A pointer is basically just a memory address, and you can get a pointer (memory address) to a variable using the & (address of) operator.  When passing a pointer variable to a function, you do something like the following:

Given a function which takes a pointer:

int foo(int* pointer);

You would pass the memory address of an int variable to this function like so:

int x = 10;
foo(&x);

So right off the bat, you can see that your function definition above is wrong:

void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation);

This is simply a syntax error.  It will not compile because of the int &currentLocation.  The & operator is used to take the address of a variable.  It can't be used in a function parameter.  If you want a "reference" to currentLocation, you need to pass in a pointer, so your function parameters should be written as:

void turn_servo(void (*servo)(int position), int* currentLocation, int newLocation);

Secondly, when you want to modify the value pointed to by the currentLocation pointer, you need to use the * operator to dereference the pointer.  So, the line where you set currentLocation is not correct.  What you want to say is:

// set value by to origional servo#_location var. making sure.
*currentLocation = i;

And of course, the line:

  for(uint16_t i=&currentLocation; i<newLocation; i=i+10)

should be:

  for(uint16_t i= *currentLocation; i<newLocation; i=i+10)

Note that in your original code you use the & operator in both cases, which takes the address of a variable.  Since currentLocation is already a memory address, this would result in taking the address of an address, also known as a pointer-to-a-pointer, which is certainly not what you want here.

Finally, the phrase "pointer or reference to the macro" is completely nonsensical.  A macro is not a function.  It is more like a meta-function: essentially it is a template used by the C preprocessor to generate further source code.  The C preprocessor is invoked before the compilation phase, and basically acts as a find/replace mechanism in the source code.  You can't have a pointer to a macro, because for all intents and purposes macros don't even exist in the compilation phase.  They are only meaningful to the preprocessor.

There may be more here, but ultimately you seem to have a fundamental misunderstanding of pointers (as well as macros) in C, and short of providing a complete tutorial, the best I can do is point out the syntax problems.  I highly recommend you read a good introductory book to C, which will certainly go over pointers, macros, and functions.


来源: stackexchange

问:
creating two models in one serializer of django rest framework
During registration of a user I would like to have both a User object and a EmailContact object created in one api call. The two objects should not be linked.
I have the following serializer:

```<code>class RegistrationSerializer(serializers.Serializer):
    userserializer=UserAccountSerializer() #reuse existing modelserializer
    emailcontactserializer=EmailContactSerializer()  #reuse existing modelserializer

    def create(self, validated_data):
        emailcontact_data = validated_data.pop('emailcontactserializer')
        user_data = validated_data.pop('userserializer')
        emailcontact= EmailContact.objects.create(**emailcontact_data)
        user= User.objects.create(**user_data)
        return user
</code>```

and the following Apiview:

```<code>class RegistrationAPIView(APIView):
    permission_classes = (AllowAny,)
    serializer_class = RegistrationSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

The error I get is the following (occurs after the serializer.save()):

AttributeError at /api/register
Got AttributeError when attempting to get a value for field userserializer on serializer RegistrationSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the User instance.
Original exception text was: 'User' object has no attribute 'userserializer'.

答:
In your RegistrationSerializer.create() method, you're returning a User object. The serializer will try to serialize that object into this representation:

```<code>{
  'userserializer': x,
  'emailcontactserializer': y
}
</code>```

But it's complaining because the User you returned doesn't have a userserializer field.

If you really want to return a User from this API call, you could make your RegistrationSerializer a ModelSerializer with Meta.model=User, and override perform_create to pop out the emailcontact_data. (I'd name the field something like RegistrationSerializer.email_contact to make the representation clearer, IMO the phrase "serializer" shouldn't be present on the client-visible portion of the API).

Alternatively, if you want to render both of your sub-serializers, you can create a RegistrationSerializer instance in RegistrationSerializer.create by passing in the data, something like

```<code>return RegistrationSerializer(data={'emailcontactserializer':
    emailcontact_data, 'userserializer': user_data})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
During registration of a user I would like to have both a User object and a EmailContact object created in one api call. The two objects should not be linked.
I have the following serializer:

class RegistrationSerializer(serializers.Serializer):
    userserializer=UserAccountSerializer() #reuse existing modelserializer
    emailcontactserializer=EmailContactSerializer()  #reuse existing modelserializer

    def create(self, validated_data):
        emailcontact_data = validated_data.pop('emailcontactserializer')
        user_data = validated_data.pop('userserializer')
        emailcontact= EmailContact.objects.create(**emailcontact_data)
        user= User.objects.create(**user_data)
        return user

and the following Apiview:

class RegistrationAPIView(APIView):
    permission_classes = (AllowAny,)
    serializer_class = RegistrationSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The error I get is the following (occurs after the serializer.save()):

AttributeError at /api/register
Got AttributeError when attempting to get a value for field userserializer on serializer RegistrationSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the User instance.
Original exception text was: 'User' object has no attribute 'userserializer'.

Body:
In your RegistrationSerializer.create() method, you're returning a User object. The serializer will try to serialize that object into this representation:

{
  'userserializer': x,
  'emailcontactserializer': y
}

But it's complaining because the User you returned doesn't have a userserializer field.

If you really want to return a User from this API call, you could make your RegistrationSerializer a ModelSerializer with Meta.model=User, and override perform_create to pop out the emailcontact_data. (I'd name the field something like RegistrationSerializer.email_contact to make the representation clearer, IMO the phrase "serializer" shouldn't be present on the client-visible portion of the API).

Alternatively, if you want to render both of your sub-serializers, you can create a RegistrationSerializer instance in RegistrationSerializer.create by passing in the data, something like

return RegistrationSerializer(data={'emailcontactserializer':
    emailcontact_data, 'userserializer': user_data})


问:
Convert HSV to grayscale in OpenCV
I'm a newbie in OpenCV. I'm learning the Segmentation by Watershed algorithm and I have a problem.

I have to convert the image color to grayscale for using Watershed.
When I use the BGR color space, no problem but with HSV, I'm not sure that the code below is correct.

Mat im = imread("./Image/118035.jpg", CV_LOAD_IMAGE_COLOR);

Mat imHSV;
cvtColor(im, imHSV, CV_BGR2HSV);
imshow("HSV", imHSV);

cvtColor(imHSV, imHSV, CV_BGR2GRAY);
imshow("HSV to gray", imHSV);

imshow("BGR", im);
cvtColor(im, im, CV_BGR2GRAY);
imshow("BGR to gray", im);
```

I think, after converting from BGR to HSV, Hue = Blue, Saturation = Green, Value = Red and I can use the operator BGR2GRAY for convert from HSV to grayscale.

The 2 output images are different. Can I convert HSV to grayscale like that?

//Is it similaire with color space LAB?

答:
Unfortunately I am unable to comment because of insufficient earned reputation.

Taking the 3rd channel alone will may give grey values you do not expect, as increasingly fully saturated colors,as an extreme example RGB 0,0,255 will appear as pure white once converted to grey scale by taking the value hsv channel.

This could certainly affect watershed (dependent on image content) as saturated red, greens and blues would not be differentiated in the V channel.

The obvious, converting to BGR then Grayscale could be a better option.

ContentLicense: CC BY-SA 4.0

Title: Convert HSV to grayscale in OpenCV

Body:
I'm a newbie in OpenCV. I'm learning the Segmentation by Watershed algorithm and I have a problem.

I have to convert the image color to grayscale for using Watershed.
When I use the BGR color space, no problem but with HSV, I'm not sure that the code below is correct.

Mat im = imread("./Image/118035.jpg", CV_LOAD_IMAGE_COLOR);

Mat imHSV;
cvtColor(im, imHSV, CV_BGR2HSV);
imshow("HSV", imHSV);

cvtColor(imHSV, imHSV, CV_BGR2GRAY);
imshow("HSV to gray", imHSV);

imshow("BGR", im);
cvtColor(im, im, CV_BGR2GRAY);
imshow("BGR to gray", im);

I think, after converting from BGR to HSV, Hue = Blue, Saturation = Green, Value = Red and I can use the operator BGR2GRAY for convert from HSV to grayscale.

The 2 output images are different. Can I convert HSV to grayscale like that?

//Is it similaire with color space LAB?


问:
Creating a Spring MVC project in Eclipse 3.5
HIi,
I try to figure out the best way to set up a fully functionally Spring MVC project for use in Eclipse.

What I did so far:

Create new project with "New Project > Spring > Spring Project"

Try "maven package" command from Eclipse's "Run as" button > Error

Compile projext on command line using "mvn package"

Drag-drop to Tomcat webapps folder.

Now I try to figure out answers to these questions:

Eclipse shows a folder with "JS" as icon, but when I open it it shows the "src" and "target" folder, also with JS icon... What is that?

is there a way to "click a button" in Eclipse an compile the project AND have it auto-deployed to my local/remote web server?

THX

答:
For the second question:

If you have configured a Server in Eclipse (for example Tomcat), and added your Project to this Server, then it auto-deployes every change in your project to the server. (Sometimes this does not work 100% correct and you have to restart the server.)

If you need more functionality you can have a look at JRebel ( http://www.zeroturnaround.com/jrebel/ )

Added

If you Project is no Dynamic Web Project (this is if you create it as Spring Project), then you have to add the Dynamic Web Facet first.

Project Properties/Project Facets/-> Convert to faceted from.../

Select: Dynamic Web Project, and Java

Then you can add the project to your server.

ContentLicense: CC BY-SA 2.5


问:
How to read and print the line multiple strings appear on in Ruby
I have a log file with contents in this format:

```<code>[28/Feb/2017] 00007bd2 7d194700 - ERROR: ws_common:
[28/Feb/2017] 00007bd2 7d194700 - ERROR: ESI: getResponse: failed
[28/Feb/2017] 00007bd2 DOWN- [] ws_common:
</code>```

I want to find and print the line containing a keyword like "DOWN", as well as the time the message appears in the log file.

I did it like this in UNIX:

```<code>SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l
</code>```

but I can't seem to get it right in Ruby. This returns ALL of the lines as well as the line numbers:

```<code>File.foreach("#{filename}").with_index do |line, line_num|

  if File.open("#{filename}") { |f| f.each.find { |line| line.include?("#
          {DAY}/#{MTH}/#{YR}:#{HR}:#{MINM}" && "down") }  }

    puts "#{line_num}: #{line} "
  end
end
</code>```

Using the file above as an example, the output I would like to get from this is:

3 [28/Feb/2017] 00007bd2 DOWN- [] ws_common:

"3" being the third line.

答:
I've done it like this in UNIX:

```<code> SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l
</code>```

And here it's almost the same. This prints all lines with DOWN in them.

```<code>puts File.foreach(filename).grep(/DOWN/)
# >> [28/Feb/2017] 00007bd2 DOWN-
</code>```

I am not sure if you want to grep for timestamp or you want to simply know the timestamps of DOWN events. If it's the latter, here you have it (lines are printed in their entirety). If it's the former, it shouldn't be too hard to implement, now that you are armed with this new technique.

Body:
I have a log file with contents in this format:

[28/Feb/2017] 00007bd2 7d194700 - ERROR: ws_common:
[28/Feb/2017] 00007bd2 7d194700 - ERROR: ESI: getResponse: failed
[28/Feb/2017] 00007bd2 DOWN- [] ws_common:

I want to find and print the line containing a keyword like "DOWN", as well as the time the message appears in the log file.

I did it like this in UNIX:

SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l

but I can't seem to get it right in Ruby. This returns ALL of the lines as well as the line numbers:

File.foreach("#{filename}").with_index do |line, line_num|

  if File.open("#{filename}") { |f| f.each.find { |line| line.include?("#
          {DAY}/#{MTH}/#{YR}:#{HR}:#{MINM}" && "down") }  }

    puts "#{line_num}: #{line} "
  end
end

Using the file above as an example, the output I would like to get from this is:

3 [28/Feb/2017] 00007bd2 DOWN- [] ws_common:

"3" being the third line.

Body:
I've done it like this in UNIX:

 SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l

And here it's almost the same. This prints all lines with DOWN in them.

puts File.foreach(filename).grep(/DOWN/)
# >> [28/Feb/2017] 00007bd2 DOWN-

I am not sure if you want to grep for timestamp or you want to simply know the timestamps of DOWN events. If it's the latter, here you have it (lines are printed in their entirety). If it's the former, it shouldn't be too hard to implement, now that you are armed with this new technique.


问:
Missing projects information from the OWASP Secure Coding Practices
When I found the OWASP Secure Coding Practices Guide, I felt like I had found a hidden gem. The information in the checklist format is great. Although I was disappointed to see that links pointed to multiple other external projects is not found and the artifacts for them just do not exist. So pointing it here hoping anyone has more information on them.

Implement a secure software development lifecycle - OWASP CLASP Project: Returns page has been deleted

ESAPI for Php link on OWASP Enterprise Security API project returns nothing

I am unsure how to find or access these.

答:
The CLASP project is no longer supported. It has been supersed by the OpenSAMM (http://www.opensamm.org) project who can give you all the things to setup a good and efficent SSDLC (Secure Software Development Live Cycle).

Anyways, as the OWASP projects are movings, i suggest you to point all the time to the home page to have a good and updated view


问:
Read shared preference of another android application
I need to access the Shared Preference file of another application. (The device is rooted!) Currently I seem to be facing a permission issues. Here is the current code that I run:

```<code>Context con = createPackageContext("com.sam.sample", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPref = con.getSharedPreferences("namefile", MODE_PRIVATE);
Map data = sharedPref.getString("name", "");
Log.d("Name", "name:" + name);
</code>```

When I run this code I get the following error:

Attempt to read preferences file /data/data/com.sam.sample/shared_prefs/namefile.xml without permission

I have also tried to run su command but I dont want the user to be notified that I want to get read access with chmod 775 on the XML file.

Any help is appreciated.

答:
To do this when creating SharedPreference in "com.sam.sample" it should be created using Context.MODE_WORLD_READABLE mode. So if you have code of "com.sam.sample" application, it should look something like below

```<code>SharedPreferences prefs = getSharedPreferences("namefile",
                Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("name", strShareValue);
        editor.commit();
</code>```

Also note that changing the mode to Context.MODE_WORLD_READABLE is not recommended as it may lead to security holes. As of NOS this will throw SecurityException. More info:-

https://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE

Ideally ContentProvider should be used.

For example query function of your ContentProvider can be

MatrixCursor cursor = new MatrixCursor(new String[] { "name" }, 1);
            cursor.addRow(new Object[] { readSharedPreference() });
            return cursor;

Body:
I need to access the Shared Preference file of another application. (The device is rooted!) Currently I seem to be facing a permission issues. Here is the current code that I run:

Context con = createPackageContext("com.sam.sample", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPref = con.getSharedPreferences("namefile", MODE_PRIVATE);
Map data = sharedPref.getString("name", "");
Log.d("Name", "name:" + name);

When I run this code I get the following error:

Attempt to read preferences file /data/data/com.sam.sample/shared_prefs/namefile.xml without permission

I have also tried to run su command but I dont want the user to be notified that I want to get read access with chmod 775 on the XML file.

Any help is appreciated.

Body:
To do this when creating SharedPreference in "com.sam.sample" it should be created using Context.MODE_WORLD_READABLE mode. So if you have code of "com.sam.sample" application, it should look something like below

SharedPreferences prefs = getSharedPreferences("namefile",
                Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("name", strShareValue);
        editor.commit();

Also note that changing the mode to Context.MODE_WORLD_READABLE is not recommended as it may lead to security holes. As of NOS this will throw SecurityException. More info:-

https://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE

Ideally ContentProvider should be used.

For example query function of your ContentProvider can be

MatrixCursor cursor = new MatrixCursor(new String[] { "name" }, 1);
            cursor.addRow(new Object[] { readSharedPreference() });
            return cursor;


问:
Increase Chart.js Scale Padding/Margin
How do I increase the separation between the border and the bar?

Example image:

http://imgur.com/a/AamLT

Current Code:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["January"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 30, 81, 56, 55, 40],
        }
    ]
};
var option = {

};

var myBarChart = Chart.Bar(canvas,{
 data:data,
  options:option
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="500"></canvas></code>```

JSFiddle:

https://jsfiddle.net/palaceslittle/mfvmoy64/217/

答:
Once you update to a latest version of Chart.js (currently v2.6.0), in the bar config section, you can set a maxBarThickness. Doing this will allow you to increase the chart canvas width, without needing to worry about the bar getting larger.

Your options section would look as following:

```<code>var option = {
    scales: {
        xAxes: [{
            maxBarThickness: 100
        }]
    }
};
</code>```

JSFiddle: https://jsfiddle.net/dhhnssgc/

See the below documentation for more information about the bar chart configuration options:

http://www.chartjs.org/docs/latest/charts/bar.html#configuration-options

Depending on how you set up the rest of your chart, the barPercentage and barThickness options may also work for you.

If you want to move your entire chart away from the edge of the canvas, you can use the layout padding option: http://www.chartjs.org/docs/latest/configuration/layout.html

```<code>options: {
    layout: {
        padding: {
            left: 0,
            right: 50,
            top: 0,
            bottom: 0
        }
    }
}
</code>```

JSFiddle: https://jsfiddle.net/dhhnssgc/2/

Title: Increase Chart.js Scale Padding/Margin

Body:
How do I increase the separation between the border and the bar?

Example image:

http://imgur.com/a/AamLT

Current Code:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["January"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 30, 81, 56, 55, 40],
        }
    ]
};
var option = {

};

var myBarChart = Chart.Bar(canvas,{
 data:data,
  options:option
});

<canvas id="myChart" width="400" height="500"></canvas>

JSFiddle:

https://jsfiddle.net/palaceslittle/mfvmoy64/217/

Body:
Once you update to a latest version of Chart.js (currently v2.6.0), in the bar config section, you can set a maxBarThickness. Doing this will allow you to increase the chart canvas width, without needing to worry about the bar getting larger.

Your options section would look as following:

var option = {
    scales: {
        xAxes: [{
            maxBarThickness: 100
        }]
    }
};

JSFiddle: https://jsfiddle.net/dhhnssgc/

See the below documentation for more information about the bar chart configuration options:

http://www.chartjs.org/docs/latest/charts/bar.html#configuration-options

Depending on how you set up the rest of your chart, the barPercentage and barThickness options may also work for you.

If you want to move your entire chart away from the edge of the canvas, you can use the layout padding option: http://www.chartjs.org/docs/latest/configuration/layout.html

options: {
    layout: {
        padding: {
            left: 0,
            right: 50,
            top: 0,
            bottom: 0
        }
    }
}

JSFiddle: https://jsfiddle.net/dhhnssgc/2/


问:
get average from while loop in C using the same variable
I have a variable total that stores the total of miles and gallons every time user enters it.

When user hits -1, the program is suppose to add all the totals together and take the average.
I can't get the variable to add the previous total value to itself for the next iteration of the loop.

I tried totals += totals; but that returns the last total value of the loop?

what am i doing wrong?

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        totals = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", totals);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += totals;
        numOfEntries++;
        avgConsumption = totals / numOfEntries;

    } // end while
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    _getch();
    return 0;

} // end main
</code>```

答:
I dont think you are getting the right "total" at all

It is getting over-written every time you reiterate through the while-loop.

Make another variable to hold the "total" and one variable that you can store "miles/gallons" by -- like 'MPG'

Then at the end you can do Total = Total + MPG.

Body:
I have a variable total that stores the total of miles and gallons every time user enters it.

When user hits -1, the program is suppose to add all the totals together and take the average.
I can't get the variable to add the previous total value to itself for the next iteration of the loop.

I tried totals += totals; but that returns the last total value of the loop?

what am i doing wrong?

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        totals = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", totals);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += totals;
        numOfEntries++;
        avgConsumption = totals / numOfEntries;

    } // end while
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    _getch();
    return 0;

} // end main


问:
How can I use a Google Apps Script to add multiple Google Docs to a Google Drive folder?
I have a list of Google Document URLs (about 700 of them) and need to add them to a Google Folder so that they are all in one space because currently they are owned by hundreds of different users.

I've seen a few postings on how to do the inverse of this: Generate a list of URLs from the contents of a folder. This has been helpful, but it seems this task is much more difficult.

This is what I've tried, and it doesn't seem to be working:

```<code>var doc = DocumentApp.openById('1sQGds0kyeO66ZiMiJlsKkHPcqjySPy5q0dWShc2irts'),
docFile = DriveApp.getFileById( doc.getId() );
DriveApp.getFolderById('0B7yp85g7j5ZHbVlEUmNGX2w0M1k').addFile( docFile );
DriveApp.getRootFolder().removeFile(docFile);
</code>```

答:
it doesn't error check and may timeout... but it is a start.
You would add the fileIds in Column A.

function makeCopyFromId() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 700;   // Last row to process.
  var dataRange = sheet.getRange(startRow, 1, numRows, 5)
  var data = dataRange.getValues();
  var destFolder = DriveApp.getFolderById("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  for (i in data) {
    var row = data[i];
    var ssId = row[0];
    Logger.log(ssId);   // check the log to see if they all complete-

     var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(ssId).makeCopy("",destFolder))  //copies each file.
  }}```

Body:
I have a list of Google Document URLs (about 700 of them) and need to add them to a Google Folder so that they are all in one space because currently they are owned by hundreds of different users.

I've seen a few postings on how to do the inverse of this: Generate a list of URLs from the contents of a folder. This has been helpful, but it seems this task is much more difficult.

This is what I've tried, and it doesn't seem to be working:

var doc = DocumentApp.openById('1sQGds0kyeO66ZiMiJlsKkHPcqjySPy5q0dWShc2irts'),
docFile = DriveApp.getFileById( doc.getId() );
DriveApp.getFolderById('0B7yp85g7j5ZHbVlEUmNGX2w0M1k').addFile( docFile );
DriveApp.getRootFolder().removeFile(docFile);


答:
What you need to do is have a variable that adds up all of the totals, and then when the loop is complete, divides the number by your avgConsumption variable.

Here is a slight modification of your program:

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

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals = 0; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        float curTotal = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", curTotal);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += curTotal;
        numOfEntries++;

    } // end while
    avgConsumption = totals / numOfEntries;
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    return 0;

} // end main
</code>```

What I did was use totals to add up all of the miles/gallons you received in your loop. I used a local variable curTotal to store the actual miles/gallons calculation. This variable is reset for every iteration of the loop. After th loop concludes, I calculated avgConsumption, instead of calculating it in the loop which produces different results. This gives you the average number of miles per gallon reported by users.

Title: get average from while loop in C using the same variable

Body:
What you need to do is have a variable that adds up all of the totals, and then when the loop is complete, divides the number by your avgConsumption variable.

Here is a slight modification of your program:

#include <stdio.h>

const float EXIT_VALUE = -1.0f;

int main(void)
{
    float gallons; // number of gallons used
    float miles; // number of miles driven
    float totals = 0; // total = miles * gallons
    int numOfEntries = 0; // number of entries
    float avgConsumption = 0; // avg of all entries made by user

    // get number of gallons from user
    printf("%s%.1f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
    scanf("%f", &gallons);

    // loops until user enter -1
    while (gallons != EXIT_VALUE) {
        //miles driven by user
        printf("%s", "Enter the miles driven: ");
        scanf("%f", &miles);

        // calculate total miles per gallon
        float curTotal = miles/gallons;
        printf("The miles/gallons for this tank was %.6f\n\n", curTotal);

        // get number of gallons from user
        printf("%s%.2f%s", "Enter the gallons used (", EXIT_VALUE, " to end): ");
        scanf("%f", &gallons);

        totals += curTotal;
        numOfEntries++;

    } // end while
    avgConsumption = totals / numOfEntries;
    printf("\nThe overall average miles/gallon was %.6f: ", avgConsumption);

    return 0;

} // end main

What I did was use totals to add up all of the miles/gallons you received in your loop. I used a local variable curTotal to store the actual miles/gallons calculation. This variable is reset for every iteration of the loop. After th loop concludes, I calculated avgConsumption, instead of calculating it in the loop which produces different results. This gives you the average number of miles per gallon reported by users.


问:
cmd prompt works fine, but Batch file cannot handle % strings
I have this image sitting in my folder named

hello%5B1%5D.png

I run this command prompt script to copy an image with a new name

COPY "hello%5B1%5D.png" "New_Image_Name.png"

which works fine

but if I dump it inside a .bat file and double click .bat, it outputs this instead:

COPY "helloB1D.png" "New_Image_Name.png"

taking out the 5 and % inside the image name.

Is there an option to allow command prompt to handle % strings as input values, if they are enclosed by double quotation marks? ""

答:
```<code>COPY "hello%%5B1%%5D.png" "New_Image_Name.png"
</code>```


问:
Embedded Stylesheet in external assembly for asp.net Core 1.1
I am using VS.2017 Community Edition with 15.2 update (26430.12) and in my solution I have a main ASP.NET Core 1.1 web application and a separate assembly which is a .NET Core class library which I have rigged so that it is the Web SDK as class library and from where I provide view components to the main web application. That works fine.

However, I have just added a couple of partial views (perhaps view components later on) but these two in particular do need a stylesheet (CSS) file to be included. Since I want everything self contained like the visual components, I created a wwwroot\css folder and therein I put my CSS and made it an embedded resource.

The question is.... in my main web application how do I go about streaming that stylesheet in the ASP.NET Core _Layout file given the stylesheet is embedded in the external assembly?

答:
Based on the docs
, I think theoretically you could add an embedded file provider to static files middleware like this:

```<code>var embeddedFiles = new EmbeddedFileProvider(
                typeof(yourtype).GetTypeInfo().Assembly,
                "your.assembly.name"
            );

builder.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = embeddedFiles
    //,RequestPath = new PathString("/files") // optionally use a path other than /
});
</code>```

If that way works it is probably best, but I have not tried it myself so not 100% sure that works. Currently in my project I have just added controller actions that returns my embedded static resources which you can see in the css, js, and fonts actionmethods in my FileManagerController

My FileManagerController needs css and js and fonts so I have action methods for each of those and a private helper action method. It works, but when I get a chance I would try the other way as it would be much less code.
The urls for my resources are like [controller]/action so filemanager/css, filemanager/js, filemanager/fonts in my case.

UPDATE 2017-06-09: I have now implemented serving embedded static resources in my own project using the StaticFiles Middleware approach. I can confirm it works in general but there is an issue if the embedded resource has any - in folder segments the resource was not found because - in folder segments needs to be changed to _ to find the resource but - in file names is ok. The EmbeddedFileProvider does not handle this so I reported an issue here and solved it with a custom IFileProvider in my project.

It is also possible as mentioned to serve static resources from controller actions, but MVC runs after authentication/authorization middleware so the result is that those middlewares run in processing the static file requests which can be avoided using static files middleware that runs before that. I guess if there was a need to protect embedded static resources then using controller actions would be a way to do that, but I don't need it in my case.

Body:
Based on the docs
, I think theoretically you could add an embedded file provider to static files middleware like this:

var embeddedFiles = new EmbeddedFileProvider(
                typeof(yourtype).GetTypeInfo().Assembly,
                "your.assembly.name"
            );

builder.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = embeddedFiles
    //,RequestPath = new PathString("/files") // optionally use a path other than /
});

If that way works it is probably best, but I have not tried it myself so not 100% sure that works. Currently in my project I have just added controller actions that returns my embedded static resources which you can see in the css, js, and fonts actionmethods in my FileManagerController

My FileManagerController needs css and js and fonts so I have action methods for each of those and a private helper action method. It works, but when I get a chance I would try the other way as it would be much less code.
The urls for my resources are like [controller]/action so filemanager/css, filemanager/js, filemanager/fonts in my case.

UPDATE 2017-06-09: I have now implemented serving embedded static resources in my own project using the StaticFiles Middleware approach. I can confirm it works in general but there is an issue if the embedded resource has any - in folder segments the resource was not found because - in folder segments needs to be changed to _ to find the resource but - in file names is ok. The EmbeddedFileProvider does not handle this so I reported an issue here and solved it with a custom IFileProvider in my project.

It is also possible as mentioned to serve static resources from controller actions, but MVC runs after authentication/authorization middleware so the result is that those middlewares run in processing the static file requests which can be avoided using static files middleware that runs before that. I guess if there was a need to protect embedded static resources then using controller actions would be a way to do that, but I don't need it in my case.


问:
Edit and Continue with TypeScript?
Is there any effort to support edit and continue with TypeScript? Everytime I want to change code while debugging I need to stop ad restart the entire debugging process...</p>

答: I think the best answer to this question is "its up to the browser, and none of them do it well. Chrome does it the best, but for large complex js files it doesnt really work. Edge and IE dont even attempt it"</p>

Title: Edit and Continue with TypeScript?


问:
Code effects business rules for windows application
Can I use code-effects business rules for Windows Applications or Console applications?
I want to define the rules using the rule editor but want to execute those rules as a service.</p>

答: Yes, you can if you are OK referencing System.Web assembly in your project.</p>


问:
Repository Pattern, NHibernate and Unit Testing
I am working on ASP MVC 3 PROJECT with repository pattern, I want to know how exactly we have to write a unit test for CRUD operations on repository(aggregate). I am stuck with Saving part where I want to rollback my save, remove it from database, something like
Transaction.rollback, it i not working for me, can anyone please help me with some sample code on how to do this.

Here is the overview of my code

```<code>Begintransaction
session.save(Parent parent) in repository
transaction.commit.
</code>```

Unittest:

```<code>opensession;
_rep.Save(parent);
</code>```

Actually if there is a way or a piece of code that i can put into the TearDown part in my test class that runs after each test Say in mycase after Save method and deletes that particular record, and one more thing considered to be is, AS THIS RUNS AFTER EACH TEST I DNT know how to handle it when it tries to do the same thing after other test methids (delete, get all) etc.., i am all confused.

答:
In your NUnit Setup and TearDown methods, you need to drop and then create the specified tables(using a script) in your database. So before and after each of your tests run, all your data will of-course get deleted leaving only empty tables for you to test.

The following example uses MySql database, but even for other databases, the code should be quite similar:

```<code>public class DatabaseCleanup
    {
        private string _connectionString;
        private MySqlConnection _mySqlConnection;
        private string _filePath;
        public DatabaseCleanup()
        {
            _filePath = @"C:\createdatabase.sql";
            _connectionString = @"Server=localhost;Port=3306;Database=dbname;Uid=username;Password=password;";
            _mySqlConnection = new MySqlConnection(_connectionString);
        }

        public void Create()
        {
            string script = File.ReadAllText(_filePath);
            ExecuteScript(script);
        }

        private void ExecuteScript(string script)
        {
            try
            {
                MySqlCommand command = new MySqlCommand(script, _mySqlConnection);
                _mySqlConnection.Open();
                command.ExecuteNonQuery();
                _mySqlConnection.Close();
            }
            catch (Exception exception)
            {
                throw;
            }
            finally
            {
                _mySqlConnection.Close();
            }
        }
    }
</code>```

The script createdatabase.sql mentioned in the above code is simply an sql file that contains drop table and create table statements, which you can supply as per your database. Following is just a sample:

```<code>DROP TABLE IF EXISTS `my_table`;

CREATE TABLE `my_table` (
  `Id` varchar(50) NOT NULL,
  `Name` varchar(50) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

You can then use the DatabaseCleanup class in your NUnit test class' Setup and TearDown methods:

```<code>DatabaseCleanup databaseCleanup = new DatabaseCleanup();
databaseCleanup.Create();
</code>```

Be careful not to run this database cleanup code on production environments. Run such tests  on development and testing environment only.

P.S., I don't like people saying here to use in-memory databases like SqlLite. That completely defeats the whole purpose of Integration Testing. That would mean to test your code using a different database in your development environment, and then go and deploy on a different database platform on the production server; and then face a nightmare!

Body:
I am working on ASP MVC 3 PROJECT with repository pattern, I want to know how exactly we have to write a unit test for CRUD operations on repository(aggregate). I am stuck with Saving part where I want to rollback my save, remove it from database, something like
Transaction.rollback, it i not working for me, can anyone please help me with some sample code on how to do this.

Here is the overview of my code

Begintransaction
session.save(Parent parent) in repository
transaction.commit.

Unittest:

opensession;
_rep.Save(parent);

Actually if there is a way or a piece of code that i can put into the TearDown part in my test class that runs after each test Say in mycase after Save method and deletes that particular record, and one more thing considered to be is, AS THIS RUNS AFTER EACH TEST I DNT know how to handle it when it tries to do the same thing after other test methids (delete, get all) etc.., i am all confused.

Body:
In your NUnit Setup and TearDown methods, you need to drop and then create the specified tables(using a script) in your database. So before and after each of your tests run, all your data will of-course get deleted leaving only empty tables for you to test.

The following example uses MySql database, but even for other databases, the code should be quite similar:

public class DatabaseCleanup
    {
        private string _connectionString;
        private MySqlConnection _mySqlConnection;
        private string _filePath;
        public DatabaseCleanup()
        {
            _filePath = @"C:\createdatabase.sql";
            _connectionString = @"Server=localhost;Port=3306;Database=dbname;Uid=username;Password=password;";
            _mySqlConnection = new MySqlConnection(_connectionString);
        }

        public void Create()
        {
            string script = File.ReadAllText(_filePath);
            ExecuteScript(script);
        }

        private void ExecuteScript(string script)
        {
            try
            {
                MySqlCommand command = new MySqlCommand(script, _mySqlConnection);
                _mySqlConnection.Open();
                command.ExecuteNonQuery();
                _mySqlConnection.Close();
            }
            catch (Exception exception)
            {
                throw;
            }
            finally
            {
                _mySqlConnection.Close();
            }
        }
    }

The script createdatabase.sql mentioned in the above code is simply an sql file that contains drop table and create table statements, which you can supply as per your database. Following is just a sample:

DROP TABLE IF EXISTS `my_table`;

CREATE TABLE `my_table` (
  `Id` varchar(50) NOT NULL,
  `Name` varchar(50) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You can then use the DatabaseCleanup class in your NUnit test class' Setup and TearDown methods:

DatabaseCleanup databaseCleanup = new DatabaseCleanup();
databaseCleanup.Create();

Be careful not to run this database cleanup code on production environments. Run such tests  on development and testing environment only.

P.S., I don't like people saying here to use in-memory databases like SqlLite. That completely defeats the whole purpose of Integration Testing. That would mean to test your code using a different database in your development environment, and then go and deploy on a different database platform on the production server; and then face a nightmare!


问:
Read function arguments in decorator
I have written this decorator that saves intermediate results in a json file

```<code>import json
import os

def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator
</code>```

And usage is

```<code>@json_file("cached.json")
def some_calculation(n):
   return {"result": 2**n}
</code>```

And I want to augment in to use the function parameters like this:

```<code>@json_file("cached_{n}.json")
def calculation(n):
    return {"result": 2**n}
</code>```

Such that {n} is replaced with the value of n when calling the function.

I tried replacing fname with fname.format(**kwargs), without any success.

How can this be achieved ?

EDIT:

As Per @jonrshape's comment, this is the error I am getting after adding the .format(**kwargs)

```<code> <ipython-input-4-12b0c894b345> in wrapper(*args, **kwargs)
       5     def decorator(function):
       6         def wrapper(*args, **kwargs):
 ----> 7             fname = fname.format(**kwargs)
       8             if os.path.isfile(fname):
       9                 with open(fname, 'r') as f:

 UnboundLocalError: local variable 'fname' referenced before assignment
</code>```

答:
You can use the inspect module.

First we extract the wrapped function's signature:

```<code>signature= inspect.signature(function)
</code>```

Then we bind the *args and **kwargs:

```<code>bound_args= signature.bind(*args, **kwargs)
</code>```

Now bound_args.parameters is a dict of parameter_name:parameter_value which we can use to format our file name:

```<code>file_name= fname.format(**bound_args.arguments)
</code>```

Everything put together:

```<code>import json
import os
import inspect

def json_file(fname):
    def decorator(function):
        signature= inspect.signature(function)

        def wrapper(*args, **kwargs):
            bound_args= signature.bind(*args, **kwargs)
            file_name= fname.format(**bound_args.arguments)

            #~ print(file_name)
            if os.path.isfile(file_name):
                with open(file_name, 'r') as f:
                    ret = json.load(f)
            else:
                with open(file_name,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator
</code>```

Title: Read function arguments in decorator

Body:
I have written this decorator that saves intermediate results in a json file

import json
import os

def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator

And usage is

@json_file("cached.json")
def some_calculation(n):
   return {"result": 2**n}

And I want to augment in to use the function parameters like this:

@json_file("cached_{n}.json")
def calculation(n):
    return {"result": 2**n}

Such that {n} is replaced with the value of n when calling the function.

I tried replacing fname with fname.format(**kwargs), without any success.

How can this be achieved ?

EDIT:

As Per @jonrshape's comment, this is the error I am getting after adding the .format(**kwargs)

 <ipython-input-4-12b0c894b345> in wrapper(*args, **kwargs)
       5     def decorator(function):
       6         def wrapper(*args, **kwargs):
 ----> 7             fname = fname.format(**kwargs)
       8             if os.path.isfile(fname):
       9                 with open(fname, 'r') as f:

 UnboundLocalError: local variable 'fname' referenced before assignment

Body:
You can use the inspect module.

First we extract the wrapped function's signature:

signature= inspect.signature(function)

Then we bind the *args and **kwargs:

bound_args= signature.bind(*args, **kwargs)

Now bound_args.parameters is a dict of parameter_name:parameter_value which we can use to format our file name:

file_name= fname.format(**bound_args.arguments)

Everything put together:

import json
import os
import inspect

def json_file(fname):
    def decorator(function):
        signature= inspect.signature(function)

        def wrapper(*args, **kwargs):
            bound_args= signature.bind(*args, **kwargs)
            file_name= fname.format(**bound_args.arguments)

            #~ print(file_name)
            if os.path.isfile(file_name):
                with open(file_name, 'r') as f:
                    ret = json.load(f)
            else:
                with open(file_name,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator


问:
make a string a new instant of a class in C#
I am facing a problem I can not solve. and I hope someone can.

// I got Table saved in M.SQL server as in Picture

// Code

DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => x );

I want to instantiate every string ( i.Position) as a new instant name of class ARTICLE.like the followings

 foreach ( var i in ALL)
{
ARTICLE "i.Position" = new ARTICLE();
"i.Name".A_STOCK = i.Stock ;
}

// The Class
public Class ARTICLE
{
public int A_STOCK { get; set;}

}

// later I want to recall it to get its A_STOCK value , for example

int k1 = A1.A_STOCK ;
int k2 = A2.A_STOCK ;```

//
In short , I want to retrieve all strings in Position Column and convert every string of them into a a new instant of class (ARTICLE) carries then instant name ...

Thank you very much ...

答:
You can use a List<T>:

```<code>var articles = new List<ARTICLE>();
foreach(var i in ALL)
    articles.Add(new ARTICLE() { A_STOCK = i.Stock });

var k1 = articles[0].A_STOCK;
var k2 = articles[1].A_STOCK;
///etc...
</code>```

Btw, so many things wrong with your style.... Have a look at https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions

Body:
I am facing a problem I can not solve. and I hope someone can.

// I got Table saved in M.SQL server as in Picture

// Code

DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => x );

I want to instantiate every string ( i.Position) as a new instant name of class ARTICLE.like the followings

 foreach ( var i in ALL)
{
ARTICLE "i.Position" = new ARTICLE();
"i.Name".A_STOCK = i.Stock ;
}

// The Class
public Class ARTICLE
{
public int A_STOCK { get; set;}

}

// later I want to recall it to get its A_STOCK value , for example

int k1 = A1.A_STOCK ;
int k2 = A2.A_STOCK ;

//
In short , I want to retrieve all strings in Position Column and convert every string of them into a a new instant of class (ARTICLE) carries then instant name ...

Thank you very much ...

Body:
You can use a List<T>:

var articles = new List<ARTICLE>();
foreach(var i in ALL)
    articles.Add(new ARTICLE() { A_STOCK = i.Stock });

var k1 = articles[0].A_STOCK;
var k2 = articles[1].A_STOCK;
///etc...

Btw, so many things wrong with your style.... Have a look at https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions


问:
extract structs values into variable named as the field
I have a 1x1 Matlab struct with 5 fields ('a', 'b', 'c', 'd', 'e'). Each field contains some sort of data (which doesn't really matter for my question) and I would like to extract each value out of the struct and assign it to a variable named as the field. Any idea for a code that will do it?</p>

答:
If you know what are the variables to be created, then you can write (assuming s is your struct):

```<code>C = struct2cell(s);
[a,b,c,d,e] = C{:};
</code>```

Otherwise, you need to create undeclared new variables while the program is running (using the assignin command from @Vahe-Tshitoyan answer) and that's a bad idea.

Body:
If you know what are the variables to be created, then you can write (assuming s is your struct):

C = struct2cell(s);
[a,b,c,d,e] = C{:};

Otherwise, you need to create undeclared new variables while the program is running (using the assignin command from @Vahe-Tshitoyan answer) and that's a bad idea.


问:
Cancel Task.Delay(TimeSpan) if condition is met prior to timespan
I have below code which waits for 300 ms and then verify the condition i.e. isMatch is True.

```<code>await Task.Delay(TimeSpan.FromMilliseconds(300));

if (isMatch)
{
//do something
isMatch = false;
}
else{

}
</code>```

How can I avoid this 300 ms constant wait when isMatch variable value is True before 300 ms time is over on in other words my code should execute based on the the any of the event occurs first i.e. either isMatch value is true or 300 ms are over.

App has a timer which runs after every 100 ms which is responsible for setting the value of isMatch as True.

答:
You cancel a Task.Delay by passing a CancellationToken into it.

So, whenever your code sets isMatch to true, also have it call CancellationTokenSource.Cancel.

Body:
I have below code which waits for 300 ms and then verify the condition i.e. isMatch is True.

await Task.Delay(TimeSpan.FromMilliseconds(300));

if (isMatch)
{
//do something
isMatch = false;
}
else{

}

How can I avoid this 300 ms constant wait when isMatch variable value is True before 300 ms time is over on in other words my code should execute based on the the any of the event occurs first i.e. either isMatch value is true or 300 ms are over.

App has a timer which runs after every 100 ms which is responsible for setting the value of isMatch as True.


问:
Eigen for c++ calculating wrong eigenvalue
So I am using Eigen for C++ in code blocks to calculate eigenvalues for my matrices. The specific part of the code that deals with this is as follows:-

```<code>EigenSolver<MatrixXd> b(B,false);
cout<<" Eigen values are: \n "<<b.eigenvalues()<<"\n";
</code>```

The problem I have been encountering is is that one of the eigenvalues calculated for my matrix B is nowhere close to the actual eigenvalue I found on calculator.vhex.net.

For example, for the matrix

1 0 0 x

0 1 x 0

0 x 1 y

x 0 y 1

where x = -1/sqrt(2) and y = -0.5 , the eigenvalues are 0, 0.5, 1.5 and 2.

However, my code calculates them to be -4.25e-016 , 0.5, 1.5 and 2.

I also tried this for a 5x5 matrix which should have had an eigenvalue 4e-06 , but the code calculated it as 1.4413e-017 .

What could be the reason(s) for this? Are they approximations?
My guess is memory issues and that a double type value of square root of 2 will not exactly equal to the square root of 2, but I am not sure about this.

What could be a possible fix for this?

答: Finding eigenvalues can be difficult when the matrix is near singular, which is indicated with a 0 eigenvalue. You should not expect an exact eigenvalue of 0 ever from a numerical solution, since it will only be good up to some numerical approximation which starts failing near that point.</p>

Body:
So I am using Eigen for C++ in code blocks to calculate eigenvalues for my matrices. The specific part of the code that deals with this is as follows:-

EigenSolver<MatrixXd> b(B,false);
cout<<" Eigen values are: \n "<<b.eigenvalues()<<"\n";

The problem I have been encountering is is that one of the eigenvalues calculated for my matrix B is nowhere close to the actual eigenvalue I found on calculator.vhex.net.

For example, for the matrix

1 0 0 x

0 1 x 0

0 x 1 y

x 0 y 1

where x = -1/sqrt(2) and y = -0.5 , the eigenvalues are 0, 0.5, 1.5 and 2.

However, my code calculates them to be -4.25e-016 , 0.5, 1.5 and 2.

I also tried this for a 5x5 matrix which should have had an eigenvalue 4e-06 , but the code calculated it as 1.4413e-017 .

What could be the reason(s) for this? Are they approximations?
My guess is memory issues and that a double type value of square root of 2 will not exactly equal to the square root of 2, but I am not sure about this.

What could be a possible fix for this?


问:
Identifier Too Long Error Where Oracle Table is 34 charactersOracle ODBC ORA-00972: identifier is too Long
I have the following SQL which pulls against an Oracle ODBC:

```<code>SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT_SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN (''6228506'')
</code>```

I receive the following error when running in VBA:

I suspect it's from SUBMISSION_OBJECT_SEGMENTATION_REF. However, I have no control over the length of this database \ table name combination.

I have searched on line to get around it, but have not found any luck.

SUBMISSION_OBJECT is the database name. SEGMENTATION_REF is the table name.

I have also tried SUBMISSION_OBJECT.SEGMENTATION_REF, but no luck.

```<code>SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT.SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN (''6228506'')
</code>```

That produces

ORA-00907: missing right parenthesis

For reference, vba code that calls follows:

```<code>Function downloadsqltoexcel(conn As ADODB.Connection, sSQL As String, exceldestinationrangename As String, sqltablename As String, bDownload As Boolean, Optional ws As Worksheet) As Variant

Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset

With rsPubs

    .ActiveConnection = conn
    .CursorLocation = adUseClient
    .Open sSQL, conn, adOpenKeyset, adLockReadOnly, adCmdText
    '**** errors on above line ****
</code>```

答:
You don't use underscores to separate databases name from table names.  You use periods:</p>

```<code>SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT.SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN ('6228506')
</code>```

Body:
I have the following SQL which pulls against an Oracle ODBC:

SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT_SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN (''6228506'')

I receive the following error when running in VBA:

I suspect it's from SUBMISSION_OBJECT_SEGMENTATION_REF. However, I have no control over the length of this database \ table name combination.

I have searched on line to get around it, but have not found any luck.

SUBMISSION_OBJECT is the database name. SEGMENTATION_REF is the table name.

I have also tried SUBMISSION_OBJECT.SEGMENTATION_REF, but no luck.

SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT.SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN (''6228506'')

That produces

ORA-00907: missing right parenthesis

For reference, vba code that calls follows:

Function downloadsqltoexcel(conn As ADODB.Connection, sSQL As String, exceldestinationrangename As String, sqltablename As String, bDownload As Boolean, Optional ws As Worksheet) As Variant

Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset

With rsPubs

    .ActiveConnection = conn
    .CursorLocation = adUseClient
    .Open sSQL, conn, adOpenKeyset, adLockReadOnly, adCmdText
    '**** errors on above line ****

Body:
You don't use underscores to separate databases name from table names.  You use periods:

SELECT t.INS_RQMT_PRODCT_NO, t.NEW_DEPT_NO
FROM SUBMISSION_OBJECT.SEGMENTATION_REF t
WHERE t.INS_RQMT_PRODUCT_NO IN ('6228506')


问:
how to read data from a URL
Is there a anyway to read data from a URL with SSL after with using

```<code>tie(*SSL, "Net::SSLeay::Handle", $host, $port);
</code>```

my code below

```<code>my $a = "POST /login.php HTTP/1.1";
my $b = "Host: www.test.com";
my $c = "Connection: close";
my $e = "Cache-Control: max-age=0";
my $f = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
my $g = "Origin: https://www.facebook.com";
my $h = "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31";
my $i = "Content-Type: application/x-www-form-urlencoded";
my $j = "Accept-Encoding: gzip,deflate,sdch";
my $k = "Accept-Language: en-US,en;q=0.8";
my $l = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3";

my $cookie = "cookie: datr=80ZzUfKqDOjwL8pauwqMjHTa";
my $post = "lsd=AVpD2t1f&display=&enable_profile_selector=&legacy_return=1&next=&profile_selector_ids=&trynum=1&timezone=300&lgnrnd=031110_Euoh&lgnjs=1366193470&email=$user&pass=$user&default_persistent=0&login=Log+In";
my $cl = length($post);
my $d = "Content-Length: $cl";

my ($host, $port) = ("www.test.com", 443);

tie(*SSL, "Net::SSLeay::Handle", $host, $port);

print SSL "$a\n";
print SSL "$b\n";
print SSL "$c\n";
print SSL "$d\n";
print SSL "$e\n";
print SSL "$f\n";
print SSL "$g\n";
print SSL "$h\n";
print SSL "$i\n";
print SSL "$j\n";
print SSL "$k\n";
print SSL "$l\n";
print SSL "$cookie\n\n";

print SSL "$post\n";
</code>```

答:
The synopsis of Net::SSLeay::Handle suggest to simply print to the handle (emphasis mine).

```<code>use Net::SSLeay::Handle qw/shutdown/;
my ($host, $port) = ("localhost", 443);

tie(*SSL, "Net::SSLeay::Handle", $host, $port);

print SSL "GET / HTTP/1.0\r\n";
shutdown(\*SSL, 1);
print while (<SSL>);                          # <------- here
close SSL;
</code>```

Title: how to read data from a URL

Body:
Is there a anyway to read data from a URL with SSL after with using

tie(*SSL, "Net::SSLeay::Handle", $host, $port);

my code below

my $a = "POST /login.php HTTP/1.1";
my $b = "Host: www.test.com";
my $c = "Connection: close";
my $e = "Cache-Control: max-age=0";
my $f = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
my $g = "Origin: https://www.facebook.com";
my $h = "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31";
my $i = "Content-Type: application/x-www-form-urlencoded";
my $j = "Accept-Encoding: gzip,deflate,sdch";
my $k = "Accept-Language: en-US,en;q=0.8";
my $l = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3";

my $cookie = "cookie: datr=80ZzUfKqDOjwL8pauwqMjHTa";
my $post = "lsd=AVpD2t1f&display=&enable_profile_selector=&legacy_return=1&next=&profile_selector_ids=&trynum=1&timezone=300&lgnrnd=031110_Euoh&lgnjs=1366193470&email=$user&pass=$user&default_persistent=0&login=Log+In";
my $cl = length($post);
my $d = "Content-Length: $cl";

my ($host, $port) = ("www.test.com", 443);

tie(*SSL, "Net::SSLeay::Handle", $host, $port);

print SSL "$a\n";
print SSL "$b\n";
print SSL "$c\n";
print SSL "$d\n";
print SSL "$e\n";
print SSL "$f\n";
print SSL "$g\n";
print SSL "$h\n";
print SSL "$i\n";
print SSL "$j\n";
print SSL "$k\n";
print SSL "$l\n";
print SSL "$cookie\n\n";

print SSL "$post\n";

Body:
The synopsis of Net::SSLeay::Handle suggest to simply print to the handle (emphasis mine).

use Net::SSLeay::Handle qw/shutdown/;
my ($host, $port) = ("localhost", 443);

tie(*SSL, "Net::SSLeay::Handle", $host, $port);

print SSL "GET / HTTP/1.0\r\n";
shutdown(\*SSL, 1);
print while (<SSL>);                          # <------- here
close SSL;


问:
Find a pending lock or transaction in MySql
I have a piece of PHP code which can't execute queries anymore because of a pending lock or already open transaction on the MySql DB which i still haven't found.
The script is launched by cron every hour. The offending code is this

```<code>    CommandHelper::log("Calling beginTransaction for item $item->id");
    $transaction = Yii::app()->db->beginTransaction();
    CommandHelper::log("Trying to get update lock for item $item->id");
    try {
       // this line will lock a single row
        $item = Item::model()->findBySql("SELECT * FROM " . $item::model()->getTableSchema()->name . " WHERE id=$item->id FOR UPDATE");
        if(!$item)
            throw new Exception("Item $item->id not found in processItem");
        CommandHelper::log("Obtained update lock for item $item->id");

    $now = DateTimeHelper::getInstance()->getStringNow();
    // the following call executes a few queries and causes an exception
    $this->processExpiredDeferredPayments($item,$now);
    // we won't get here
    CommandHelper::log("Item $item->id query confirmed units");
   ....
   ....

        $transaction->commit();

    } catch (Exception $e) {
        $transaction->rollBack();
        CommandHelper::log("Transaction error:" . $e->getMessage());
    }
</code>```

The log prints these lines every hour:

```<code>...
...
2017-06-03 14:46:04 Item 164 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 164
2017-06-03 14:46:04 Trying to get update lock for item 164
2017-06-03 14:46:04 Obtained update lock for item 164
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 164 end processing
2017-06-03 14:46:04 Item 160 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 160
2017-06-03 14:46:04 Trying to get update lock for item 160
2017-06-03 14:46:04 Obtained update lock for item 160
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 160 end processing
2017-06-03 14:46:04 Item 182 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 182
2017-06-03 14:46:04 Trying to get update lock for item 182
2017-06-03 14:46:04 Obtained update lock for item 182
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 182 end processing
...
...
</code>```

This is the output of show engine innodb status

```<code>=====================================
2017-06-03 15:00:16 2af55a655700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 10 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 139314 srv_active, 0 srv_shutdown, 2478167 srv_idle
srv_master_thread log flush and writes: 2617481
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 139170
OS WAIT ARRAY INFO: signal count 139073
Mutex spin waits 15233, rounds 456961, OS waits 14580
RW-shared spins 123701, rounds 3711390, OS waits 123173
RW-excl spins 89, rounds 42528, OS waits 1410
Spin rounds per wait: 30.00 mutex, 30.00 RW-shared, 477.84 RW-excl
------------
TRANSACTIONS
------------
Trx id counter 233590159
Purge done for trx's n:o < 233589999 undo n:o < 0 state: running but idle
History list length 2636
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 225441219, not started
MySQL thread id 271018, OS thread handle 0x2af55a655700, query id 28702104 172.31.10.242 ebroot init
show engine innodb status
---TRANSACTION 0, not started
MySQL thread id 271017, OS thread handle 0x2af55bfa6700, query id 28698794 172.31.10.242 ebroot cleaning up
---TRANSACTION 233590158, not started
MySQL thread id 1, OS thread handle 0x2af55a550700, query id 28702102 localhost 127.0.0.1 rdsadmin cleaning up
   --------
   FILE I/O
   --------
   ...
   ...
</code>```

And this is the output of show full processlist:

Which is the pending transaction or lock here and how to kill it?

And why it did not get automatically closed when the PHP script ends?
I thought that even though a PHP thread has a Mysql connection, when the thread  exits the MySQL connection is automatically closed and the transactions/locks started by it should be automatically committed or rolled back, no ?
Thanks

答:
Ok i found the issue.

Inside the processExpiredDeferredPayments method i forgot that i was opening another transaction there, and since a transaction was already opened , Mysql raised an exception.

Now it works, both with Mysql 5.16 and 5.35. No need to upgrade for now

Thanks everybody

Body:
I have a piece of PHP code which can't execute queries anymore because of a pending lock or already open transaction on the MySql DB which i still haven't found.
The script is launched by cron every hour. The offending code is this

    CommandHelper::log("Calling beginTransaction for item $item->id");
    $transaction = Yii::app()->db->beginTransaction();
    CommandHelper::log("Trying to get update lock for item $item->id");
    try {
       // this line will lock a single row
        $item = Item::model()->findBySql("SELECT * FROM " . $item::model()->getTableSchema()->name . " WHERE id=$item->id FOR UPDATE");
        if(!$item)
            throw new Exception("Item $item->id not found in processItem");
        CommandHelper::log("Obtained update lock for item $item->id");

    $now = DateTimeHelper::getInstance()->getStringNow();
    // the following call executes a few queries and causes an exception
    $this->processExpiredDeferredPayments($item,$now);
    // we won't get here
    CommandHelper::log("Item $item->id query confirmed units");
   ....
   ....

        $transaction->commit();

    } catch (Exception $e) {
        $transaction->rollBack();
        CommandHelper::log("Transaction error:" . $e->getMessage());
    }

The log prints these lines every hour:

...
...
2017-06-03 14:46:04 Item 164 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 164
2017-06-03 14:46:04 Trying to get update lock for item 164
2017-06-03 14:46:04 Obtained update lock for item 164
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 164 end processing
2017-06-03 14:46:04 Item 160 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 160
2017-06-03 14:46:04 Trying to get update lock for item 160
2017-06-03 14:46:04 Obtained update lock for item 160
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 160 end processing
2017-06-03 14:46:04 Item 182 start processing
2017-06-03 14:46:04 Calling beginTransaction for item 182
2017-06-03 14:46:04 Trying to get update lock for item 182
2017-06-03 14:46:04 Obtained update lock for item 182
2017-06-03 14:46:04 Transaction error:There is already an active transaction
2017-06-03 14:46:04 Item 182 end processing
...
...

This is the output of show engine innodb status

=====================================
2017-06-03 15:00:16 2af55a655700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 10 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 139314 srv_active, 0 srv_shutdown, 2478167 srv_idle
srv_master_thread log flush and writes: 2617481
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 139170
OS WAIT ARRAY INFO: signal count 139073
Mutex spin waits 15233, rounds 456961, OS waits 14580
RW-shared spins 123701, rounds 3711390, OS waits 123173
RW-excl spins 89, rounds 42528, OS waits 1410
Spin rounds per wait: 30.00 mutex, 30.00 RW-shared, 477.84 RW-excl
------------
TRANSACTIONS
------------
Trx id counter 233590159
Purge done for trx's n:o < 233589999 undo n:o < 0 state: running but idle
History list length 2636
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 225441219, not started
MySQL thread id 271018, OS thread handle 0x2af55a655700, query id 28702104 172.31.10.242 ebroot init
show engine innodb status
---TRANSACTION 0, not started
MySQL thread id 271017, OS thread handle 0x2af55bfa6700, query id 28698794 172.31.10.242 ebroot cleaning up
---TRANSACTION 233590158, not started
MySQL thread id 1, OS thread handle 0x2af55a550700, query id 28702102 localhost 127.0.0.1 rdsadmin cleaning up
   --------
   FILE I/O
   --------
   ...
   ...

And this is the output of show full processlist:

Which is the pending transaction or lock here and how to kill it?

And why it did not get automatically closed when the PHP script ends?
I thought that even though a PHP thread has a Mysql connection, when the thread  exits the MySQL connection is automatically closed and the transactions/locks started by it should be automatically committed or rolled back, no ?
Thanks


问:
how to use linq to return all ints in another set of ints for this scenario?
I have the following scenario:

```<code>1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions
</code>```

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

```<code>  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();
</code>```

答:
Your code is almost correct, but instead of "Count() > 1" should be "Count() > 0".

```<code>var userIdsWithPermissions = userPermssions.Where(
                    x => x.Value.Intersect(contentPermissions).Count() > 0)
                    .Select(x => x.Key).ToArray();
</code>```

Another solution could be this:

```<code>var userIdsWithPermissions = from u in userPermssions
                             where contentPermissions.Any(p => u.Value.Contains(p))
                             select u;
</code>```

Both producing same output. Last one is faster taking just 4 ms, against 22 ms of the Intersect solution.

Body:
I have the following scenario:

1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();

Body:
Your code is almost correct, but instead of "Count() > 1" should be "Count() > 0".

var userIdsWithPermissions = userPermssions.Where(
                    x => x.Value.Intersect(contentPermissions).Count() > 0)
                    .Select(x => x.Key).ToArray();

Another solution could be this:

var userIdsWithPermissions = from u in userPermssions
                             where contentPermissions.Any(p => u.Value.Contains(p))
                             select u;

Both producing same output. Last one is faster taking just 4 ms, against 22 ms of the Intersect solution.


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答: Another, more Windows-y option (for $39) is http://www.expandrive.com/sftpdrive</p>

OwnerDisplayName: Jared

LastEditorDisplayName: Michael Haren

OwnerDisplayName: Vinko Vrsalovic


问:
Do we really need sorting in the MapReduce framework?
I am completely new to MapReduce and just can't get my mind around the need to sort the mapper output according to the keys in each partition. Eventually all we  want is that a reducer is fed a partition which consists of several pairs of <key,List of Values> and that the key in each pair is unique not just for the corresponding partition but all the partitions which are fed to different reducers.

For doing that what is the need to do a sort at any stage whatsoever. Can't we use a hash table to group the values corresponding to the same key?

To break it down for each stage. At the mapper stage, for each output  pair we simply hash the key to find the partition number and then we append the corresponding pair to a linked list of all such pairs belonging to the same partition. So at the end, the output obtained by a single mapper would be a hashtable. In  which for each partition number we have a linked list of <key,value> pairs with no key based order whatsoever i.e. no locality for similar key values .

Then the partitions from different mapper tasks are shuffled to a reducer. We now need to make sure that we first group all the values corresponding to the same key (a kind of a merge) and then feed those merged pairs of <key,List of Values> to a separate reducer function . Here again we can use a hashtable to do the same, we simply iterate through all the partition and for each key map them to an index in the hashtable and append the corresponding value to the linked list in the hashtable.
 Wouldn't this method save more time as compare to the one in which we sort the output of each mapper?

I have already gone through the link (I currently can't comment on the thread , so I wrote a separate question.) The top answer mentions that

Sorting saves time for the reducer, helping it easily distinguish when a new reduce task should start. It simply starts a new reduce task, when the next key in the sorted input data is different than the previous, to put it simply. Each reduce task takes a list of key-value pairs, but it has to call the reduce() method which takes a key-list(value) input, so it has to group values by key. It's easy to do so, if input data is pre-sorted (locally) in the map phase and simply merge-sorted in the reduce phase (since the reducers get data from many mappers)

But again we can do the same by using a hash table or can we not?

答:
Well, yeah, you could use a hash table as long as everything fits in memory. But once the amount of data you're working with exceeds your computer's memory capacity, you have a problem.

The solution is to output data to a disk file and do an external sort.


问:
VBScript Replace for character string of unknown length
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

```<code>Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub
</code>```

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.

答:
Use a regular expression (start here) to replace sequences of the string "%20" with one "/":</p>

```<code>>> s = "http://domainname.com/products/prodName%20%20%20ProdNumber"
>> Set r = New RegExp
>> r.Global = True
>> r.Pattern = "(%20)+"
>> WScript.Echo s
>> WScript.Echo r.Replace(s, "/")
>>
http://domainname.com/products/prodName%20%20%20ProdNumber
http://domainname.com/products/prodName/ProdNumber
>>
</code>```

Body:
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.

Body:
Use a regular expression (start here) to replace sequences of the string "%20" with one "/":

>> s = "http://domainname.com/products/prodName%20%20%20ProdNumber"
>> Set r = New RegExp
>> r.Global = True
>> r.Pattern = "(%20)+"
>> WScript.Echo s
>> WScript.Echo r.Replace(s, "/")
>>
http://domainname.com/products/prodName%20%20%20ProdNumber
http://domainname.com/products/prodName/ProdNumber
>>


问:
cannot call method 'then' on undefined sequelize error
I am returning a promise inside a function and and the handling the promise outside the function but I am getting cannot call method 'then' on undefined error. Can somebody point out what am I doing wrong or how can this be fixed.

```<code>function getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date){
   getNameByMeterId(sequelize, Meter, meter_id)
  .then(function(meter){
    getServerIdByMeterId(sequelize, Server, meter_id)
    .then(function(server){
      var name = meter[0].meter_id;
      var channel = "Ch"+name.substr(-1);
      var serialNumber = parseInt(name.substr(0,12));
      console.log({name:name,channel:channel,serialNumber:serialNumber});
      var server_id = server[0].server_id;
      return sequelize.query("select SUM(?) as total from dial?s where RealReadDate <= ? and SN = ?",
      {
        model:Dials[server_id],
        replacements:[channel, server_id, date.toISOString(), serialNumber],
        type: sequelize.QueryTypes.SELECT
      });
    });
  });
}

function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}

 getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Servers, meter.id, billing_id)
            .then(function(current_date_result){
              meter_obj.current = current_date_result[0].total;
});
</code>```

I am getting cannot call method 'then' error when I function callgetStartMeterReadingByMeterIdAndBillingId  . Are we allowed to return Sequelize promises like than and then handle then else where by using the function.

答:
The getStartMeterReadingByMeterIdAndBillingIdfunction does not return a promise based on your code example.

Assuming that getStartDateByBillingId returns a promise, you should change the code to:

```<code>function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   return getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}
</code>```

Body:
I am returning a promise inside a function and and the handling the promise outside the function but I am getting cannot call method 'then' on undefined error. Can somebody point out what am I doing wrong or how can this be fixed.

function getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date){
   getNameByMeterId(sequelize, Meter, meter_id)
  .then(function(meter){
    getServerIdByMeterId(sequelize, Server, meter_id)
    .then(function(server){
      var name = meter[0].meter_id;
      var channel = "Ch"+name.substr(-1);
      var serialNumber = parseInt(name.substr(0,12));
      console.log({name:name,channel:channel,serialNumber:serialNumber});
      var server_id = server[0].server_id;
      return sequelize.query("select SUM(?) as total from dial?s where RealReadDate <= ? and SN = ?",
      {
        model:Dials[server_id],
        replacements:[channel, server_id, date.toISOString(), serialNumber],
        type: sequelize.QueryTypes.SELECT
      });
    });
  });
}

function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}

 getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Servers, meter.id, billing_id)
            .then(function(current_date_result){
              meter_obj.current = current_date_result[0].total;
});

I am getting cannot call method 'then' error when I function callgetStartMeterReadingByMeterIdAndBillingId  . Are we allowed to return Sequelize promises like than and then handle then else where by using the function.

Body:
The getStartMeterReadingByMeterIdAndBillingIdfunction does not return a promise based on your code example.

Assuming that getStartDateByBillingId returns a promise, you should change the code to:

function getStartMeterReadingByMeterIdAndBillingId(sequelize, Dials, Billings, Meter, Server, meter_id, billing_id){
   return getStartDateByBillingId(sequelize,Billings,billing_id)
  .then(function(date){
    return getMeterReadingByMeterIdandDate(sequelize, Dials, Meter, Server, meter_id, date[0].start_date);
  });
}


问:
Double for loop in R creating a matrix
I would like to create a 5x5 matrix in R using two for loops.
I have 5 numbers p_j and q_i with i and j in {1,2,3,4,5}.
I would like to create a matrix with where the element in (j,i) is given by p_j * q_j. j-th row and i-th column.
So, first of all I would like to create an empty matrix m and then filling the matrix using the for loops.

for (i in 1:5){   for (j in 1:5){
         } }

答:
I will walk through two solutions that I proposed. Both of these solutions avoid any explicit looping. Mostly in R, if it is easy to avoid a loop,  you probably should.  First, let's get some example data.

```<code>set.seed(2017)
p = sample(5)
q = sample(5)
p
[1] 5 3 2 1 4
q
[1] 4 1 2 5 3
</code>```

Here p and q are randomly generated.  The set.seed part is so that we both get the same "random" numbers.

Solution 1 - matrix multiplication

```<code>p %*% t(q)
     [,1] [,2] [,3] [,4] [,5]
[1,]   20    5   10   25   15
[2,]   12    3    6   15    9
[3,]    8    2    4   10    6
[4,]    4    1    2    5    3
[5,]   16    4    8   20   12
</code>```

%*% is the way to specify matrix multiplication in R.

p %*% t(q)  multiplies the 5x1 matrix p by the 1x5 matrix t(q),  the transpose of q, resulting in the 5x5 matrix with the desired answer.

Solution 2 - outer

```<code>outer(p,q, `*`)
     [,1] [,2] [,3] [,4] [,5]
[1,]   20    5   10   25   15
[2,]   12    3    6   15    9
[3,]    8    2    4   10    6
[4,]    4    1    2    5    3
[5,]   16    4    8   20   12
</code>```

The function outer in r, creates the "outer product" of two vectors - that is, it takes all combinations of an element of p and an element of q and combines them using the function that you supplied,  in this case *,   exactly the calculation that you are asking for.   Actually,  this could have been written more succinctly as outer(p,q)  because the default function to use to combine p & q is *.

Title: Double for loop in R creating a matrix

Body:
I will walk through two solutions that I proposed. Both of these solutions avoid any explicit looping. Mostly in R, if it is easy to avoid a loop,  you probably should.  First, let's get some example data.

set.seed(2017)
p = sample(5)
q = sample(5)
p
[1] 5 3 2 1 4
q
[1] 4 1 2 5 3

Here p and q are randomly generated.  The set.seed part is so that we both get the same "random" numbers.

Solution 1 - matrix multiplication

p %*% t(q)
     [,1] [,2] [,3] [,4] [,5]
[1,]   20    5   10   25   15
[2,]   12    3    6   15    9
[3,]    8    2    4   10    6
[4,]    4    1    2    5    3
[5,]   16    4    8   20   12

%*% is the way to specify matrix multiplication in R.

p %*% t(q)  multiplies the 5x1 matrix p by the 1x5 matrix t(q),  the transpose of q, resulting in the 5x5 matrix with the desired answer.

Solution 2 - outer

outer(p,q, `*`)
     [,1] [,2] [,3] [,4] [,5]
[1,]   20    5   10   25   15
[2,]   12    3    6   15    9
[3,]    8    2    4   10    6
[4,]    4    1    2    5    3
[5,]   16    4    8   20   12

The function outer in r, creates the "outer product" of two vectors - that is, it takes all combinations of an element of p and an element of q and combines them using the function that you supplied,  in this case *,   exactly the calculation that you are asking for.   Actually,  this could have been written more succinctly as outer(p,q)  because the default function to use to combine p & q is *.