问:
Dictionary with dictonary inside to pandas dataframe
I have dict with structure like this:

```<code>{'periodicity' : 'false',
 'load' : '45',
 'cell' : '33',
 'capacity' : '20'
 'SList' : [{'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's5'},
  {'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's6'},
  {'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's7'}],
 ...}
</code>```

And I made dataframe from that dict. The problem is that I got 3 rows with exactly the same value, except the SList column, you can see why, but I need just one dict which look like this:

```<code>periodicity     load      cell     capacity                                 SList
  false          45        33         20          {'sPer' : '22','sRep' : '43','sMes' : 's5'}, {'sPer' : '22', 'sRep' : '43', 'sMes' : 's6'}, ...
</code>```

Where is the problem?

答:
Use either pd.DataFrame.from_dict by specifying that the keys of the dictionary must be passed as the index labels with orient="index" and transpose it:

```<code>pd.DataFrame.from_dict(d, orient="index").T
</code>```

Or, let json_normalize do the parsing for you directly:

```<code>from pandas.io.json import json_normalize
json_normalize(d)
</code>```

Both approaches yield:

Body:
I have dict with structure like this:

{'periodicity' : 'false',
 'load' : '45',
 'cell' : '33',
 'capacity' : '20'
 'SList' : [{'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's5'},
  {'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's6'},
  {'sPer' : '22',
   'sRep' : '43',
   'sMes' : 's7'}],
 ...}

And I made dataframe from that dict. The problem is that I got 3 rows with exactly the same value, except the SList column, you can see why, but I need just one dict which look like this:

periodicity     load      cell     capacity                                 SList
  false          45        33         20          {'sPer' : '22','sRep' : '43','sMes' : 's5'}, {'sPer' : '22', 'sRep' : '43', 'sMes' : 's6'}, ...

Where is the problem?

Body:
Use either pd.DataFrame.from_dict by specifying that the keys of the dictionary must be passed as the index labels with orient="index" and transpose it:

pd.DataFrame.from_dict(d, orient="index").T

Or, let json_normalize do the parsing for you directly:

from pandas.io.json import json_normalize
json_normalize(d)

Both approaches yield:


来源: stackexchange

问:
Ajax call Into MVC Controller- URL Issue
I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.

I have the following JavaScript code:

```<code>$.ajax({
    type: "POST",
    url: '@Url.Action("Search","Controller")',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});
</code>```

When calling the Url the post looks like:

```<code>NetworkError: 500 Internal Server Error - <a href="http://localhost/Web/Navigation/@Url.Action(%22Search%22,%22Chat%22)"></a>
</code>```

Why does it return it like this (the logic behind it) and what's a solution?

P.S.: Additional Information: %22 is the URL Encoding Reference for <<">> character

答:
starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like: </p>

```<code> $.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.

I have the following JavaScript code:

$.ajax({
    type: "POST",
    url: '@Url.Action("Search","Controller")',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

When calling the Url the post looks like:

NetworkError: 500 Internal Server Error -

Why does it return it like this (the logic behind it) and what's a solution?

P.S.: Additional Information: %22 is the URL Encoding Reference for <<">> character

Body:
starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:

 $.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

ContentLicense: CC BY-SA 3.0


问:
How do I build a c# treeview from SQL Hierarchyid?
I'm developing an C# .NET Windows Form application that 'll manage a hierarchical tree-view structure. (I have a single SQL table with a hierarchyid column. The data set is small ~300 rows/nodes at the moment, but is bound to grow large eventually)

After I exit the application, I want to be able to restart it with the last modified state. I understand I can do this by serializing it to XML.

However, I'm trying to find a method by which the treeview could be generated directly from the table at run time, using the hierarchy id column.

After Googling around, I've found some others who wish to the same, but unfortunately I've found no solutions. Is there a good way to do this?

Thanks.

答: Look for IHierarchicalEnumerable, HierarchicalDataSourceControl and HierarchicalDataSourceView. Thats exactly what are you looking for.</p>

ContentLicense: CC BY-SA 2.5


问:
Angular directive throws Error: [$injector:unpr]
I am working on an project and need to modify some code to resolve an error

directive:

```<code>(function () {
    'use strict';

    angular.module('myApp').directive("myDirective", function ($filter) {
        return {
            // code
        };
    });
})();
</code>```

This throws an error with the minified version only.
I am using angular 1.5.9

I think I need to define $filter somewhere.

答:
I assume you have the app already defined somewhere.

You seem to have not injected $filter, try this instead:

```<code>(function () {
  'use strict';

  angular.module('myApp').directive("myDirective", ["$filter", function ($filter) {
    return {
      // code
    };
  }]);
})();
</code>```

Body:
I am working on an project and need to modify some code to resolve an error

directive:

(function () {
    'use strict';

    angular.module('myApp').directive("myDirective", function ($filter) {
        return {
            // code
        };
    });
})();

This throws an error with the minified version only.
I am using angular 1.5.9

I think I need to define $filter somewhere.

Body:
I assume you have the app already defined somewhere.

You seem to have not injected $filter, try this instead:

(function () {
  'use strict';

  angular.module('myApp').directive("myDirective", ["$filter", function ($filter) {
    return {
      // code
    };
  }]);
})();


问:
How to disable the cursor but not only visually?
I want to hide the cursor until my function is done but I can't find how to disable it. I mean I have found how to hide it and show it but when it's hidden I can still click So how to disable it?

window.document.styleSheets[0].insertRule('* {cursor: none;}', window.document.styleSheets[0].cssRules.length);
Meteor.call("lockTheMachine", machine.nameMachine, Session.get("loggedUser"), function(err, res) {
  if (!err) {
    Session.set("lastMachineUsed", machine.nameMachine);
    window.document.styleSheets[0].insertRule('* {cursor: default   ;}', window.document.styleSheets[0].cssRules.length);
  } else {
    console.error(err);
  }
});
}
```

答:
There's a CSS property for that called pointer-events.

The CSS property pointer-events allows authors to control under what circumstances (if any) a particular graphic element can become the target of mouse events.

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

If you were to disable any click interaction on your whole site you could simply add:

```<code>body.block { pointer-events: none; }
</code>```

And trigger the class .block programatically via Javascript.

Body:
There's a CSS property for that called pointer-events.

The CSS property pointer-events allows authors to control under what circumstances (if any) a particular graphic element can become the target of mouse events.

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

If you were to disable any click interaction on your whole site you could simply add:

body.block { pointer-events: none; }

And trigger the class .block programatically via Javascript.


问:
Best way of reading all available bytes from socket in blocking mode, C++
What is the best way of reading from blocking socket all available bytes? 'Available' means that server response is a bunch of text lines (each with '\n') and EOF is a line with some prefix. Length of this response is always different, so I don't know it before reading. I assume using select() (poll, epoll) and then 'ioctl(FIONREAD)' is the best way, am I right? Or may be just reading all available at that moment, then checking if EOF is reached and if not, then repeating all again? Yes, it sounds more rational. Does it all make any sense? So, what is the most efficient way?

答:
If you are doing blocking reads there is little point in using select/epoll.

ioctl(FIONREAD) is a pretty useless call because by the time it returns more data may have arrived into the kernel socket buffer.

Blocking reads are easy: just keep reading into your user-space socket buffer until the message terminator is found.

Ideally, the networking components you use should not care whether the socket is in blocking or in non-blocking mode: there should be a function that is called when the socket is ready for reading. In blocking mode you would call this function regardless of whether the socket is ready, it just blocks on read if no data is available.


问:
How do I remove duplicate items from an array in Perl?
I have an array in Perl:

```<code>my @my_array = ("one","two","three","two","three");
</code>```

How do I remove the duplicates from the array?

答:
Using concept of unique hash keys :

```<code>my @array  = ("a","b","c","b","a","d","c","a","d");
my %hash   = map { $_ => 1 } @array;
my @unique = keys %hash;
print "@unique","\n";
</code>```

Output:
a c b d

Body:
I have an array in Perl:

my @my_array = ("one","two","three","two","three");

How do I remove the duplicates from the array?

LastEditorDisplayName: brian d foy

Body:
Using concept of unique hash keys :

my @array  = ("a","b","c","b","a","d","c","a","d");
my %hash   = map { $_ => 1 } @array;
my @unique = keys %hash;
print "@unique","\n";

Output:
a c b d


问:
Remote form post Python and cookies headers
I have a script to post a form from a distant web page.
This webpage sends a cookie, and I like to get this and insert it in the header to post the form.

How could I do that ?

Thank you

答:
Thanks a lot,
When I go to the website from a web browser I have this :

```<code>Cookie: __qca=P0-1275531178-1484650046149; _ga=GA1.2.1669629019.1484650088; optimizelyEndUserId=oeu1486719631164r0.37280650070167387; optimizelySegments=%7B%224541596561%22%3A%22ff%22%2C%224547081444%22%3A%22none%22%2C%224502945149%22%3A%22direct%22%2C%224547981473%22%3A%22false%22%7D; optimizelyBuckets=%7B%7D; IRF_1322=%7Bvisits%3A1%2Cuser%3A%7Btime%3A1486719631639%2Cref%3A%22direct%22%2Cpv%3A1%2Ccap%3A%7B%7D%2Cv%3A%7B%7D%7D%2Cvisit%3A%7Btime%3A1486719631639%2Cref%3A%22direct%22%2Cpv%3A1%2Ccap%3A%7B%7D%2Cv%3A%7B%7D%7D%2Clp%3A%22http%3A%2F%2Flastingmemoriesbylisa.zenfolio.com%2F%22%2Cdebug%3A0%2Ca%3A1486719631639%7D; zf_5y_visitor=s7fL-1Wogsx-E1mBu-WkZbl-5gcAAAAATer6DQw9WNnr; zf_10y_tz=120; zf_pat=256887569$labellevuephotography$$396676290$492530544; zf_lsc=NPUPdGc1+bbM3gpqJ/i3nH4o...0
</code>```

but when I use my script I online have :

```<code>zf_5y_visitor=s7fL-1Wogsx-E1mBu-WkZbl-5gcAAAAATer6DQw9WNnr; zf_10y_tz=120;
</code>```

Is that possible to get the other parts ? At least the one starting with "zf"

Body:
Thanks a lot,
When I go to the website from a web browser I have this :

Cookie: __qca=P0-1275531178-1484650046149; _ga=GA1.2.1669629019.1484650088; optimizelyEndUserId=oeu1486719631164r0.37280650070167387; optimizelySegments=%7B%224541596561%22%3A%22ff%22%2C%224547081444%22%3A%22none%22%2C%224502945149%22%3A%22direct%22%2C%224547981473%22%3A%22false%22%7D; optimizelyBuckets=%7B%7D; IRF_1322=%7Bvisits%3A1%2Cuser%3A%7Btime%3A1486719631639%2Cref%3A%22direct%22%2Cpv%3A1%2Ccap%3A%7B%7D%2Cv%3A%7B%7D%7D%2Cvisit%3A%7Btime%3A1486719631639%2Cref%3A%22direct%22%2Cpv%3A1%2Ccap%3A%7B%7D%2Cv%3A%7B%7D%7D%2Clp%3A%22http%3A%2F%2Flastingmemoriesbylisa.zenfolio.com%2F%22%2Cdebug%3A0%2Ca%3A1486719631639%7D; zf_5y_visitor=s7fL-1Wogsx-E1mBu-WkZbl-5gcAAAAATer6DQw9WNnr; zf_10y_tz=120; zf_pat=256887569$labellevuephotography$$396676290$492530544; zf_lsc=NPUPdGc1+bbM3gpqJ/i3nH4o...0

but when I use my script I online have :

zf_5y_visitor=s7fL-1Wogsx-E1mBu-WkZbl-5gcAAAAATer6DQw9WNnr; zf_10y_tz=120;

Is that possible to get the other parts ? At least the one starting with "zf"


问:
Background image that always scales so that any normal background color wouldn't appear
I wonder if there is a hack that would resize the image in the way that it would always cover the whole browser window. It should also keep the image´s aspect ratio.</p>

答:
try this code through jquery</p>

```<code> var docHeight = Math.max(

            $(document).height(),

            $(window).height(),

            /* For opera: */

            document.documentElement.clientHeight

        );

        var docWidth = Math.max(

            $(document).width(),

            $(window).width(),

            /* For opera: */

            document.documentElement.clientWidth

        );

        $("selector").css({

            "height":docHeight,

            "width":docWidth

        });
</code>```

Body:
try this code through jquery

 var docHeight = Math.max(

            $(document).height(),

            $(window).height(),

            /* For opera: */

            document.documentElement.clientHeight

        );

        var docWidth = Math.max(

            $(document).width(),

            $(window).width(),

            /* For opera: */

            document.documentElement.clientWidth

        );

        $("selector").css({

            "height":docHeight,

            "width":docWidth

        });


问:
How to disable cache in tomcat 8.0.23?
How can I disable the static-file cache in Tomcat 8.0.23?

My app.nocache.js file created by GWT is being cached by Tomcat. Anytime I recompile, Tomcat is serving the old version of the file.

I would be happy to disable Tomcat's cache for any file containing "nocache" in it's name. Fully disabling Tomcat's cache would do as well.

I have tried:

<Resources
         cachingAllowed="false"
         cacheMaxSize="0"
    />

in my WEB-INF/context.xml file, or:

<Context cachingAllowed="false" cacheMaxSize="0">

...but neither of these attempts have succeeded in disabling the cache.

答: I simply changed a line in my context.xml to read <Context antiResourceLocking="false">. The default value was set to 'true' (Tomcat 8.0.39).

Title: How to disable cache in tomcat 8.0.23?


问:
Manifest Merger Failed when allow backup is made false
In the android manifest file,when i make android:allowBackup="true" to android:allowBackup="false" then it through me the error of maifest murger failed.

My Manifest File is :

```<code> <?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.goturbo">

    <application
        android:allowBackup="false"
        android:icon="@mipmap/trucks"
        android:label="@string/app_name"
        android:supportsRtl="true"
        tools:replace="android:icon"
        android:theme="@style/AppTheme">

       <activity
            android:name="com.goturbo.FragmentContainerActivity"
            android:windowSoftInputMode="adjustResize"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 </manifest>
</code>```

Error:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs
</code>```

答:
The android documentation says

Whether to allow the application to participate in the backup and
  restore infrastructure. If this attribute is set to false, no backup
  or restore of the application will ever be performed, even by a
  full-system backup that would otherwise cause all application data to
  be saved via adb. The default value of this attribute is true.

https://developer.android.com/guide/topics/manifest/application-element.html

So if you dont mention the allowbackup you should be fine.

Body:
In the android manifest file,when i make android:allowBackup="true" to android:allowBackup="false" then it through me the error of maifest murger failed.

My Manifest File is :

 <?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.goturbo">

    <application
        android:allowBackup="false"
        android:icon="@mipmap/trucks"
        android:label="@string/app_name"
        android:supportsRtl="true"
        tools:replace="android:icon"
        android:theme="@style/AppTheme">

       <activity
            android:name="com.goturbo.FragmentContainerActivity"
            android:windowSoftInputMode="adjustResize"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 </manifest>

Error:

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs


问:
Multiple class selecting in CSS
```<code>.upload header {...}
</code>```

Styling will be applied to any header that is a child of any element with class of '.upload'.

Is it possible to do this?

```<code>.upload header, form {...}
</code>```

Or will I have to specify the class for every type selector ?

答:
You could do this with two selectors. First set your styles with * and then reset the same styles if you only want it to be applied to the first child element.</p>

```<code>.upload *:first-child {
    background: blue;
}

.upload *:first-child *:first-child {
    background: none;
}
</code>```

Title: Multiple class selecting in CSS

Body:
.upload header {...}

Styling will be applied to any header that is a child of any element with class of '.upload'.

Is it possible to do this?

.upload header, form {...}

Or will I have to specify the class for every type selector ?

Body:
You could do this with two selectors. First set your styles with * and then reset the same styles if you only want it to be applied to the first child element.

.upload *:first-child {
    background: blue;
}

.upload *:first-child *:first-child {
    background: none;
}


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
Create an Anti-corruption (DDD) layer for the existing library... this is nothing but a facade.. and then write unit-test for this anti-corruption layer... Now even if someone upgrade/update the library you would know if something is broken by running the unit tests...

These tests could also serve as documentation of contract... and not every project that need to use the library has to write this anti -corruption layer, if they are using the same exact functionality..

OwnerDisplayName: Andrei

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe

OwnerDisplayName: StackUnderflow


问:
Create Own Column Property in SQL
i want to create my one own property for every column.

ex. every column has description property but i require one more property for me.

i want required for auto code generate from that property.

what is best way for that?

答:
Using Extended Properties on Database Objects

To add a new extended property to the SafetyStockLevel of the dbo.Product table use the following command:

```<code>EXEC sys.sp_addextendedproperty
  @name = N'MS_DescriptionExample',
  @value = N'Minimum inventory quantity.',
  @level0type = N'SCHEMA', @level0name = dbo,
  @level1type = N'TABLE',  @level1name = Product,
  @level2type = N'COLUMN', @level2name = SafetyStockLevel;
</code>```

Title: Create Own Column Property in SQL

Body:
Using Extended Properties on Database Objects

To add a new extended property to the SafetyStockLevel of the dbo.Product table use the following command:

EXEC sys.sp_addextendedproperty
  @name = N'MS_DescriptionExample',
  @value = N'Minimum inventory quantity.',
  @level0type = N'SCHEMA', @level0name = dbo,
  @level1type = N'TABLE',  @level1name = Product,
  @level2type = N'COLUMN', @level2name = SafetyStockLevel;


问:
Implement AES encryption in Image
```<code>if (i < 1 && j < textBox3.TextLength)
{
    char letter = Convert.ToChar(textBox3.Text.Substring(j, 1));
    // int value = Convert.ToInt32(letter);
    //Encryption Mechanism here
    AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
    int quote = Convert.ToInt32(textBox3.Text);
    string quote1 = Convert.ToString(quote) + 12;
    aesCSP.GenerateKey();
    aesCSP.GenerateIV();
    byte[] encQuote = EncryptString(aesCSP, quote1);
    string enc = Convert.ToBase64String(encQuote);
    int nerd = Convert.ToInt32(enc);
    img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, nerd));
}
</code>```

here i am  trying to implement an AES encryption on the string which i want to input from the user which i will then store those encrypted values in an array of integers. My problem is that even tough after converting a string to an int variable , i am not able to put that int value into the setpixel() method.

答:
The documentation for Color.FromArgb( int alpha, int red, int green, int blue) states:

Although this method allows a 32-bit value to be passed for each
  component, the value of each component is limited to 8 bits.

You don't state what the value of nerd is when you run your code, and you also don't actually state what the problem is, but this is a common issue with people using this method and not understanding that this limitation exists.

Check your code, debug and put a break point at the call to Color.FromArgb and be mindful of this limitation.

Title: Implement AES encryption in Image

Body:
if (i < 1 && j < textBox3.TextLength)
{
    char letter = Convert.ToChar(textBox3.Text.Substring(j, 1));
    // int value = Convert.ToInt32(letter);
    //Encryption Mechanism here
    AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
    int quote = Convert.ToInt32(textBox3.Text);
    string quote1 = Convert.ToString(quote) + 12;
    aesCSP.GenerateKey();
    aesCSP.GenerateIV();
    byte[] encQuote = EncryptString(aesCSP, quote1);
    string enc = Convert.ToBase64String(encQuote);
    int nerd = Convert.ToInt32(enc);
    img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, nerd));
}

here i am  trying to implement an AES encryption on the string which i want to input from the user which i will then store those encrypted values in an array of integers. My problem is that even tough after converting a string to an int variable , i am not able to put that int value into the setpixel() method.


问:
Spoon JAR for local testing
I'm trying to test making changes to the Spoon source (trying to learn how it all works) but can't figure out how to build the final jar (with dependencies similar to the one available from the site) that we can then use to run independently.

I tried running the ./gradlew build and ./gradlew install with some minor code changes and everything builds successfully but I can't locate the JAR that works properly. :(

Any help / documentation related to the build/release process would be much appreciated.

答:
Import project in Intellij Idea (not Android studio)

Import project from external model Gradle

Next -> Finish

Then you'll receive

Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

Create local.properties file in root directory with following content:

```<code>sdk.dir=/Users/yourusername/Library/Android/sdk
</code>```

If you see problems with gradle, press on gradle menu (tab at the right side) and click on synchronize/refresh button.

Open Project Structure -> Modules. Click + -> Import module -> spoon-client -> Import module from external model Gradle -> Next -> Next.
Do the same procedure for spoon-runner and click Apply.

Open Project Structure -> Artifacts. Click + -> JAR -> From modules with dependencies...
Select spoon-client, leave Main class empty, press OK.
Do the same procedure for spoon-runner. Click Apply -> OK.

Click Build -> Build Artifacts... -> All artifacts.

JARs will be created at the location you have specified in the Artifacts menu.

Title: Spoon JAR for local testing

Body:
Import project in Intellij Idea (not Android studio)

Import project from external model Gradle

Next -> Finish

Then you'll receive

Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

Create local.properties file in root directory with following content:

sdk.dir=/Users/yourusername/Library/Android/sdk

If you see problems with gradle, press on gradle menu (tab at the right side) and click on synchronize/refresh button.

Open Project Structure -> Modules. Click + -> Import module -> spoon-client -> Import module from external model Gradle -> Next -> Next.
Do the same procedure for spoon-runner and click Apply.

Open Project Structure -> Artifacts. Click + -> JAR -> From modules with dependencies...
Select spoon-client, leave Main class empty, press OK.
Do the same procedure for spoon-runner. Click Apply -> OK.

Click Build -> Build Artifacts... -> All artifacts.

JARs will be created at the location you have specified in the Artifacts menu.


问:
How can I change the color of a button each time I try to click on it?
I have a question recording to the code I wrote today. I know that I can change the backgroundcolor of the button, but just once (with: button2.BackColor = Color.Yellow;). But now, I have a problem.

The color should change each time I try to click on the button. How does it work? Thank you for your help.

This is my code. I programmed something funny: when you try to click the button, it disappears and appears elsewhere :).
¨

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Random cox = new Random();

    private void button2_MouseMove(object sender, MouseEventArgs e)
    {
        int x = cox.Next(500);
        int y = cox.Next(500);
        button2.Left = x;
        button2.Top = y;
    }
}
</code>```

答:
Besically you have 2 options: Either keep an array of colors and choose a color randomly from that array on each click, or generate a random color on each click.

option 1:

```<code>// inside your form:
Color[] colors = new Color[] {Color.Yellow, Color.Green, Color.Red};

// inside the button click event handler:
button2.BackColor = colors[col.Next(0,colors.Length)];
</code>```

option2:

```<code>// inside the button click event handler:

button2.BackColor = new Color(col.Next(0,256), col.Next(0,256), col.Next(0,256));
</code>```

Of course, both options use the Random instance named col in the code you provided.

Body:
I have a question recording to the code I wrote today. I know that I can change the backgroundcolor of the button, but just once (with: button2.BackColor = Color.Yellow;). But now, I have a problem.

The color should change each time I try to click on the button. How does it work? Thank you for your help.

This is my code. I programmed something funny: when you try to click the button, it disappears and appears elsewhere :).
¨

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Random cox = new Random();

    private void button2_MouseMove(object sender, MouseEventArgs e)
    {
        int x = cox.Next(500);
        int y = cox.Next(500);
        button2.Left = x;
        button2.Top = y;
    }
}

Body:
Besically you have 2 options: Either keep an array of colors and choose a color randomly from that array on each click, or generate a random color on each click.

option 1:

// inside your form:
Color[] colors = new Color[] {Color.Yellow, Color.Green, Color.Red};

// inside the button click event handler:
button2.BackColor = colors[col.Next(0,colors.Length)];

option2:

// inside the button click event handler:

button2.BackColor = new Color(col.Next(0,256), col.Next(0,256), col.Next(0,256));

Of course, both options use the Random instance named col in the code you provided.


问:
Keep getting undeclared identifier I error caesar
I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later. </p>

<p>Here's my code: </p>

```<code>int main(int argc, string argv[])
{
    // get key from command line argument, return 1 if wrong
    if (argc < 2)
    {
        printf("No value entered!\n");
        return 1;
    }

    //store key in integer
    int k = atoi(argv[1]);

    if (k < 0)
    {
        printf("No right variable detected\n");
        return 1;
    }
    else
    {
        printf("Plain text: \n");
        string s = get_string();

        // iterate over strings in argv
        for (int i = 0; n = strlen(s); i < n; i++);
        {
            if (isalpha(s[i]))
            {
                // for capitalized letters
                if (isupper(s[i]))
                {
                    int a = s[i] - 65;
                    int b = (a + k) % 26;
                    int c = b + 65;
                    printf("%c", c);
                }

                //for lowercase
                else
                {
                    int d = s[i] - 97;
                    int e = (d + k) % 26;
                    int f = e + 97;
                    printf("%c", f);
                }
            }
            else
            {
                //for non alphabetical characters
                printf("%c", s[i]);
            }
        }
    }
    // print new line
    printf("\n");
    return 0;
}
</code>```

答:
For loop is wrong, it accepts 3 parameters, you set it 4.

Also, notice semicolon after your for loop.

This line:

```<code>for (int i = 0; n = strlen(s); i < n; i++);
</code>```

should be:

```<code>for (int i = 0, n = strlen(s); i < n; i++)
</code>```

Notice comma and no semi-colon at the end

Body:
I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later.

Here's my code:

int main(int argc, string argv[])
{
    // get key from command line argument, return 1 if wrong
    if (argc < 2)
    {
        printf("No value entered!\n");
        return 1;
    }

    //store key in integer
    int k = atoi(argv[1]);

    if (k < 0)
    {
        printf("No right variable detected\n");
        return 1;
    }
    else
    {
        printf("Plain text: \n");
        string s = get_string();

        // iterate over strings in argv
        for (int i = 0; n = strlen(s); i < n; i++);
        {
            if (isalpha(s[i]))
            {
                // for capitalized letters
                if (isupper(s[i]))
                {
                    int a = s[i] - 65;
                    int b = (a + k) % 26;
                    int c = b + 65;
                    printf("%c", c);
                }

                //for lowercase
                else
                {
                    int d = s[i] - 97;
                    int e = (d + k) % 26;
                    int f = e + 97;
                    printf("%c", f);
                }
            }
            else
            {
                //for non alphabetical characters
                printf("%c", s[i]);
            }
        }
    }
    // print new line
    printf("\n");
    return 0;
}

Body:
For loop is wrong, it accepts 3 parameters, you set it 4.

Also, notice semicolon after your for loop.

This line:

for (int i = 0; n = strlen(s); i < n; i++);

should be:

for (int i = 0, n = strlen(s); i < n; i++)

Notice comma and no semi-colon at the end


问:
Adding global title to Plots.jl subplots
I would like to add a global title to a group of subplots using Plots.jl.

Ideally, I'd do something like:

```<code>using Plots
pyplot()
plot(rand(10,2), plot_title="Main title", title=["A" "B"], layout=2)
</code>```

but, as per the Plots.jl documentation, the plot_title attribute is not yet implemented:

Title for the whole plot (not the subplots) (Note: Not currently implemented)

In the meanwhile, is there any way around it?

I'm currently using the pyplot backend, but I'm not especially tied to it.

答:
When using the pyplot backend, you can use PyPlot commands to alter a Plots figure, cf. Accessing backend specific functionality with Julia Plots.

To set a title for the whole figure, you could do something like:

```<code>using Plots
p1 = plot(sin, title = "sin")
p2 = plot(cos, title = "cos")
p = plot(p1, p2, top_margin=1cm)
import PyPlot
PyPlot.suptitle("Trigonometric functions")
PyPlot.savefig("suptile_test.png")
</code>```

One needs to explicitly call PyPlot.savefig to see the effect of the PyPlot functions.

Note that all changes made using the PyPlot interface will be overwritten when you use a Plots function.

Body:
I would like to add a global title to a group of subplots using Plots.jl.

Ideally, I'd do something like:

using Plots
pyplot()
plot(rand(10,2), plot_title="Main title", title=["A" "B"], layout=2)

but, as per the Plots.jl documentation, the plot_title attribute is not yet implemented:

Title for the whole plot (not the subplots) (Note: Not currently implemented)

In the meanwhile, is there any way around it?

I'm currently using the pyplot backend, but I'm not especially tied to it.

Body:
When using the pyplot backend, you can use PyPlot commands to alter a Plots figure, cf. Accessing backend specific functionality with Julia Plots.

To set a title for the whole figure, you could do something like:

using Plots
p1 = plot(sin, title = "sin")
p2 = plot(cos, title = "cos")
p = plot(p1, p2, top_margin=1cm)
import PyPlot
PyPlot.suptitle("Trigonometric functions")
PyPlot.savefig("suptile_test.png")

One needs to explicitly call PyPlot.savefig to see the effect of the PyPlot functions.

Note that all changes made using the PyPlot interface will be overwritten when you use a Plots function.


问:
How to reload node_modules' jar and js?
I have some react-native questions:

1) I have added some console.log() in

```<code>node_modules\react-native\ReactAndroid\src\androidTest\assets\AndroidTestBundle.js
</code>```

However, when I try "react-native run-android" in Windows command, the debug panel does not show it. Should I run another command before run-android?

2) In addition, I have changed the java files in

```<code>node_modules\react-native\android\com\facebook\react\react-native\0.42.3\react-native-0.42.3-sources.jar
</code>```

but it seems that it does not auto compile the jar again. Should I run any command first?

Thanks.

答:
For your first question:

The React Packager usually doesn't listen to any changes to files inside the node_modules folder. If you make any changes to JS files inside the node_modules folder, then you will have to kill the packager (ctrl+c) and start it again using react-native start command. Then you can see the result of modifications to JS files inside the node_modules folder

And for your second question:

React Packager cannot compile native code in real-time it only compiles the JS files and delivers them to the device. So, if you make any changes to native code JAVA/Swift or Obj-C(for iOS) you need to build the app again using react-native run-android command for Android, react-native run-ios for iOS simulator. (manually re-run the build through XCode if you are testing on real iPhone)

Title: How to reload node_modules' jar and js?

Body:
I have some react-native questions:

1) I have added some console.log() in

node_modules\react-native\ReactAndroid\src\androidTest\assets\AndroidTestBundle.js

However, when I try "react-native run-android" in Windows command, the debug panel does not show it. Should I run another command before run-android?

2) In addition, I have changed the java files in

node_modules\react-native\android\com\facebook\react\react-native\0.42.3\react-native-0.42.3-sources.jar

but it seems that it does not auto compile the jar again. Should I run any command first?

Thanks.


问:
How to change the value of array element in list of arrays? (C#)
I have list of arrays of labels and I want to change visibility of some label in some array in list by index. Tell me, please, how can I do that?</p>

答:
You said you want to change visibility of your labels with indexes. So something like that:  </p>

```<code>List<Label[]> labels;//your labels

Label[] firstArray=labels[0];
Label[] secondArray=labels[1];
...

Label firstLabelInFirstArray=firstArray[0]; //get first label
Label secondLabelInFirstArray=firstArray[1]; //get second label

firstLabelInFirstArray.Visible=true; //In Windows Forms
firstLabelInFirstArray.Visibility=Visibility.Hidden; //In WPF
</code>```

Body:
You said you want to change visibility of your labels with indexes. So something like that:

List<Label[]> labels;//your labels

Label[] firstArray=labels[0];
Label[] secondArray=labels[1];
...

Label firstLabelInFirstArray=firstArray[0]; //get first label
Label secondLabelInFirstArray=firstArray[1]; //get second label

firstLabelInFirstArray.Visible=true; //In Windows Forms
firstLabelInFirstArray.Visibility=Visibility.Hidden; //In WPF


问:
Php Simple HTML DOM Parser - how to work with block repeats
I have blocks of
 but without attributes. After that go blocks of
 without attributes.

Structure of this looked like this:

```<code><h2></h2>
<p></p>
<p></p>
<p></p>
<h2></h2>
<p></p>
<p></p>
<h2></h2>
<p></p>
</code>```

I'm using Php Simple HTML DOM Parser. I want to get data from
 block, after that get all
 to another
 and so on.

But all
 must be connected to
 which go after them. I thought to use key => value (example
 =>
,
,... and another
) but I am not sure how to do this.

Also, I know about next_sibling(), but don't know how to use it in loop. I did 2 variables, 1st has all
, 2nd has
. I thought it can be useful for my goal. Here is the code:

```<code>$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
  echo $test2 . '<br>';
  foreach($test->find('p') as $test3) {
    echo $test3 .'<br>';
  }
}
</code>```

答:
It's not super clear what you're looking for but here's an idea to get you started:</p>

```<code>foreach($html->find('h2') as $el){
  $h2 = $el;
  while($el = $el->next_sibling()){
    if('p' != $el->tag) break;
    // do something
  }
}
</code>```

Body:
I have blocks of
 but without attributes. After that go blocks of
 without attributes.

Structure of this looked like this:

I'm using Php Simple HTML DOM Parser. I want to get data from
 block, after that get all
 to another
 and so on.

But all
 must be connected to
 which go after them. I thought to use key => value (example
 =>
,
,... and another
) but I am not sure how to do this.

Also, I know about next_sibling(), but don't know how to use it in loop. I did 2 variables, 1st has all
, 2nd has
. I thought it can be useful for my goal. Here is the code:

$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
  echo $test2 . '
';
  foreach($test->find('p') as $test3) {
    echo $test3 .'
';
  }
}

Body:
It's not super clear what you're looking for but here's an idea to get you started:

foreach($html->find('h2') as $el){
  $h2 = $el;
  while($el = $el->next_sibling()){
    if('p' != $el->tag) break;
    // do something
  }
}


问:
TestNg's @BeforeTest on base class only happening once per fixture
I'm trying to use @BeforeTest to get code to ... run once before every test.

This is my code:

```<code>public class TestBase {
    @BeforeTest
    public void before() {
        System.out.println("BeforeTest");
    }
}

public class TestClass extends TestBase{
    @Test
    public void test1(){}

    @Test
    public void test2(){}
}
</code>```

"BeforeTest" is only printed once, not twice. What am I doing wrong?

答:
Use @BeforeMethod, not @BeforeTest.

The meaning of @BeforeTest is explained in the documentation.

Body:
I'm trying to use @BeforeTest to get code to ... run once before every test.

This is my code:

public class TestBase {
    @BeforeTest
    public void before() {
        System.out.println("BeforeTest");
    }
}

public class TestClass extends TestBase{
    @Test
    public void test1(){}

    @Test
    public void test2(){}
}

"BeforeTest" is only printed once, not twice. What am I doing wrong?


问:
In C why can I pass function name (not a pointer) as parameter to funtion?
I have test the following code:

```<code>#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}
</code>```

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

```<code>void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}
</code>```

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

答:
The C standard ISO/IEC 9899:2011, section 6.3.2.1 item 4 says:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator,65) or the unary & operator, a function designator with type “function returning type” is converted to an expression that has type “pointer to function returning type”.

So normally a function name (or other expression with function type, i.e. a function designator) is converted to a pointer to a function, except in the circumstances mentioned above.

So what happens when you apply the & operator to a function, as that is one of the cases excluded from the above clause. The answer is given by section 6.5.3.3 item 3, the relevant parts of which are:

The unary & operator yields the address of its operand. If the operand has type “type”, the result has type “pointer to type”. [...] Otherwise, the result is a pointer to the object or function designated by its operand.

(The "[...]" part I missed out discusses applying the & operator to the result of a unary * operator and to the result of the [] operator.)

So applying & to a function name (or other function designator) also gives you a pointer to the function.

So what happens when you dereference a function pointer with the unary * operator? It produces a function designator (section 6.5.3.3 item 4), which in most circumstances (as discussed above) gets converted back to a pointer to a function!

EDIT: I neglected to mention the case of declaring a parameter of a function to be a function returning type. As discussed in Vlad from Moscow's answer referring to section 6.7.6.3 item 8, that gets automatically adjusted to be a pointer to a function returning type.

Body:
I have test the following code:

#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?


问:
Apache Beam count HBase row block and not return
Start to try out the Apache Beam and try to use it to read and count HBase table. When try to read the table without the Count.globally, it can read the row, but when try to count number of rows, the process hung and never exit.

Here is the very simple code:

```<code>Pipeline p = Pipeline.create(options);

p.apply("read",    HBaseIO.read().withConfiguration(configuration).withTableId(HBASE_TABLE))
  .apply(ParDo.of(new DoFn<Result, String>() {
   @ProcessElement
   public void processElement(ProcessContext c) {
        Result result = c.element();
        String rowkey = Bytes.toString(result.getRow());
        System.out.println("row key: " + rowkey);
        c.output(rowkey);
   }
}))
.apply(Count.<String>globally())
.apply("FormatResults", MapElements.via(new SimpleFunction<Long, String>() {
      public String apply(Long element) {
          System.out.println("result: " + element.toString());
          return element.toString();
      }
 }));
</code>```

when use Count.globally, the process never finish. When comment it out, the process print all the rows.

Anyy ideas?

答:
Which version of beam are you using?

Thanks for bringing this issue. I tried to reproduce your case and indeed there seems to be an issue with colliding versions of guava that breaks transforms with HBaseIO. I sent a pull request to fix the shading of this, I will keep you updated once it is merged so you can test if it works.

Thanks again.

Body:
Start to try out the Apache Beam and try to use it to read and count HBase table. When try to read the table without the Count.globally, it can read the row, but when try to count number of rows, the process hung and never exit.

Here is the very simple code:

Pipeline p = Pipeline.create(options);

p.apply("read",    HBaseIO.read().withConfiguration(configuration).withTableId(HBASE_TABLE))
  .apply(ParDo.of(new DoFn<Result, String>() {
   @ProcessElement
   public void processElement(ProcessContext c) {
        Result result = c.element();
        String rowkey = Bytes.toString(result.getRow());
        System.out.println("row key: " + rowkey);
        c.output(rowkey);
   }
}))
.apply(Count.<String>globally())
.apply("FormatResults", MapElements.via(new SimpleFunction<Long, String>() {
      public String apply(Long element) {
          System.out.println("result: " + element.toString());
          return element.toString();
      }
 }));

when use Count.globally, the process never finish. When comment it out, the process print all the rows.

Anyy ideas?


问:
the running application have different layout than the preview
While running the application the design layout is not same as in the preview as all the widgets are overlapping at the top-left corner no matter where I place them.

答:
Can we see your code please.
Perhaps you're using a Relativelayout without specifying the position with its attribute. </p>


问:
How can I exclude a specific file from TFS source control
We have multiple config files (app.DEV.config, app.TEST.config, etc) and a pre-build event that copies the correct config file to app.config.  Obviously the configuration specific files are in source control --- but at the moment so is App.Config, and that shouldn't be.

How can I mark that one file as excluded from source control, but obviously not from the project.

I'm using VS 2005, and 2005 Team Explorer.

答: Select the App.config file in Solution Explorer, and choose File -> Source Control -> Exclude App.config from Source Control.</p>


问:
MessagePack : MessageTypeException: Expected raw value, but got boolean [Android]
I am implementing MessagePack in my android application. I am getting following error while deserializing Response data only when app runs in below API 22 devices;

```<code>Caused by: org.msgpack.MessageTypeException: Expected raw value, but got boolean
at org.msgpack.unpacker.Accept.acceptBoolean(Accept.java:33)
at org.msgpack.unpacker.MessagePackUnpacker.readOneWithoutStackLarge(MessagePackUnpacker.java:154)
at org.msgpack.unpacker.MessagePackUnpacker.readOneWithoutStack(MessagePackUnpacker.java:139)
at org.msgpack.unpacker.MessagePackUnpacker.readOne(MessagePackUnpacker.java:73)
at org.msgpack.unpacker.MessagePackUnpacker.readString(MessagePackUnpacker.java:472)
at org.msgpack.template.StringTemplate.read(StringTemplate.java:46)
at org.msgpack.template.StringTemplate.read(StringTemplate.java:25)
at org.msgpack.template.builder.ReflectionTemplateBuilder$FieldTemplateImpl.read(ReflectionTemplateBuilder.java:70)
at org.msgpack.template.builder.ReflectionTemplateBuilder$ReflectionClassTemplate.read(ReflectionTemplateBuilder.java:143)
</code>```

If I run same application in device with API 22 or above everything works fine.

Following code is for deserialize ;

```<code>private T readMessagePack(byte[] response, Class<T> responseType) throws Exception
    {
        MessagePack msgpack = new MessagePack();
        TemplateRegistry registry = new TemplateRegistry(null);
        ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry);
        Template<T> objTemplate = builder.buildTemplate(responseType);
        BufferUnpacker unpacker = msgpack.createBufferUnpacker();
        unpacker.resetReadByteCount();
        unpacker.wrap(response);
        return objTemplate.read(unpacker, null);

    }
</code>```

I am using org.msgpack:msgpack:0.6.8 Dependency.

答:
After doing research I solved my issue. May be my answer will helpful to someone.

This issue is caused by the order of declared fields that BufferUnpacker returns. For that we have to use @Index() annotation while Serializing & Deserializing.
For example;

```<code>@Index(0)
    public boolean state;
@Index(1)
    public String error_message;
</code>```

Body:
I am implementing MessagePack in my android application. I am getting following error while deserializing Response data only when app runs in below API 22 devices;

Caused by: org.msgpack.MessageTypeException: Expected raw value, but got boolean
at org.msgpack.unpacker.Accept.acceptBoolean(Accept.java:33)
at org.msgpack.unpacker.MessagePackUnpacker.readOneWithoutStackLarge(MessagePackUnpacker.java:154)
at org.msgpack.unpacker.MessagePackUnpacker.readOneWithoutStack(MessagePackUnpacker.java:139)
at org.msgpack.unpacker.MessagePackUnpacker.readOne(MessagePackUnpacker.java:73)
at org.msgpack.unpacker.MessagePackUnpacker.readString(MessagePackUnpacker.java:472)
at org.msgpack.template.StringTemplate.read(StringTemplate.java:46)
at org.msgpack.template.StringTemplate.read(StringTemplate.java:25)
at org.msgpack.template.builder.ReflectionTemplateBuilder$FieldTemplateImpl.read(ReflectionTemplateBuilder.java:70)
at org.msgpack.template.builder.ReflectionTemplateBuilder$ReflectionClassTemplate.read(ReflectionTemplateBuilder.java:143)

If I run same application in device with API 22 or above everything works fine.

Following code is for deserialize ;

private T readMessagePack(byte[] response, Class<T> responseType) throws Exception
    {
        MessagePack msgpack = new MessagePack();
        TemplateRegistry registry = new TemplateRegistry(null);
        ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry);
        Template<T> objTemplate = builder.buildTemplate(responseType);
        BufferUnpacker unpacker = msgpack.createBufferUnpacker();
        unpacker.resetReadByteCount();
        unpacker.wrap(response);
        return objTemplate.read(unpacker, null);

    }

I am using org.msgpack:msgpack:0.6.8 Dependency.

Body:
After doing research I solved my issue. May be my answer will helpful to someone.

This issue is caused by the order of declared fields that BufferUnpacker returns. For that we have to use @Index() annotation while Serializing & Deserializing.
For example;

@Index(0)
    public boolean state;
@Index(1)
    public String error_message;


问:
Understand the flow of touch event in HTML5 , JavaScript
In my project when we are touching one button another button is getting selected. I can not share the code here. But I am trying to understand the flow of the touch event.
My understanding is :

We click a button

Browser detects the event and let the HTML5 know.

HTML5 raises that as an event (like click)

HTML5 passes that to the JavaScript's event handlers.

So may be the  page.x and page.y co-ordinates detected  by the browser are wrong.
Kindly let me know if my understanding is wrong of the flow of touch event.

答:
Check whether are you using same class for the buttons.

This may also due to event may get bubbled up this can be prevented by using event.stopPropagation().

Check this link https://api.jquery.com/event.stoppropagation/.

This is what i can suggest, if not please post a detail explanation.


问:
Python os.system enter commands to execute in CLI application
I am currently writing a program to help me with some database administration. It's supposed to execute commands in MariaDB. I thought since this is a CLI application I can just do that with os.system, but I'm having problems doing so. So lets say I have the following code

```<code>import os

os.system('mysql --user=%s --password=%s' %(user, password)
os.system('USE database;')
</code>```

This code logs me into MariaDB, but it does not execute the second command to choose the database. Is this possible with os.system, and if not, what are my alternatives? Thanks.

Edit: I tried using subprocess instead, which gives me another problem: It immediately exits MariaDB after logging in.

答:
I recomand you to use Subprocess instead of os python module, using Popen

try to check this link out :
Calling an external command in Python

Body:
I am currently writing a program to help me with some database administration. It's supposed to execute commands in MariaDB. I thought since this is a CLI application I can just do that with os.system, but I'm having problems doing so. So lets say I have the following code

import os

os.system('mysql --user=%s --password=%s' %(user, password)
os.system('USE database;')

This code logs me into MariaDB, but it does not execute the second command to choose the database. Is this possible with os.system, and if not, what are my alternatives? Thanks.

Edit: I tried using subprocess instead, which gives me another problem: It immediately exits MariaDB after logging in.


问:
Replace content present in the nested brackets
Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))

Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW

Tried so far

```<code>Output = Input.replace(/ *\([^)]*\)*/g, "");
</code>```

答:
Using a regex here probably won't work, or scale, because you expect nested parentheses in your input string.  Regex works well when there is a known and fixed structure to the input.  Instead, I would recommend that you approach this using a parser.  In the code below, I iterate over the input string, one character at at time, and I use a counter to keep track of how many open parentheses there are.  If we are inside a parenthesis term, then we don't record those characters.  I also have one simple replacement at the end to remove whitespace, which is an additional step which your output implies, but you never explicitly mentioned.

var pCount = 0;
var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = "";
for (var i=0; i < Input.length; i++) {
    if (Input[i] === '(') {
        pCount++;
    }
    else if (Input[i] === ')') {
        pCount--;
    }
    else if (pCount == 0) {
        Output += Input[i];
    }
}

Output = Output.replace(/ /g,'');
console.log(Output);```

Body:
Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))

Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW

Tried so far

Output = Input.replace(/ *\([^)]*\)*/g, "");


问:
Shell Script for adding base_url to the php files
I have a website setup in which there are a lot of files mostly php. But in this i am calling the files as say /model/login/......

I want to rename all such occurences as $base_url/model/login/....

How can I approach the problem or where can I get the tutorials for the same.

答:
sed can do this trivially, provided you don't use the path for anything else in the code.</p>

```<code>sed -i 's!/model/login/!$base_url&!g' foo.php
</code>```

Body:
sed can do this trivially, provided you don't use the path for anything else in the code.

sed -i 's!/model/login/!$base_url&!g' foo.php


问:
My modelstate is always invalid even if there are no errors on the data entered by the user
Hi I have a method in my controller and has the following code

```<code>if (ModelState.IsValid)

{

    IDataOperations ops = DataSession.GetDataOperations(null);
    List<Department> dept = new List<Department>();
    ops.Load(dept);
    ops.Commit();
    int deptId = dept[dept.Count - 1].Id + 1;
    Department department = new Department()
    {
      Id = deptId,
      CompanyId = deptModel.CompanyId,
      Active = deptModel.Active,
      Name = deptModel.Name
    };

    ops.Create(department);
    ops.Commit();
    return RedirectToAction("CompanyDepartment", "Task");
}

else

{
  //some code
</code>```

Every time the page runs it always goes to the else part, meaning model-state is invalid.
How do I check where the error in the page is, what code can I add to show where the error in the page is.

Thank you

答: Generate the field automatically when create view and copy the required fields then make some of them hidden as you want </p>

Body:
Hi I have a method in my controller and has the following code

if (ModelState.IsValid)

{

    IDataOperations ops = DataSession.GetDataOperations(null);
    List<Department> dept = new List<Department>();
    ops.Load(dept);
    ops.Commit();
    int deptId = dept[dept.Count - 1].Id + 1;
    Department department = new Department()
    {
      Id = deptId,
      CompanyId = deptModel.CompanyId,
      Active = deptModel.Active,
      Name = deptModel.Name
    };

    ops.Create(department);
    ops.Commit();
    return RedirectToAction("CompanyDepartment", "Task");
}

else

{
  //some code

Every time the page runs it always goes to the else part, meaning model-state is invalid.
How do I check where the error in the page is, what code can I add to show where the error in the page is.

Thank you


问:
Maven - How to find correct groupId/artifactId to include dependency in POM
In general, what is the best strategy for finding the groupId and artifactId for a well-known dependency for use in a Maven POM? For example, how would I find the correct entry for the MySQL JDBC driver? It's not mentioned on the mysql.com site, so I would usually spend time looking for another POM that already uses the Maven repository version of the jar. This can't be the best way.</p>

答:
1. Go to http://search.maven.org

2. Search in the required jar with groupId/artifactId or Just with basic text.

Like for your case


问:
Auto scaling using cloud formation according to Request count
We are using cloud formation for auto scaling according based upon the load balancer RequestCount metric. Currently we scale up an instance if the request is increased to 1500 for 1 minute (each instance can handle 1500 request per minute). The problem is, since the autoscaling group continually checks the RequestCount and adds a new instance if the request count is greater than 1500 for 1 min. But it is not required as I now have 2 instances which can handle 3000 req. per minute. Is there any facility to make matrices custom? i.e. if new instance is added then the scale up policy will change to 3000 req.

Example scenario:

Initially there is 1 ELB, 1 tomcat instance attached to ELB(can
handle 1500 req. per min).

1 cloud watch with action of scale up ploicy if the req. count on ELB is increased to 1500 for min.

Currently request load on ELB is 1500 for 1 min. now req. load is increased to 1700 for min. so it will attach a new tomcat
instance on ELB. So i have 2 instance which can handle 3000 req. for
min.

But now what problem is cloud watch still check the req. count on ELB and if req. load is 1700 for min. it will add one new tomcat
instance which is not required.

How can i over come from this problem?

答:
I've made the scaling based on RequestCount work by applying Scaling Policy with associated Cloudwatch alarms that trigger policy evaulation. Below you'll find cloudformation template that I've used in ElasticBeanstalk app:

```<code>   RequestCountScalingAlarmLt2000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when Request Count < 2000"
       AlarmName: {"Fn::Join": ["-", ["Scale when Request Count < 2000", { "Ref":"AWSEBEnvironmentName" }]]}
       ComparisonOperator: LessThanThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 2000
   RequestCountScalingAlarmGt2000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 2000 < Request Count < 20000"
       AlarmName: "Scale when Request 2000 < Count < 20000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 2000
   RequestCountScalingAlarmGt20000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 20000 < Request Count < 30000"
       AlarmName: "Scale when 20000 < Request Count < 30000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 20000
   RequestCountScalingAlarmGt30000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 30000 < Request Count < 40000"
       AlarmName: "Scale when 30000 < Request Count < 40000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 30000
   RequestCountScalingAlarmGt40000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions::
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 40000 < Request Count < 50000"
       AlarmName: "Scale when 40000 < Request Count < 50000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 40000
   RequestCountScalingAlarmGt50000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 50000 < Request Count < 60000"
       AlarmName: "Scale when 50000 < Request Count < 60000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 50000
   RequestCountScalingAlarmGt60000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions::
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 60000 < Request Count < 70000"
       AlarmName: "Scale when 60000 < Request Count < 70000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 60000
   RequestCountScalingAlarmGt70000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when Request Count >= 70000"
       AlarmName: "Scale when Request Count >= 70000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 70000
   RequestCountScalingPolicy:
     Type: "AWS::AutoScaling::ScalingPolicy"
     Properties:
       AutoScalingGroupName:
         Ref: "AWSEBAutoScalingGroup"
       AdjustmentType: "ExactCapacity"
       PolicyType: "StepScaling"
       EstimatedInstanceWarmup: 120
       StepAdjustments:
         -
           MetricIntervalLowerBound: "0"
           MetricIntervalUpperBound: "2000"
           ScalingAdjustment: "1"
         -
           MetricIntervalLowerBound: "2000"
           MetricIntervalUpperBound: "20000"
           ScalingAdjustment: "2"
         -
           MetricIntervalLowerBound: "20000"
           MetricIntervalUpperBound: "30000"
           ScalingAdjustment: "3"
         -
           MetricIntervalLowerBound: "30000"
           MetricIntervalUpperBound: "40000"
           ScalingAdjustment: "4"
         -
           MetricIntervalLowerBound: "40000"
           MetricIntervalUpperBound: "50000"
           ScalingAdjustment: "5"
         -
           MetricIntervalLowerBound: "50000"
           MetricIntervalUpperBound: "60000"
           ScalingAdjustment: "6"
         -
           MetricIntervalLowerBound: "60000"
           MetricIntervalUpperBound: "70000"
           ScalingAdjustment: "7"
         -
           MetricIntervalLowerBound: "70000"
           ScalingAdjustment: "8"
</code>```

Body:
I've made the scaling based on RequestCount work by applying Scaling Policy with associated Cloudwatch alarms that trigger policy evaulation. Below you'll find cloudformation template that I've used in ElasticBeanstalk app:

   RequestCountScalingAlarmLt2000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when Request Count < 2000"
       AlarmName: {"Fn::Join": ["-", ["Scale when Request Count < 2000", { "Ref":"AWSEBEnvironmentName" }]]}
       ComparisonOperator: LessThanThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 2000
   RequestCountScalingAlarmGt2000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 2000 < Request Count < 20000"
       AlarmName: "Scale when Request 2000 < Count < 20000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 2000
   RequestCountScalingAlarmGt20000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 20000 < Request Count < 30000"
       AlarmName: "Scale when 20000 < Request Count < 30000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 20000
   RequestCountScalingAlarmGt30000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 30000 < Request Count < 40000"
       AlarmName: "Scale when 30000 < Request Count < 40000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 30000
   RequestCountScalingAlarmGt40000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions::
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 40000 < Request Count < 50000"
       AlarmName: "Scale when 40000 < Request Count < 50000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 40000
   RequestCountScalingAlarmGt50000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 50000 < Request Count < 60000"
       AlarmName: "Scale when 50000 < Request Count < 60000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 50000
   RequestCountScalingAlarmGt60000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions::
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when 60000 < Request Count < 70000"
       AlarmName: "Scale when 60000 < Request Count < 70000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 60000
   RequestCountScalingAlarmGt70000:
     Type: "AWS::CloudWatch::Alarm"
     Properties:
       ActionsEnabled: true
       AlarmActions:
         - Ref: RequestCountScalingPolicy
       OKActions:
         - Ref: RequestCountScalingPolicy
       AlarmDescription: "Scale when Request Count >= 70000"
       AlarmName: "Scale when Request Count >= 70000"
       ComparisonOperator: GreaterThanOrEqualToThreshold
       Dimensions:
         - Name: LoadBalancerName
           Value:
             Ref: AWSEBLoadBalancer
       EvaluationPeriods: "1"
       MetricName: RequestCount
       Namespace: AWS/ELB
       Period: "300"
       Statistic: Sum
       Threshold: 70000
   RequestCountScalingPolicy:
     Type: "AWS::AutoScaling::ScalingPolicy"
     Properties:
       AutoScalingGroupName:
         Ref: "AWSEBAutoScalingGroup"
       AdjustmentType: "ExactCapacity"
       PolicyType: "StepScaling"
       EstimatedInstanceWarmup: 120
       StepAdjustments:
         -
           MetricIntervalLowerBound: "0"
           MetricIntervalUpperBound: "2000"
           ScalingAdjustment: "1"
         -
           MetricIntervalLowerBound: "2000"
           MetricIntervalUpperBound: "20000"
           ScalingAdjustment: "2"
         -
           MetricIntervalLowerBound: "20000"
           MetricIntervalUpperBound: "30000"
           ScalingAdjustment: "3"
         -
           MetricIntervalLowerBound: "30000"
           MetricIntervalUpperBound: "40000"
           ScalingAdjustment: "4"
         -
           MetricIntervalLowerBound: "40000"
           MetricIntervalUpperBound: "50000"
           ScalingAdjustment: "5"
         -
           MetricIntervalLowerBound: "50000"
           MetricIntervalUpperBound: "60000"
           ScalingAdjustment: "6"
         -
           MetricIntervalLowerBound: "60000"
           MetricIntervalUpperBound: "70000"
           ScalingAdjustment: "7"
         -
           MetricIntervalLowerBound: "70000"
           ScalingAdjustment: "8"


问:
ng-model not selecting the radio button
I have an input type radio inside a ng-repeat.
The entire div is loaded in a popup, so i am accessing the controller property via parentScope.

```<code><div ng-repeat="name in parentScope.PatientInfo">
      <input type="radio" id="select-radio-{{$index}}" ng-class="{'radio-btn':true, 'newpaymentmethod1' : true}"
        ng-model="parentScope.nameObject"  name="object">
</div>
</code>```

I am getting the value for parentScope.PatientInfo, but my input type radio is not getting selected by default or on click either.
I tried giving value and ng-value to my input type radio, but all in vain.

答:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {

  $scope.selected = {
    "name": "",
    "zipCode": "",
    "addressType": "",
    "message": ""
  };
  $scope.items = [{
    "name": "newyork",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }, {
    "name": "toronto",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }, {
    "name": "california",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }];
  $scope.MessageDelivery = function(name) {
    $scope.selected.message = "Will be Delivered to " + name;

  };
  $scope.getItems = function() {
    return $scope.items;
  };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myController">
    <div>Which one?</div>
    <label class="radio" ng-repeat="item in getItems()">
          <input type="radio" ng-model="selected.name" name="itemOptions" ng-change="MessageDelivery(item.name)" value="{{item.name}}">{{item.name}} - {{item.zipCode}} - {{item.addressType}}
        </label>
    <hr />
    <div>You picked: {{selected.name}} - {{selected.message}} </div>
  </div>
</div></code>```

Title: ng-model not selecting the radio button

Body:
I have an input type radio inside a ng-repeat.
The entire div is loaded in a popup, so i am accessing the controller property via parentScope.

      <input type="radio" id="select-radio-{{$index}}" ng-class="{'radio-btn':true, 'newpaymentmethod1' : true}"
        ng-model="parentScope.nameObject"  name="object">

I am getting the value for parentScope.PatientInfo, but my input type radio is not getting selected by default or on click either.
I tried giving value and ng-value to my input type radio, but all in vain.

Body:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {

  $scope.selected = {
    "name": "",
    "zipCode": "",
    "addressType": "",
    "message": ""
  };
  $scope.items = [{
    "name": "newyork",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }, {
    "name": "toronto",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }, {
    "name": "california",
    "zipCode": "80166",
    "addressType": "shipToHome",
    "message": "test"
  }];
  $scope.MessageDelivery = function(name) {
    $scope.selected.message = "Will be Delivered to " + name;

  };
  $scope.getItems = function() {
    return $scope.items;
  };

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myController">
    <div>Which one?</div>
    <label class="radio" ng-repeat="item in getItems()">
          <input type="radio" ng-model="selected.name" name="itemOptions" ng-change="MessageDelivery(item.name)" value="{{item.name}}">{{item.name}} - {{item.zipCode}} - {{item.addressType}}
        </label>
    <hr />
    <div>You picked: {{selected.name}} - {{selected.message}} </div>
  </div>
</div>


问:
Error:(2, 0) Plugin with id 'com.github.dcendents.android-maven' not found in android
I use the following library to add material design to my android project

https://github.com/boxme/SquareCamera

But after importing it as a module, I get the following error. How can I fix it

```<code>Error:(2, 0) Plugin with id 'com.github.dcendents.android-maven' not found.
</code>```

答:
Update buildscript dependencies where your build.gradle file located in
Your_Project/build.gradle

classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' // This line you need to add

    }
}
</code>```

Body:
I use the following library to add material design to my android project

https://github.com/boxme/SquareCamera

But after importing it as a module, I get the following error. How can I fix it

Error:(2, 0) Plugin with id 'com.github.dcendents.android-maven' not found.

Body:
Update buildscript dependencies where your build.gradle file located in
Your_Project/build.gradle

classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' // This line you need to add

    }
}


问:
Keep getting undeclared identifier I error caesar
I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later. </p>

<p>Here's my code: </p>

```<code>int main(int argc, string argv[])
{
    // get key from command line argument, return 1 if wrong
    if (argc < 2)
    {
        printf("No value entered!\n");
        return 1;
    }

    //store key in integer
    int k = atoi(argv[1]);

    if (k < 0)
    {
        printf("No right variable detected\n");
        return 1;
    }
    else
    {
        printf("Plain text: \n");
        string s = get_string();

        // iterate over strings in argv
        for (int i = 0; n = strlen(s); i < n; i++);
        {
            if (isalpha(s[i]))
            {
                // for capitalized letters
                if (isupper(s[i]))
                {
                    int a = s[i] - 65;
                    int b = (a + k) % 26;
                    int c = b + 65;
                    printf("%c", c);
                }

                //for lowercase
                else
                {
                    int d = s[i] - 97;
                    int e = (d + k) % 26;
                    int f = e + 97;
                    printf("%c", f);
                }
            }
            else
            {
                //for non alphabetical characters
                printf("%c", s[i]);
            }
        }
    }
    // print new line
    printf("\n");
    return 0;
}
</code>```

答:
You have a ; at the end of for loop

```<code>for (int i = 0; n = strlen(s); i < n; i++);
                                          ^
</code>```

Change it to

```<code>for (int i = 0, n = strlen(s); i < n; i++)
</code>```

Moreover, as you can see init must be placed before the first semicolon ,(comma) separated.

Side notes

You should avoid to use "magic numbers" in code. In your case you can simply use

You should use variable names that can make your code more readable

You can do your ashing with a single variable, not 6

```<code>if (isalpha(s[i]))
{
    int ashed;

    // for capitalized letters
    if (isupper(s[i]))
    {
        ashed = s[i] - 'A';
        ashed = (ashed + k) % 26;
        ashed += 'A';
    }

    //for lowercase
    else
    {
        ashed = s[i] - 'a';
        ashed = (ashed + k) % 26;
        ashed += 'a';
    }
    printf("%c", ashed);
}
</code>```

Body:
I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later.

Here's my code:

int main(int argc, string argv[])
{
    // get key from command line argument, return 1 if wrong
    if (argc < 2)
    {
        printf("No value entered!\n");
        return 1;
    }

    //store key in integer
    int k = atoi(argv[1]);

    if (k < 0)
    {
        printf("No right variable detected\n");
        return 1;
    }
    else
    {
        printf("Plain text: \n");
        string s = get_string();

        // iterate over strings in argv
        for (int i = 0; n = strlen(s); i < n; i++);
        {
            if (isalpha(s[i]))
            {
                // for capitalized letters
                if (isupper(s[i]))
                {
                    int a = s[i] - 65;
                    int b = (a + k) % 26;
                    int c = b + 65;
                    printf("%c", c);
                }

                //for lowercase
                else
                {
                    int d = s[i] - 97;
                    int e = (d + k) % 26;
                    int f = e + 97;
                    printf("%c", f);
                }
            }
            else
            {
                //for non alphabetical characters
                printf("%c", s[i]);
            }
        }
    }
    // print new line
    printf("\n");
    return 0;
}

Body:
You have a ; at the end of for loop

for (int i = 0; n = strlen(s); i < n; i++);
                                          ^

Change it to

for (int i = 0, n = strlen(s); i < n; i++)

Moreover, as you can see init must be placed before the first semicolon ,(comma) separated.

Side notes

You should avoid to use "magic numbers" in code. In your case you can simply use

You should use variable names that can make your code more readable

You can do your ashing with a single variable, not 6

if (isalpha(s[i]))
{
    int ashed;

    // for capitalized letters
    if (isupper(s[i]))
    {
        ashed = s[i] - 'A';
        ashed = (ashed + k) % 26;
        ashed += 'A';
    }

    //for lowercase
    else
    {
        ashed = s[i] - 'a';
        ashed = (ashed + k) % 26;
        ashed += 'a';
    }
    printf("%c", ashed);
}


问:
Get all fields using Generics
Task:
You need to get all fields of a specified class, including private and inluding fields from all superclasses.
Usuall approach is to get fields recusivly:

```<code>private static void getAllFieldsRecursive(List<Field> fields, Class<?> type) {
    fields.addAll(Arrays.asList(type.getDeclaredFields()));
    if (type.getSuperclass() != null) {
        getAllFieldsRecursive(fields, type.getSuperclass());
    }
}
</code>```

However the case doesn't cover overridden fields.
Running code for:

```<code>class A {String myfield; String otherAField}
class B extends class A {String myField; String otherBField}
</code>```

will give result:
String B.myfield; String B.otherBField; String A.myfield, String A.otherField

Using Set will not help, because String A.myfield doesn't equal B.myfield

Solution below

答:
```<code>/**
 * Collect all fields declared, including superclasses.
 * @param type class
 * @return
 */
public static List<Field> getAllFields(Class<?> type) {
    List<Field> fields = new ArrayList<>();
    getAllFieldsRecursive(fields, type);
    return fields;
}

/**
 * Get fields recursively, starting from child.
 * Starting from child is important to support fields overriding.
 * @param fields all fields collected
 * @param type currently scanned class
 * Example:
 * class A {String myfield; String otherField}
 * class B extends class A {String myField; String bField}
 * Result: String B.myfield; String B.bField; String A.otherField
 */
private static void getAllFieldsRecursive(List<Field> fields, Class<?> type) {
    List<Field> declaredFields = Arrays.asList(type.getDeclaredFields()); //Start from child
    for (Field declaredField : declaredFields){
        if (!genericContainsField(declaredField, fields))
            fields.add(declaredField); //if field is not overridden in child, add it
    }
    if (type.getSuperclass() != null) {
        getAllFieldsRecursive(fields, type.getSuperclass());
    }
}

/**
 *
 * @param declaredField field we are comparing
 * @param fields current fields list
 * @return
 */
private static boolean genericContainsField(Field declaredField, List<Field> fields){
    for (Field field:fields){
        if (genericEqualsFields(field, declaredField))
            return true;
    }
    return false;
}

/**
 * Compares this {@code Field} against the specified object.  Returns
 * true if the objects are the same.  Two {@code Field} objects are the same if
 * they were have the same name and type.
 * Declared by the same class is NOT needed
 * Hack for Generic lookup, based on Field.equals()
 */
private static boolean genericEqualsFields(Field obj, Field other) {
    return (obj.getName() == other.getName())
            && (obj.getType() == other.getType());
}
</code>```

Title: Get all fields using Generics

Body:
Task:
You need to get all fields of a specified class, including private and inluding fields from all superclasses.
Usuall approach is to get fields recusivly:

private static void getAllFieldsRecursive(List<Field> fields, Class<?> type) {
    fields.addAll(Arrays.asList(type.getDeclaredFields()));
    if (type.getSuperclass() != null) {
        getAllFieldsRecursive(fields, type.getSuperclass());
    }
}

However the case doesn't cover overridden fields.
Running code for:

class A {String myfield; String otherAField}
class B extends class A {String myField; String otherBField}

will give result:
String B.myfield; String B.otherBField; String A.myfield, String A.otherField

Using Set will not help, because String A.myfield doesn't equal B.myfield

Solution below


问:
How to Start SQL Server without TempDB
After the scheduled maintenance when the DBA tried to start the SQL Server;
it failed due to some corruption issue with storage subsystem.

Later on,  we identified that the drive on which we had our TempDB's data and log files was corrupt and it was preventing SQL Server from starting successfully.
(Drive was corrupt, so I am unable to read anything from that drive)

So basically we did not have Tempdb database on the server.

And we had to start SQL Server without TempDB

So how do we start the SQL Server without TempDB and how do we fix this?

答: What version of SQL Server it is? One simple solution is to move the tempdb.* files from that location and restart the SQL Server it will create new tempdb files. If you keep those files in that same location it will fail to start.</p>

Title: How to Start SQL Server without TempDB