问:
why md-row-select not worked in md-data-table?
I use the md-data-table and md-row-select , all things worked ok but md-row-select has no effect, can some one help me? my code:

<md-data-table-container>

 {{domain}}

                #
                类型
                线路
                记录键
                记录值
                切换类型
                切换线路
                切换记录键
                切换记录值

                {{record.record_id}}
                {{ record.record_type }}
                {{ input.net_type_from }}
                {{ record.host_record }}
                {{ record.record_value }}
                {{ record.to.record_type }}
                {{ input.net_type_to }}
                {{ record.to.host_record }}
                {{ record.to.record_value }}

</md-data-table-container>```

答:
Make

```<code>md-row-select = "true"
</code>```

This should work out.

Body:
Make

md-row-select = "true"

This should work out.


来源: stackexchange

问:
How to use the #Requires keyword for DLLs?
How can I use the #Requires keyword to check for a specific dll? This is the code I have got, which requires the file Microsoft.Search.Interop.dll to be in the same folder as the script.

```<code># Load DLL containing classes & interfaces
Add-Type -path "Microsoft.Search.Interop.dll"

# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass

# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")

# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()
</code>```

答:
A simple function to test for existence of an assembly should suffice, if all you want is to check for existence of a specific assembly in the filesystem (i.e. in the same folder as the script) or in the GAC.

The function will accept an assembly name with or without a path. It tests for an assembly in the script folder (if no path element). Then if searchGAC param specified, tests for existence in the GAC. If it finds the assembly anywhere, it will load it, otherwise, will throw an exception.

```<code># requires function
function Get-Assembly ([string]$dllName, [switch]$searchGAC) {
  if ($dllName.Split('\\').Count -eq 1) {
    $dllName = Join-Path $PSScriptRoot $dllName
  }
  if (Test-Path $dllName -PathType Leaf) {
    Add-Type -path $dllName
  } else {
    $found = $false
  }
  if (!$found -and $searchGAC) {
    $dllName = ($dllName -split '\\')[-1]
    $assembly = [appdomain]::CurrentDomain.GetAssemblies() | Select -ExpandProperty Modules | where {$_.Name -match $dllName}
    if ($assembly) {
      [void][System.Reflection.Assembly]::Load($assembly.Assembly.FullName)
      $found = $true
    }
  }
  if (!$found) {
    throw [System.IO.FileNotFoundException] "$dllName not found."
  }
}
Set-Alias -Name Requires -Value Get-Assembly -Force

# your code from here, with the requires added in
# Load DLL containing classes & interfaces
Requires -dllName 'Microsoft.Search.Interop.dll' -searchGAC

# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass

# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")

# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I use the #Requires keyword to check for a specific dll? This is the code I have got, which requires the file Microsoft.Search.Interop.dll to be in the same folder as the script.

# Load DLL containing classes & interfaces
Add-Type -path "Microsoft.Search.Interop.dll"

# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass

# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")

# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()

Body:
A simple function to test for existence of an assembly should suffice, if all you want is to check for existence of a specific assembly in the filesystem (i.e. in the same folder as the script) or in the GAC.

The function will accept an assembly name with or without a path. It tests for an assembly in the script folder (if no path element). Then if searchGAC param specified, tests for existence in the GAC. If it finds the assembly anywhere, it will load it, otherwise, will throw an exception.

# requires function
function Get-Assembly ([string]$dllName, [switch]$searchGAC) {
  if ($dllName.Split('\\').Count -eq 1) {
    $dllName = Join-Path $PSScriptRoot $dllName
  }
  if (Test-Path $dllName -PathType Leaf) {
    Add-Type -path $dllName
  } else {
    $found = $false
  }
  if (!$found -and $searchGAC) {
    $dllName = ($dllName -split '\\')[-1]
    $assembly = [appdomain]::CurrentDomain.GetAssemblies() | Select -ExpandProperty Modules | where {$_.Name -match $dllName}
    if ($assembly) {
      [void][System.Reflection.Assembly]::Load($assembly.Assembly.FullName)
      $found = $true
    }
  }
  if (!$found) {
    throw [System.IO.FileNotFoundException] "$dllName not found."
  }
}
Set-Alias -Name Requires -Value Get-Assembly -Force

# your code from here, with the requires added in
# Load DLL containing classes & interfaces
Requires -dllName 'Microsoft.Search.Interop.dll' -searchGAC

# Provides methods for controlling the Search service. This
# interface manages settings and objects that affect the search engine
# across catalogs.
#
# https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass

# Retrieves a catalog by name and creates a new ISearchCatalogManager
# object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")

# Resets the underlying catalog by rebuilding the databases
# and performing a full indexing.
#
# https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()


问:
Why can minValue == maxValue in Random.Next?
http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx

Apparently maxValue is an exclusive upper bound. So Random.Next(2,3) will always return 2. Random.Next(2,2) will also always return 2. Why do you suppose they even allow the min to be equal to the max in this case? It's misleading!

答:
Looks like just a bit of poor design to me. I agree that maxValue should be strictly greater than minValue - and it should throw an ArgumentOutOfRangeException if they're equal.

There are a few aspects to Random which I dislike - for one thing, it would be really nice to have it properly pluggable (in a well-documented way) so that you could have a subclass using a cryptographically secure source. It's possible now, but you basically need to know too much about the implementation, and which methods call which other ones :(

The gotchas around creating a new Random instance each time you go round a loop, and the obvious "fix" (a static variable) not being thread-safe are other annoyances.

Basically, I'm not terribly surprised to see another little wart :(

ContentLicense: CC BY-SA 2.5


问:
NuGet command line has been stopped working
i cant built a solution, and this errors occurs ,
the error window is given below. how can i solve this error.enter image description here</p>

答: I installed .Net framework 4.5 it is working for me</p>


问:
Working with Pandas DataFrame / Sorting
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

```<code>import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)
</code>```

答:
```<code>df.groupby('Final PAC ID').head(50).reset_index(drop=True)
</code>```

Title: Working with Pandas DataFrame / Sorting

Body:
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)


问:
clear the Visual Studio OUTPUT window programmatically
is it possible to have a way to clear the Visual Studio OUTPUT window, programmatically for a C++ program? Today I use OutputDebugString call to write there, and at some point I want to clear it. Is this possible?

I use VS2008

答:
There is an answer, but it's not what you really want.

```<code>printf("\f");
</code>```

will print a form feed to the console. That is supposed to clear it. In fact modern consoles store histories which are hard to clear in a definite way.

Body:
There is an answer, but it's not what you really want.

printf("\f");

will print a form feed to the console. That is supposed to clear it. In fact modern consoles store histories which are hard to clear in a definite way.


问:
Restrict Access Page for Particular user in PHP
There are 3 users in my database

```<code>id username  password
 1  bhaku     123
 2  navin     124
 3  avinash   123
</code>```

I want restrict page access. User 'bhaku' will able to access the Page after login. & another users cannot access by loggin in or directly.

I used below code;

```<code>session_start();
    if($_SESSION["full_name"]!="bhaskar")
            {
            header('Location: index.php');
            }
</code>```

but its throwing "Indirect Loops" error.

and any user can access the page.

So what's the solution?

答:
try to print the name of the $['full_name'] and make sure you are getting what you are expecting to get.

the check using

```<code><?php
session_start();
    if(isset($_SESSION['full_name'] && $_SESSION['full_name'] == "bhaskaran")
    {
    // redirect where you want to move this user
       header('Location: index.php');
       exit;
    }
?>
</code>```

One more point is that it would be easier to redirect using id rather than name because name can be in uppercase and it might be subject to potential security issue.

If you have similar group of people whom you want to provide extra access then as mentioned about create a separate field which stores their access rights. Set it to 1 or anything you want and include it in the if () clause to check if that is also set or not.

I hope this would help you. Please, let me know if you need any further information.

Body:
There are 3 users in my database

id username  password
 1  bhaku     123
 2  navin     124
 3  avinash   123

I want restrict page access. User 'bhaku' will able to access the Page after login. & another users cannot access by loggin in or directly.

I used below code;

session_start();
    if($_SESSION["full_name"]!="bhaskar")
            {
            header('Location: index.php');
            }

but its throwing "Indirect Loops" error.

and any user can access the page.

So what's the solution?

Body:
try to print the name of the $['full_name'] and make sure you are getting what you are expecting to get.

the check using

<?php
session_start();
    if(isset($_SESSION['full_name'] && $_SESSION['full_name'] == "bhaskaran")
    {
    // redirect where you want to move this user
       header('Location: index.php');
       exit;
    }
?>

One more point is that it would be easier to redirect using id rather than name because name can be in uppercase and it might be subject to potential security issue.

If you have similar group of people whom you want to provide extra access then as mentioned about create a separate field which stores their access rights. Set it to 1 or anything you want and include it in the if () clause to check if that is also set or not.

I hope this would help you. Please, let me know if you need any further information.


问:
My_sine: what is wrong with my function?
Okay, so I have tried everything I could think of and haven't been able to figure out how to get this program working. I have tested all the functions used in the main, but included them anyway just in case there is some bug in them. More than likely though, I believe my mistake is in the main.</p>

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

#define PI 3.14159265359

double int_power(double x, int e);

int main()
{
    int my_factorial(int n);
    double my_sine_taylor(double x);
    double my_sine(double x);
    double mod_two_pi(double x);
    double get_double(void);
    void safeGetString(char arr[], int limit)

    char arr[255];
    double x,y,ans;

    printf("Enter a number: ");
    safeGetString(arr[255],255);
    my_sine(mod_two_pi(get_double()));
    printf("The sine is %f \n", ans);

    return 0;
}

/*
int_power should compute x^e, where x is a double and e is an integer.
*/
double int_power(double x, int e)
{
    int i = 0;
    double ans = 1;
    while(i <= e)
    {
        ans = ans*x;
        i++;
    }

    return ans;
}

/*
my_factorial will find the factorial of n
*/
int my_factorial(int n)
{
    int i = n;
    int ans = 1;

    while(i > 0)
    {
        ans = ans*i;
        i = i-1;
    }

    return ans;
}

/*
my_sine_taylor computes the approxmiation
of sin(x) using the taylor series up through x^11/11!
*/
double my_sine_taylor(double x)
{
    return x - int_power(x,3)/my_factorial(3) + int_power(x,5)/my_factorial(5) -
    int_power(x,7)/my_factorial(7) + int_power(x,9)/my_factorial(9) -
    int_power(x,11)/my_factorial(11);
}

/*
my_sine(x) should return a very good approximation of sin(x).
It should first reduce x mod 2pi and then map the result into the
upper right quadrant (where the taylor approximation is quite accurate).
Finally, it should use my_sine_taylor to compute the answer.
*/

double my_sine(double x)
{
    double ans;

    if (x >= 0 && x <= PI/2){
        ans = my_sine_taylor(x);
    } else if (x > PI/2 && x <= PI){
        x=PI-x;
        ans = my_sine_taylor(x);
    } else if (x > PI && x <= 3*(PI/2)){
        x = x-PI;
        ans = -(my_sine_taylor(x));
    } else {
        x=2*PI-x;
        ans = -(my_sine_taylor(x));
    }
}

/*
mod_two_pi(x) should return the remainder when x
is divided by 2*pi.  This reduces values like
17pi/2 down to pi/2
*/
double mod_two_pi(double x)
{
    int y;
    y = floor(x/(2*PI));
    x = x - 2*PI*y;
    return x;
}

/*
get_double and safeGetString are used to get floating point
input from the user
*/
double get_double(void)
{
    double x;
    char arr[255];
    x=atof(arr);
}

void safeGetString(char arr[], int limit)
{
    int c, i;
    i = 0;

    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}
</code>```

答:
oh my... where to begin?

Let's see...

You have this function:

```<code>double get_double(void)
{

    double x;

    char arr[255];

    x=atof(arr);
}
</code>```

Which you call like this:

```<code>my_sine(mod_two_pi(get_double()));
</code>```

So you're not sending it anything, but you're expecting to get some meaningful value.  Basically, arr[255] is not initialized, so it holds garbage. You're taking this garbage and converting it to a float with atof, but that doesn't do anything.

If I had to guess, I'd say that this is what's really breaking your program. The rest of what I wrote below is just commentary.

For some reason, you're declaring all of these functions inside your main.  I don't think this should break anything, but it sure is bad coding style.

my_sine_taylor calculates using a 6-element taylor approximation of the sine.  Are you sure you need that accuracy?  11! is pretty large, and certain numbers to the 11th power can also be pretty large.  You may be introducing unnecessary rounding or overflow errors with this.

Body:
Okay, so I have tried everything I could think of and haven't been able to figure out how to get this program working. I have tested all the functions used in the main, but included them anyway just in case there is some bug in them. More than likely though, I believe my mistake is in the main.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.14159265359

double int_power(double x, int e);

int main()
{
    int my_factorial(int n);
    double my_sine_taylor(double x);
    double my_sine(double x);
    double mod_two_pi(double x);
    double get_double(void);
    void safeGetString(char arr[], int limit)

    char arr[255];
    double x,y,ans;

    printf("Enter a number: ");
    safeGetString(arr[255],255);
    my_sine(mod_two_pi(get_double()));
    printf("The sine is %f \n", ans);

    return 0;
}

/*
int_power should compute x^e, where x is a double and e is an integer.
*/
double int_power(double x, int e)
{
    int i = 0;
    double ans = 1;
    while(i <= e)
    {
        ans = ans*x;
        i++;
    }

    return ans;
}

/*
my_factorial will find the factorial of n
*/
int my_factorial(int n)
{
    int i = n;
    int ans = 1;

    while(i > 0)
    {
        ans = ans*i;
        i = i-1;
    }

    return ans;
}

/*
my_sine_taylor computes the approxmiation
of sin(x) using the taylor series up through x^11/11!
*/
double my_sine_taylor(double x)
{
    return x - int_power(x,3)/my_factorial(3) + int_power(x,5)/my_factorial(5) -
    int_power(x,7)/my_factorial(7) + int_power(x,9)/my_factorial(9) -
    int_power(x,11)/my_factorial(11);
}

/*
my_sine(x) should return a very good approximation of sin(x).
It should first reduce x mod 2pi and then map the result into the
upper right quadrant (where the taylor approximation is quite accurate).
Finally, it should use my_sine_taylor to compute the answer.
*/

double my_sine(double x)
{
    double ans;

    if (x >= 0 && x <= PI/2){
        ans = my_sine_taylor(x);
    } else if (x > PI/2 && x <= PI){
        x=PI-x;
        ans = my_sine_taylor(x);
    } else if (x > PI && x <= 3*(PI/2)){
        x = x-PI;
        ans = -(my_sine_taylor(x));
    } else {
        x=2*PI-x;
        ans = -(my_sine_taylor(x));
    }
}

/*
mod_two_pi(x) should return the remainder when x
is divided by 2*pi.  This reduces values like
17pi/2 down to pi/2
*/
double mod_two_pi(double x)
{
    int y;
    y = floor(x/(2*PI));
    x = x - 2*PI*y;
    return x;
}

/*
get_double and safeGetString are used to get floating point
input from the user
*/
double get_double(void)
{
    double x;
    char arr[255];
    x=atof(arr);
}

void safeGetString(char arr[], int limit)
{
    int c, i;
    i = 0;

    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}

Body:
oh my... where to begin?

Let's see...

You have this function:

double get_double(void)
{

    double x;

    char arr[255];

    x=atof(arr);
}

Which you call like this:

my_sine(mod_two_pi(get_double()));

So you're not sending it anything, but you're expecting to get some meaningful value.  Basically, arr[255] is not initialized, so it holds garbage. You're taking this garbage and converting it to a float with atof, but that doesn't do anything.

If I had to guess, I'd say that this is what's really breaking your program. The rest of what I wrote below is just commentary.

For some reason, you're declaring all of these functions inside your main.  I don't think this should break anything, but it sure is bad coding style.

my_sine_taylor calculates using a 6-element taylor approximation of the sine.  Are you sure you need that accuracy?  11! is pretty large, and certain numbers to the 11th power can also be pretty large.  You may be introducing unnecessary rounding or overflow errors with this.


问:
How to pass Json string with variable in c#?
```<code>string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";
</code>```

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

答:
```<code>string a = "a";
string b = "b";

string jSonContent = (@"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}").Replace(@":""summary""", a).Replace("modified.", b);
</code>```

Body:
string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!


问:
Response content-type text/html while expected application/json
I have the same application on two different servers. On one server there is everything OK the application is loaded correctly. On the second server the application can't load. The error message is Unexpected token < in JSON at position 0. When I open developer tools in a browser I see that response content type header on the second server is text/html while on the first server is application/json what it should be.
On both servers in IIS MIME Types is .json  application/json.
What else could block the corect content type on the second server?</p>

答:
Here is one of possible answers:
In our case it turned out that the cause was IIS setting, actually Application Pool setting. Instead of using Integrated, we had it switched to Classic.
When using Classic Application Pool in IIS, all JSON media type responses were converted automatically http/text.

Switching it back to Integrated Application Pool solved the issue.
Hope it helps somebody.
Radek


问:
Javascript RegExp for matching different values with $ (dollar sign) as part of the string
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

```<code>"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match
</code>```

user input: "$5000" or "5000"

```<code>"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match
</code>```

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

答:
Version 1

Except the example with comma, the following Regex meets your requirement:

(?:\$?)\$5000(?:$|\s.*)

Remember to escape the $ in $5000

Explanation

(?:\$?): Match a single $ sign if present, the ? indicates occurrence of $ to be 1 or 0.

\$5000: It is the input with $ escaped.

(?:$|\s.*): Matches either the end of a string or anything after a space.

Version 2

Again, comma is not accommodated.

(?:\$?)\$50(?:$|(?:\s(?:\+|\-)\s(?:\$?)(?:[0-9]+))+)

Explanation

(?:\$?): Match a single $ sign if present, the ? indicates occurrence of $ to be 1 or 0.

\$5000: It is the input with $ escaped.

(?:$|(?:\s(?:\+|\-)\s(?:\$?)(?:[0-9]+))+): Matches either end of string or + $xxx or - $xxx after the match, even if they are repeated.

Body:
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match

user input: "$5000" or "5000"

"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?


问:
How put margin between diffrent div on a container?
I have different lines each one contains logo and some text.I want to put each logo in a different line and put a margin-top of 20px between them.

index.html:

```<code><container class="list_project">
      <div class="project">
          <img class ="first_logo" src="./logos/logo.png" value="" />
          <img class ="project_logo" src="./logos/logo.png" value="" />
      </div>
    </container>
</code>```

style.css:

```<code>  .first_logo
  {
   position: absolute;
   top: 150px;
   width: 85px;
   height: 45px;
  }
  .project_logo
  {
    position: absolute;
    margin-bottom: 20px;
    width: 85px;
    height: 45px;

   }
</code>```

But I find that the position of the image is relative to main page not to the container. How can I fix that and I make the position of each image relative to the container?

Logo

答:
If both of them are fixed size, this does the work.

HTML:

```<code><container class="list_project">
  <div class="project">
    <img class ="first_logo" src="https://i.stack.imgur.com/OTRXb.png" value="" />
    <img class ="project_logo" src="https://i.stack.imgur.com/OTRXb.png" value="" />
  </div>
</container>
</code>```

CSS:

```<code>.first-logo,
.project-logo {
  display: block;
  width: 85px;
  height: 45px
}

.first-logo {
    margin-bottom: 20px;
}
</code>```

Body:
I have different lines each one contains logo and some text.I want to put each logo in a different line and put a margin-top of 20px between them.

index.html:

<container class="list_project">

    </container>

style.css:

  .first_logo
  {
   position: absolute;
   top: 150px;
   width: 85px;
   height: 45px;
  }
  .project_logo
  {
    position: absolute;
    margin-bottom: 20px;
    width: 85px;
    height: 45px;

   }

But I find that the position of the image is relative to main page not to the container. How can I fix that and I make the position of each image relative to the container?

Logo

Body:
If both of them are fixed size, this does the work.

HTML:

<container class="list_project">
  <div class="project">
    <img class ="first_logo" src="https://i.stack.imgur.com/OTRXb.png" value="" />
    <img class ="project_logo" src="https://i.stack.imgur.com/OTRXb.png" value="" />
  </div>
</container>

CSS:

.first-logo,
.project-logo {
  display: block;
  width: 85px;
  height: 45px
}

.first-logo {
    margin-bottom: 20px;
}


问:
Setting UITextView font size based for different devices
Sorry for my poor english.

I have UITextview, which is configured with Auto layout. So it's height will change depends on devices. So it should take the font size, in such way that it show only one line available space. like SMS box or Chat box.

See the pictures for iPhone4 it shows only one line and for iPhone 6s and 5s it shows two lines. But for me it should increase font size and show only one line for any size.

答:
Using this:

```<code>static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
</code>```

you can check the condition:

```<code>if(SCREEN_WIDTH == 320) {
   textView.font = UIFont.systemFont(ofSize: 12.0)
} else if(SCREEN_WIDTH == 375) {
   textView.font = UIFont.systemFont(ofSize: 13.0)
} else if(SCREEN_WIDTH == 414) {
   textView.font = UIFont.systemFont(ofSize: 14.0)
}
</code>```

By this the font size will be adjust according to device.

Body:
Using this:

static let SCREEN_WIDTH = UIScreen.main.bounds.size.width

you can check the condition:

if(SCREEN_WIDTH == 320) {
   textView.font = UIFont.systemFont(ofSize: 12.0)
} else if(SCREEN_WIDTH == 375) {
   textView.font = UIFont.systemFont(ofSize: 13.0)
} else if(SCREEN_WIDTH == 414) {
   textView.font = UIFont.systemFont(ofSize: 14.0)
}

By this the font size will be adjust according to device.


问:
"This method requires a GET or HEAD" error using twitteR, rjson, httr
I am following code provided on a Stack Overflow thread from several years ago, but I am getting an error when I run the 'fromJSON' command, "Code 86, This method requires a GET or HEAD". I am trying to get a list of usernames from a public Twitter list (all NHL players).

Here is the code

```<code># load packages
library("twitteR")
library("rjson")
library("httr")

consumer_key <- "XXX"
consumer_secret <- "XXX"
access_token <- "XXX"
access_secret <- "XXX"
options(httr_oauth_cache=T)
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)

twlist <- "nhl-players"
twowner <- "NHL"
api.url <- paste0("https://api.twitter.com/1.1/lists/members.json?slug=",
              twlist, "&owner_screen_name=", twowner, "&count=500")
response <- POST(api.url, config(token=twitteR:::get_oauth_sig()))
fromJSON(content(response, as = "text", encoding = "UTF-8"))
</code>```

答:
I think I've got it. There is a little typo in your api.url object. It's not "&NHL="(which is the actual value), it's "&owner_screen_name=" (which is the name of the paramater that you want to pass). Plus you need to use a GET request.

```<code> api.url <- paste0("https://api.twitter.com/1.1/lists/members.json?slug=", twlist, "&owner_screen_name=", twowner, "&count=500")
 response <- GET(api.url, config(token=twitteR:::get_oauth_sig()))
</code>```

Body:
I am following code provided on a Stack Overflow thread from several years ago, but I am getting an error when I run the 'fromJSON' command, "Code 86, This method requires a GET or HEAD". I am trying to get a list of usernames from a public Twitter list (all NHL players).

Here is the code

# load packages
library("twitteR")
library("rjson")
library("httr")

consumer_key <- "XXX"
consumer_secret <- "XXX"
access_token <- "XXX"
access_secret <- "XXX"
options(httr_oauth_cache=T)
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)

twlist <- "nhl-players"
twowner <- "NHL"
api.url <- paste0("https://api.twitter.com/1.1/lists/members.json?slug=",
              twlist, "&owner_screen_name=", twowner, "&count=500")
response <- POST(api.url, config(token=twitteR:::get_oauth_sig()))
fromJSON(content(response, as = "text", encoding = "UTF-8"))

Body:
I think I've got it. There is a little typo in your api.url object. It's not "&NHL="(which is the actual value), it's "&owner_screen_name=" (which is the name of the paramater that you want to pass). Plus you need to use a GET request.

 api.url <- paste0("https://api.twitter.com/1.1/lists/members.json?slug=", twlist, "&owner_screen_name=", twowner, "&count=500")
 response <- GET(api.url, config(token=twitteR:::get_oauth_sig()))


问:
Modify the exception
I have 2 WCF services and a client which calls the method of 1st WCF service, and that method consequently calls the method of 2nd WCF service. The method of 2nd WCF service rises a generic fault exception, I need that this exception will be normally 'delivered' to my client through the 1st service. The 1st WCF service normally gets that generic exception with some Action "http://SomeNamespace" in exception message body. When the 1st service rethrow this exception to client, the client gets simple FaultException instead of FaultException1. I think the problem is inAction` which contains a namespace which is not acceptable for the client, and that's why the client is not able to get generic exception. There is a WCF Exception Shielding in 1st WCF service. Below are the configuration code and the handler code.
Please help me and advise the best way to change the action of exception that the client will be able to get it normally.

Here is the config:

```<code><exceptionHandling>
      <exceptionPolicies>
        <add name="WCF Exception Shielding">
          <exceptionTypes>
            <add type="System.ServiceModel.FaultException`1[[Sample.SomeFaultContract, Sample, PublicKeyToken=769e6b46280078d4]], System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                postHandlingAction="ThrowNewException" name="SomeFaultContract">
                <exceptionHandlers>
                  <add faultContractType="Sample.SomeFaultContract, Sample, PublicKeyToken=769e6b46280078d4"
                    type="Helper.ServiceFaultContractHandler, Logger, PublicKeyToken=769e6b46280078d4"
                    name="Fault Contract Exception Handler" />
                </exceptionHandlers>
            </add>
          </exceptionTypes>
        </add>
  </exceptionHandling>
</code>```

And the handler part is:

```<code>public class ServiceFaultContractHandler : IExceptionHandler
{
   public ServiceFaultContractHandler(NameValueCollection ignore) { }

   public Exception HandleException(Exception exception, Guid correlationID)
   {

   }
}
</code>```

Thank you in advance.

Aram

答:
In order to get the details of the exception, you should set the includeExceptionDetailInFaults property to true in the service behavior.

Below is a sample:

```<code><behaviors>
    <serviceBehaviors>
      <behavior name="WCFServicesName">
        <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>
   </serviceBehaviors>
</behaviors>
</code>```

Title: Modify the exception

Body:
I have 2 WCF services and a client which calls the method of 1st WCF service, and that method consequently calls the method of 2nd WCF service. The method of 2nd WCF service rises a generic fault exception, I need that this exception will be normally 'delivered' to my client through the 1st service. The 1st WCF service normally gets that generic exception with some Action "http://SomeNamespace" in exception message body. When the 1st service rethrow this exception to client, the client gets simple FaultException instead of FaultException1. I think the problem is inAction` which contains a namespace which is not acceptable for the client, and that's why the client is not able to get generic exception. There is a WCF Exception Shielding in 1st WCF service. Below are the configuration code and the handler code.
Please help me and advise the best way to change the action of exception that the client will be able to get it normally.

Here is the config:

<exceptionHandling>
      <exceptionPolicies>
        <add name="WCF Exception Shielding">
          <exceptionTypes>
            <add type="System.ServiceModel.FaultException`1[[Sample.SomeFaultContract, Sample, PublicKeyToken=769e6b46280078d4]], System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                postHandlingAction="ThrowNewException" name="SomeFaultContract">
                <exceptionHandlers>
                  <add faultContractType="Sample.SomeFaultContract, Sample, PublicKeyToken=769e6b46280078d4"
                    type="Helper.ServiceFaultContractHandler, Logger, PublicKeyToken=769e6b46280078d4"
                    name="Fault Contract Exception Handler" />
                </exceptionHandlers>
            </add>
          </exceptionTypes>
        </add>
  </exceptionHandling>

And the handler part is:

public class ServiceFaultContractHandler : IExceptionHandler
{
   public ServiceFaultContractHandler(NameValueCollection ignore) { }

   public Exception HandleException(Exception exception, Guid correlationID)
   {

   }
}

Thank you in advance.

Aram

Body:
In order to get the details of the exception, you should set the includeExceptionDetailInFaults property to true in the service behavior.

Below is a sample:

<behaviors>
    <serviceBehaviors>
      <behavior name="WCFServicesName">
        <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>
   </serviceBehaviors>
</behaviors>


问:
Select rows with more than one occurrence but not group them
I have an IP table with users IP addresses stored. I basically want to see if potentially a user has created more than one profile.

How can I select rows from the table where the IP address shows more than once, but also not group them so I can see the user ids for each IP?

I have this so far but I can't figure out a way to find duplicate IPs without grouping:

```<code>SELECT ow_base_user.username, ow_userip_address.userid,     ow_userip_address.ip, COUNT(*) AS cnt
FROM ow_userip_address
INNER JOIN ow_base_user ON ow_userip_address.userid = ow_base_user.id
GROUP BY ip
HAVING cnt > 1
</code>```

答:
Try this one:</p>

```<code>SELECT ow_base_user.username, ow_userip_address.userid, ow_userip_address.ip, COUNT(*) AS cnt
FROM ow_userip_address
INNER JOIN ow_base_user ON ow_userip_address.userid = ow_base_user.id
GROUP BY ip, userip_address.userid
HAVING cnt > 1
</code>```

Body:
I have an IP table with users IP addresses stored. I basically want to see if potentially a user has created more than one profile.

How can I select rows from the table where the IP address shows more than once, but also not group them so I can see the user ids for each IP?

I have this so far but I can't figure out a way to find duplicate IPs without grouping:

SELECT ow_base_user.username, ow_userip_address.userid,     ow_userip_address.ip, COUNT(*) AS cnt
FROM ow_userip_address
INNER JOIN ow_base_user ON ow_userip_address.userid = ow_base_user.id
GROUP BY ip
HAVING cnt > 1

Body:
Try this one:

SELECT ow_base_user.username, ow_userip_address.userid, ow_userip_address.ip, COUNT(*) AS cnt
FROM ow_userip_address
INNER JOIN ow_base_user ON ow_userip_address.userid = ow_base_user.id
GROUP BY ip, userip_address.userid
HAVING cnt > 1


问:
Date Intervals in For each Loop
What i want is i have 5 records in table,
dates -> 2017-03-12, 2017-03-23, 2017-03-25, 2017-03-28, 2017-03-29 and they have according price-> 10,20,30,40,50.

I want to generate a report where they show dates between 12 to 29. 12, 13, 14, 15 and so on to 29. with their price, if there is no price available for this date, it should take the previous price record. For an ex, for date 13, 14, 15 it should take the price 10, while for date 24 it should take price 20.

Any Ideas About it?

Title: Date Intervals in For each Loop

Body:
Here you go.

$dates['2017-03-12'] = 10;
$dates['2017-03-23'] = 20;
$dates['2017-03-25'] = 30;
$dates['2017-03-28'] = 40;
$dates['2017-03-29'] = 50;

$start = min(array_keys($dates));

$end = max(array_keys($dates));

$list = array();
while($start <= $end){

    $value = $dates[$start];

    if(!is_null($value))
        $last_value = $value;

    $list[] = array("date" => $start,"value" => $last_value);

    $start = date('Y-m-d',strtotime($start."+1day"));

}

print_r($list);

This will print

Array
(
    [0] => Array
        (
            [date] => 2017-03-12
            [value] => 10
        )

    [1] => Array
        (
            [date] => 2017-03-13
            [value] => 10
        )

    [2] => Array
        (
            [date] => 2017-03-14
            [value] => 10
        )

    [3] => Array
        (
            [date] => 2017-03-15
            [value] => 10
        )

    [4] => Array
        (
            [date] => 2017-03-16
            [value] => 10
        )

    [5] => Array
        (
            [date] => 2017-03-17
            [value] => 10
        )

    [6] => Array
        (
            [date] => 2017-03-18
            [value] => 10
        )

    [7] => Array
        (
            [date] => 2017-03-19
            [value] => 10
        )

    [8] => Array
        (
            [date] => 2017-03-20
            [value] => 10
        )

    [9] => Array
        (
            [date] => 2017-03-21
            [value] => 10
        )

    [10] => Array
        (
            [date] => 2017-03-22
            [value] => 10
        )

    [11] => Array
        (
            [date] => 2017-03-23
            [value] => 20
        )

    [12] => Array
        (
            [date] => 2017-03-24
            [value] => 20
        )

    [13] => Array
        (
            [date] => 2017-03-25
            [value] => 30
        )

    [14] => Array
        (
            [date] => 2017-03-26
            [value] => 30
        )

    [15] => Array
        (
            [date] => 2017-03-27
            [value] => 30
        )

    [16] => Array
        (
            [date] => 2017-03-28
            [value] => 40
        )

    [17] => Array
        (
            [date] => 2017-03-29
            [value] => 50
        )

)


问:
I can not change src of imageview from inside non-activity class in Android
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

```<code> LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);
</code>```

Updated: Complete class

```<code>public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}
</code>```

答:
You can make the ImageView static in your Fragment

```<code>public class YourFragment extends Fragment{
public static ImageView okaddress;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.control_address_fragment, container, false);

okaddress = (ImageView)view.findViewById(R.id.address_ok);
}

return view;
}
</code>```

And when the result is 0 as you said you can change it like this in AddressControl

```<code>YourFragment.okaddress.setImageResource(R.drawable.clear);
</code>```

Body:
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);

Updated: Complete class

public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}

Body:
You can make the ImageView static in your Fragment

public class YourFragment extends Fragment{
public static ImageView okaddress;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.control_address_fragment, container, false);

okaddress = (ImageView)view.findViewById(R.id.address_ok);
}

return view;
}

And when the result is 0 as you said you can change it like this in AddressControl

YourFragment.okaddress.setImageResource(R.drawable.clear);


问:
Producing a Dialog that will be dismissed automatically
is it possible to create a Dialog that will be dismissed automatically after some time if it doesn't have any user interaction?

答:
You could use a Handler to automatically dismiss it.

In the class members:

```<code>private final int CANCEL_DIALOG = 1;
private Handler mHandler;
private Dialog mDialog;
</code>```

In onCreate():

```<code>mHandler = new Handler(new Handler.Callback()
{
    @Override
    public boolean handleMessage(Message msg)
    {
        if(msg.what == CANCEL_DIALOG)
        {
            mDialog.cancel();
        }

        return false;
    }
});
</code>```

On the button you use to open the dialog (or whatever system you use):

```<code>mDialog.show();
mHandler.sendEmptyMessageDelayed(CANCEL_DIALOG, 5000);
</code>```

Essentially after 5 seconds, the dialog will close after it has opened using this code.

Body:
You could use a Handler to automatically dismiss it.

In the class members:

private final int CANCEL_DIALOG = 1;
private Handler mHandler;
private Dialog mDialog;

In onCreate():

mHandler = new Handler(new Handler.Callback()
{
    @Override
    public boolean handleMessage(Message msg)
    {
        if(msg.what == CANCEL_DIALOG)
        {
            mDialog.cancel();
        }

        return false;
    }
});

On the button you use to open the dialog (or whatever system you use):

mDialog.show();
mHandler.sendEmptyMessageDelayed(CANCEL_DIALOG, 5000);

Essentially after 5 seconds, the dialog will close after it has opened using this code.


问:
Android Retrofit appends unwanted characters
I am trying to do a GET request to a json file:

https://www.someurl.com/appconfiguration.json

So I created an Interface with the following GET method

```<code>  @GET("appconfiguration.json}")
  Call<AppConfigParent> loadAppConfigParent();
</code>```

and call it like this:

```<code>   final MMSATServices.AppConfigResponse appConfigResponse = new MMSATServices.AppConfigResponse();
    appConfigResponse.appConfigParent = new AppConfigParent();
    appConfigResponse.appConfigParent.configuration = null;

    Call<AppConfigParent> call = api.loadAppConfigParent();
    call.enqueue(new Callback<AppConfigParent>() {
        @Override
        public void onResponse(Call<AppConfigParent> call, Response<AppConfigParent> response) {
            appConfigResponse.appConfigParent.configuration = response.body().configuration;
            bus.post(appConfigResponse);
        }

        @Override
        public void onFailure(Call<AppConfigParent> call, Throwable t) {

        }
    });
</code>```

note that the api object is the instance of the interface, whichis defined in the super class.

The actual problem is that I get a 404 repsonse:

Request{method=GET, url=https://someurl.com/appconfiguration.json%7D, tag=Request{method=GET, url=https://someurl.com/appconfiguration.json%7D, tag=null}}

As you can see %7D is appended to the URL, which leads to the 404 error. How can I get rid of this behavior?

答: Remove } in @GET("appconfiguration.json}")

Body:
I am trying to do a GET request to a json file:

https://www.someurl.com/appconfiguration.json

So I created an Interface with the following GET method

  @GET("appconfiguration.json}")
  Call<AppConfigParent> loadAppConfigParent();

and call it like this:

   final MMSATServices.AppConfigResponse appConfigResponse = new MMSATServices.AppConfigResponse();
    appConfigResponse.appConfigParent = new AppConfigParent();
    appConfigResponse.appConfigParent.configuration = null;

    Call<AppConfigParent> call = api.loadAppConfigParent();
    call.enqueue(new Callback<AppConfigParent>() {
        @Override
        public void onResponse(Call<AppConfigParent> call, Response<AppConfigParent> response) {
            appConfigResponse.appConfigParent.configuration = response.body().configuration;
            bus.post(appConfigResponse);
        }

        @Override
        public void onFailure(Call<AppConfigParent> call, Throwable t) {

        }
    });

note that the api object is the instance of the interface, whichis defined in the super class.

The actual problem is that I get a 404 repsonse:

Request{method=GET, url=https://someurl.com/appconfiguration.json%7D, tag=Request{method=GET, url=https://someurl.com/appconfiguration.json%7D, tag=null}}

As you can see %7D is appended to the URL, which leads to the 404 error. How can I get rid of this behavior?


问:
Spring Security 3.2 - configuring global method security to use role hierarchy
Using Spring Security 3.2.5 and Spring 4.1.2, 100% Java config

Our webapp has global method security enabled and service methods annotated with @PreAuthorize - everything is working as expected.  I'm trying to add a role hierarchy and having no success at all.  Here's the hierarchy I'm trying to achieve:

ROLE_ADMIN can access all methods that ROLE_USER can access.

ROLE_USER can access all methods that ROLE_DEFAULT can access.

Despite my best efforts, a user with ROLE_ADMIN receives a 403 when doing something that results in a call to a method annotated with @PreAuthorized("hasAuthority('ROLE_DEFAULT')")

Here's the relevant configuration code:

AppInitializer

```<code>public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
  @Override
  protected Class<?>[] getRootConfigClasses()
  {
    return new Class[]
    {
      AppConfig.class, SecurityConfig.class
    };
  }

  @Override
  protected Class<?>[] getServletConfigClasses()
  {
    return new Class[]
    {
      MvcConfig.class
    };
  }
  // other methods not shown for brevity
}
</code>```

AppConfig.java

```<code>@Configuration
@ComponentScan(basePackages={"myapp.config.profile", "myapp.dao", "myapp.service", "myapp.security"})
public class AppConfig
{
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth,
                              AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> detailSvc) throws Exception
  {
    PreAuthenticatedAuthenticationProvider authProvider = new PreAuthenticatedAuthenticationProvider();
    authProvider.setPreAuthenticatedUserDetailsService(detailSvc);
    auth.authenticationProvider(authProvider);
  }
  // other methods not shown for brevity
}
</code>```

SecurityConfig.java

```<code>@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
  @Override
  protected void configure(HttpSecurity http) throws Exception
  {
    PKIAuthenticationFilter pkiFilter = new PKIAuthenticationFilter();
    pkiFilter.setAuthenticationManager(authenticationManagerBean());

    http.authorizeRequests()
        .antMatchers("/app/**").fullyAuthenticated()
        .and()
        .anonymous().disable()
        .jee().disable()
        .formLogin().disable()
        .csrf().disable()
        .x509().disable()
        .addFilter(pkiFilter)
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }

  @Override
  public void configure(WebSecurity web) throws Exception
  {
    // ignore everything but /app/*
    web.ignoring().regexMatchers("^(?!/app/).*");
  }
}
</code>```

MvcConfig.java

```<code>@Configuration
@EnableWebMvc
@ComponentScan({"myapp.controller"})
public class MvcConfig extends WebMvcConfigurerAdapter
{
  // resource handlers, content negotiation, message converters configured here
}
</code>```

In the same package as SecurityConfig (so it is thus part of the AppConfig component scan) I had this class:

GlobalMethodSecurityConfig.java

```<code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration
{
  @Bean
  public RoleHierarchy roleHierarchy()
  {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER > ROLE_DEFAULT");
    return roleHierarchy;
  }

  @Bean
  public RoleVoter roleVoter()
  {
    return new RoleHierarchyVoter(roleHierarchy);
  }

  @Bean
  @Override
  protected AccessDecisionManager accessDecisionManager()
  {
    return new AffirmativeBased(Arrays.asList(roleVoter()));
  }

  // The method below was added in an attempt to get things working but it is never called
  @Override
  protected MethodSecurityExpressionHandler createExpressionHandler()
  {
    DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
    handler.setRoleHierarchy(roleHierarchy());
    return handler;
  }
}
</code>```

In another attempt I made AppConfig extend GlobalMethodSecurityConfiguration but a user with ROLE_ADMIN cannot call a method requiring ROLE_DEFAULT access.

I'm sure I've misconfigured something somewhere but I can't figure out where I've gone wrong despite reading everything I can find on configuring global method security with a role hierarchy.  It appears this would be trivial using XML configuration but the Java config solution eludes me.

答:
Since this question keeps getting views I thought I'd post a follow-up to it. The problem appears to be with the line

roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER > ROLE_DEFAULT");

I don't remember why I wrote the hierarchy like that but it's not correct. The API for that method handles the same situation thusly:

Role hierarchy: ROLE_A > ROLE_B and ROLE_B > ROLE_C.

  Directly assigned authority: ROLE_A.

  Reachable authorities: ROLE_A, ROLE_B, ROLE_C.

Eventually it became clear that a hierarchical model didn't fit our roles so we instead implemented a finer-grained set of authorities mapped to roles, as mentioned in the Spring Security Reference:

For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information.

Body:
Using Spring Security 3.2.5 and Spring 4.1.2, 100% Java config

Our webapp has global method security enabled and service methods annotated with @PreAuthorize - everything is working as expected.  I'm trying to add a role hierarchy and having no success at all.  Here's the hierarchy I'm trying to achieve:

ROLE_ADMIN can access all methods that ROLE_USER can access.

ROLE_USER can access all methods that ROLE_DEFAULT can access.

Despite my best efforts, a user with ROLE_ADMIN receives a 403 when doing something that results in a call to a method annotated with @PreAuthorized("hasAuthority('ROLE_DEFAULT')")

Here's the relevant configuration code:

AppInitializer

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
  @Override
  protected Class<?>[] getRootConfigClasses()
  {
    return new Class[]
    {
      AppConfig.class, SecurityConfig.class
    };
  }

  @Override
  protected Class<?>[] getServletConfigClasses()
  {
    return new Class[]
    {
      MvcConfig.class
    };
  }
  // other methods not shown for brevity
}

AppConfig.java

@Configuration
@ComponentScan(basePackages={"myapp.config.profile", "myapp.dao", "myapp.service", "myapp.security"})
public class AppConfig
{
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth,
                              AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> detailSvc) throws Exception
  {
    PreAuthenticatedAuthenticationProvider authProvider = new PreAuthenticatedAuthenticationProvider();
    authProvider.setPreAuthenticatedUserDetailsService(detailSvc);
    auth.authenticationProvider(authProvider);
  }
  // other methods not shown for brevity
}

SecurityConfig.java

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
  @Override
  protected void configure(HttpSecurity http) throws Exception
  {
    PKIAuthenticationFilter pkiFilter = new PKIAuthenticationFilter();
    pkiFilter.setAuthenticationManager(authenticationManagerBean());

    http.authorizeRequests()
        .antMatchers("/app/**").fullyAuthenticated()
        .and()
        .anonymous().disable()
        .jee().disable()
        .formLogin().disable()
        .csrf().disable()
        .x509().disable()
        .addFilter(pkiFilter)
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }

  @Override
  public void configure(WebSecurity web) throws Exception
  {
    // ignore everything but /app/*
    web.ignoring().regexMatchers("^(?!/app/).*");
  }
}

MvcConfig.java

@Configuration
@EnableWebMvc
@ComponentScan({"myapp.controller"})
public class MvcConfig extends WebMvcConfigurerAdapter
{
  // resource handlers, content negotiation, message converters configured here
}

In the same package as SecurityConfig (so it is thus part of the AppConfig component scan) I had this class:

GlobalMethodSecurityConfig.java

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration
{
  @Bean
  public RoleHierarchy roleHierarchy()
  {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER > ROLE_DEFAULT");
    return roleHierarchy;
  }

  @Bean
  public RoleVoter roleVoter()
  {
    return new RoleHierarchyVoter(roleHierarchy);
  }

  @Bean
  @Override
  protected AccessDecisionManager accessDecisionManager()
  {
    return new AffirmativeBased(Arrays.asList(roleVoter()));
  }

  // The method below was added in an attempt to get things working but it is never called
  @Override
  protected MethodSecurityExpressionHandler createExpressionHandler()
  {
    DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
    handler.setRoleHierarchy(roleHierarchy());
    return handler;
  }
}

In another attempt I made AppConfig extend GlobalMethodSecurityConfiguration but a user with ROLE_ADMIN cannot call a method requiring ROLE_DEFAULT access.

I'm sure I've misconfigured something somewhere but I can't figure out where I've gone wrong despite reading everything I can find on configuring global method security with a role hierarchy.  It appears this would be trivial using XML configuration but the Java config solution eludes me.


问:
Calculate the time stamp of year
Given that I have $num_years, how can I add it to Time()  to get a time stamp $num_years hence?

答: strtotime("+$num_years years") will give you a timestamp $num_years years in the future.

Title: Calculate the time stamp of year


问:
how to delete image from folder using dropzone?
I am using laravel framework 5.2. I have successfully implemented dropzone and i have also done with upload images. Now problem is that when i want to delete the image from folder it gives me error. I think my code is not right for deleting image.

Here is my add Upload image Function i have uploaded images in session:-

```<code>public function addContributorimages(Request $request){
    if($request->ajax()){
        $image=$_FILES['file'];
        if(!empty($image)){
            if($image['error']==0){
                $name = pathinfo($_FILES['file']['name']);
                $ext = $name['extension'];
                $rand=str_random(24).'.'.$ext;
                $destination = base_path() . '/public/images/ContributorImages/';
                if(is_uploaded_file($image['tmp_name'])){
                list( $width, $height, $source_type ) = getimagesize($image['tmp_name']);
                if ($width >= 10 && $height >= 10){
                    move_uploaded_file($image['tmp_name'],$destination.$rand);
                    $request->session()->put('contributorimage.'.str_random(5).'.image',$rand);
                    $images = $request->session()->get('contributorimage');
                    echo "```"; print_r($images);
                }
                else{
                        echo "Error";die;
                    }
                }
            }
        }
    }
}
```

<p>This is my add Function of images
Here is my dropzone code :-</p>

```Dropzone.autoDiscover = false;
    var fileList = new Array;
    var i =0;
    $("#my-awesome-dropzone").dropzone({
        method:'POST',
        maxFiles: 10,
        paramName: "file",
        maxFilesize: 10,
        addRemoveLinks: true,
        acceptedFiles: ".jpeg,.jpg,.png,.gif",
        clickable: true,

        init: function() {

            // Hack: Add the dropzone class to the element
            $(this.element).addClass("dropzone");
            this.on("sending",function(file, xhr, formData) {
                formData.append("_token", "{{ csrf_token() }}");
            });
            this.on("success", function(file, serverFileName) {
                fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
                //console.log(fileList);
                i++;

            });
            this.on("removedfile", function(file) {
                var rmvFile = "";
                for(f=0;f<fileList.length;f++){

                    if(fileList[f].fileName == file.name)
                    {
                        rmvFile = fileList[f].serverFileName;

                        if (rmvFile){
                            $.ajax({
                                type: 'POST',
                                url: '../contributor/delete-subimages/'+rmvFile,
                            });
                        }
                    }
                }

            });

        },
        url: '../contributor/add-subimages',
    });

});
```

<p>My images are successfully uploaded but i want to remove the image from session as well as from folder can anyone help me how to do that
Here is my delete function of image:-</p>

```public function deleteContributorImage(Request $request,$name = null){
    $imageName=explode('.',$name);
    $imageRandomName = $request->session()->get('contributorimage.'.$imageName[0].'.image');
    $destination = base_path() . '/public/images/ContributorImages/';
    if(unlink($destination.$imageRandomName)){
        $request->session()->forget('contributorimage.'.$imageName[0]);
        echo "success";
    }
    else{
        echo "failed";
    }
}
```

<p>Now when i upload images it create this sesssion now i am having two images in session</p>

```Array
(
[Dkf08] => Array
    (
        [image] => whywu3dprVPKKkhUgdIMAdLQ.jpg
    )

[rH5NV] => Array
    (
        [image] => i2sZEqjMdiQHcKRyy5Km9vlu.jpg
    )

)
```

can anyone hlep me how to slove this issue . Thanks in advance :)

答:
you have to create one hidden filed for that and when you remove file from dropzone than that file name should be save in that hidden filed.

```<code>myDropzone.on('removedfile', function (file) {

        var hidden_filed= document.getElementById('hidden_filed').value;
        if (alreadyRemove == "") {
            $('#deleteImage').val(file.name);
        } else {
            $('#deleteImage').val(hidden_filed+ ',' + file.name);
        }
    });
</code>```

after that get that field as POST data in controller. From file name you can delete Image as usual.

Body:
I am using laravel framework 5.2. I have successfully implemented dropzone and i have also done with upload images. Now problem is that when i want to delete the image from folder it gives me error. I think my code is not right for deleting image.

Here is my add Upload image Function i have uploaded images in session:-

public function addContributorimages(Request $request){
    if($request->ajax()){
        $image=$_FILES['file'];
        if(!empty($image)){
            if($image['error']==0){
                $name = pathinfo($_FILES['file']['name']);
                $ext = $name['extension'];
                $rand=str_random(24).'.'.$ext;
                $destination = base_path() . '/public/images/ContributorImages/';
                if(is_uploaded_file($image['tmp_name'])){
                list( $width, $height, $source_type ) = getimagesize($image['tmp_name']);
                if ($width >= 10 && $height >= 10){
                    move_uploaded_file($image['tmp_name'],$destination.$rand);
                    $request->session()->put('contributorimage.'.str_random(5).'.image',$rand);
                    $images = $request->session()->get('contributorimage');
                    echo "
"; print_r($images);
                }
                else{
                        echo "Error";die;
                    }
                }
            }
        }
    }
}

This is my add Function of images
Here is my dropzone code :-

Dropzone.autoDiscover = false;
    var fileList = new Array;
    var i =0;
    $("#my-awesome-dropzone").dropzone({
        method:'POST',
        maxFiles: 10,
        paramName: "file",
        maxFilesize: 10,
        addRemoveLinks: true,
        acceptedFiles: ".jpeg,.jpg,.png,.gif",
        clickable: true,

        init: function() {

            // Hack: Add the dropzone class to the element
            $(this.element).addClass("dropzone");
            this.on("sending",function(file, xhr, formData) {
                formData.append("_token", "{{ csrf_token() }}");
            });
            this.on("success", function(file, serverFileName) {
                fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
                //console.log(fileList);
                i++;

            });
            this.on("removedfile", function(file) {
                var rmvFile = "";
                for(f=0;f<fileList.length;f++){

                    if(fileList[f].fileName == file.name)
                    {
                        rmvFile = fileList[f].serverFileName;

                        if (rmvFile){
                            $.ajax({
                                type: 'POST',
                                url: '../contributor/delete-subimages/'+rmvFile,
                            });
                        }
                    }
                }

            });

        },
        url: '../contributor/add-subimages',
    });

});

My images are successfully uploaded but i want to remove the image from session as well as from folder can anyone help me how to do that
Here is my delete function of image:-

public function deleteContributorImage(Request $request,$name = null){
    $imageName=explode('.',$name);
    $imageRandomName = $request->session()->get('contributorimage.'.$imageName[0].'.image');
    $destination = base_path() . '/public/images/ContributorImages/';
    if(unlink($destination.$imageRandomName)){
        $request->session()->forget('contributorimage.'.$imageName[0]);
        echo "success";
    }
    else{
        echo "failed";
    }
}

Now when i upload images it create this sesssion now i am having two images in session

Array
(
[Dkf08] => Array
    (
        [image] => whywu3dprVPKKkhUgdIMAdLQ.jpg
    )

[rH5NV] => Array
    (
        [image] => i2sZEqjMdiQHcKRyy5Km9vlu.jpg
    )

)

can anyone hlep me how to slove this issue . Thanks in advance :)

Body:
you have to create one hidden filed for that and when you remove file from dropzone than that file name should be save in that hidden filed.

myDropzone.on('removedfile', function (file) {

        var hidden_filed= document.getElementById('hidden_filed').value;
        if (alreadyRemove == "") {
            $('#deleteImage').val(file.name);
        } else {
            $('#deleteImage').val(hidden_filed+ ',' + file.name);
        }
    });

after that get that field as POST data in controller. From file name you can delete Image as usual.


问:
How to sort a HashMap by it amount of value in Java
I have declared a HashMap like this:

```<code>Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();
</code>```

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

答:
What about something like this:

```<code>Map<Integer, List<Integer>> numbers = new HashMap<Integer, List<Integer>>();
numbers.put(64, Arrays.asList(61, 68, 77));
numbers.put(65, Arrays.asList(63, 66, 66, 70));
numbers.put(66, Arrays.asList(69, 75, 2));
numbers.put(67, Arrays.asList(65, 77));
numbers.put(2, Arrays.asList(4));
numbers.put(4, Arrays.asList(2));

List<Integer> topValues = numbers.entrySet().stream()
       .collect(
               Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> entry.getValue().size()
                ) // get a map where key=original key and value list size
       )  // {64=3, 65=4, 2=1, 66=3, 67=2, 4=1}
       .entrySet()
       .stream() // sort map by value - list size
       .sorted( Map.Entry.<Integer,Integer>comparingByValue().reversed())
       .limit(3) // get top 3
       .map(Map.Entry::getKey)
       .collect(Collectors.toList());

System.out.println(topValues); // [65, 64, 66]
</code>```

As a first step we transform out map Map<Integer, List<Integer>> numbers to a new temporary map Map<Integer,Integer> where a key is key from original map, and a value is a list size.  So the original map
{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]} will became {64=3, 65=4, 2=1, 66=3, 67=2, 4=1} Then we will sort temporary map in descending order, and will get top 3 elements. As final step we will get keys of the top 3, and add them to topValues list.

I hope this helps.

Body:
I have declared a HashMap like this:

Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

Body:
What about something like this:

Map<Integer, List<Integer>> numbers = new HashMap<Integer, List<Integer>>();
numbers.put(64, Arrays.asList(61, 68, 77));
numbers.put(65, Arrays.asList(63, 66, 66, 70));
numbers.put(66, Arrays.asList(69, 75, 2));
numbers.put(67, Arrays.asList(65, 77));
numbers.put(2, Arrays.asList(4));
numbers.put(4, Arrays.asList(2));

List<Integer> topValues = numbers.entrySet().stream()
       .collect(
               Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> entry.getValue().size()
                ) // get a map where key=original key and value list size
       )  // {64=3, 65=4, 2=1, 66=3, 67=2, 4=1}
       .entrySet()
       .stream() // sort map by value - list size
       .sorted( Map.Entry.<Integer,Integer>comparingByValue().reversed())
       .limit(3) // get top 3
       .map(Map.Entry::getKey)
       .collect(Collectors.toList());

System.out.println(topValues); // [65, 64, 66]

As a first step we transform out map Map<Integer, List<Integer>> numbers to a new temporary map Map<Integer,Integer> where a key is key from original map, and a value is a list size.  So the original map
{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]} will became {64=3, 65=4, 2=1, 66=3, 67=2, 4=1} Then we will sort temporary map in descending order, and will get top 3 elements. As final step we will get keys of the top 3, and add them to topValues list.

I hope this helps.


问:
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?

答:
How to Start SQL Server without TempDB database?

Step 1:  Start the SQL Server in minimal configuration mode.

Click here
to see, "How to start the SQL Server in minimal mode using command prompt".

Step 2: Once SQL Server has started with  minimum configuration mode;
  connect to SQL Server instance and move TempDB data and log file to a new location.

See, move TempDB data and log files to new location

Step 3: Once you have performed the troubleshooting steps; exit SQLCMD window by typing Quit and Press Enter.

Step 4: . In the initial window click CTRL C and enter Y to Stop SQL Server Service.

Step 5 : Eventually, start the SQL Server Database Engine by Using SQL Server Configuration Manager.

Title: How to Start SQL Server without TempDB


问:
Application crashing only on lollipop devices
Application is working fine on all OS, but when i add facebook SDK, it gives me following error message on lollipop devices.

```<code>compile 'com.facebook.android:facebook-android-sdk:4.20.0'
</code>```

Caused by: java.lang.ClassNotFoundException: Didn't find class
  "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file
  "/data/app/com.myapp.app-3/base.apk", zip file

java.lang.NoClassDefFoundError: Failed resolution of:
  Lretrofit2/Retrofit$Builder;
               Caused by: java.lang.ClassNotFoundException: Didn't find class "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file
  "/data/app/com.myapp.app-3/base.apk", zip file "/data/app/
  com.myapp.app-3/split_lib_dependencies_apk.apk",

This is my gradle file.

```<code>compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {

    applicationId 'com.myapp.app'
    minSdkVersion 21
    targetSdkVersion 23
    versionCode 122
    versionName "1.2.5"
    multiDexEnabled true
    ndk {
        abiFilters "armeabi", "armeabi-v7a", "x86"
    }

configurations.all {
    resolutionStrategy {
    force 'com.squareup.okhttp:okhttp:2.4.0'
    force 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
    force 'com.squareup.okio:okio:1.11.0'
    force 'com.squareup.okhttp3:okhttp:3.6.0'
        force 'com.squareup.retrofit2:retrofit:2.2.0'
        force 'com.android.support:recyclerview-v7:25.0.0'
        force 'com.android.support:support-v4:25.0.0'
        force 'com.android.support:cardview-v7:25.0.0'
        force 'com.android.support:appcompat-v7:25.0.0'
        force 'com.android.support:design:25.0.0'
        force 'com.android.support:support-annotations:25.0.0'
        force 'com.google.android.gms:play-services-ads:9.0.1'
        force 'com.google.android.gms:play-services-location:9.0.1'
        force 'com.google.android.gms:play-services-auth-base:9.0.1'
        force 'com.google.android.gms:play-services-base:9.0.1'

        }

configurations.all {
    resolutionStrategy {
        failOnVersionConflict()
    }
}
</code>```

Kindly guide me what can be the reason of this crash, and why its only crashing on lollipop devices and working fine on Marshmallow and Nougat.

EDIT

If I don't use facebook sdk, everything seems fine, no crashes. Maybe Facebook sdk cause this problem but I don't know why

答:
You are using too many libraries so your methods have crossed over 64k so
you have to enable Multidex for you project

inside your build.gradle

```<code>     android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}
</code>```

and in AndroidManifest.xml

```<code>  <application
        android:name="android.support.multidex.MultiDexApplication" >
    ...
</application>
</code>```

see This for more info

Body:
Application is working fine on all OS, but when i add facebook SDK, it gives me following error message on lollipop devices.

compile 'com.facebook.android:facebook-android-sdk:4.20.0'

Caused by: java.lang.ClassNotFoundException: Didn't find class
  "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file
  "/data/app/com.myapp.app-3/base.apk", zip file

java.lang.NoClassDefFoundError: Failed resolution of:
  Lretrofit2/Retrofit$Builder;
               Caused by: java.lang.ClassNotFoundException: Didn't find class "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file
  "/data/app/com.myapp.app-3/base.apk", zip file "/data/app/
  com.myapp.app-3/split_lib_dependencies_apk.apk",

This is my gradle file.

compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {

    applicationId 'com.myapp.app'
    minSdkVersion 21
    targetSdkVersion 23
    versionCode 122
    versionName "1.2.5"
    multiDexEnabled true
    ndk {
        abiFilters "armeabi", "armeabi-v7a", "x86"
    }

configurations.all {
    resolutionStrategy {
    force 'com.squareup.okhttp:okhttp:2.4.0'
    force 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
    force 'com.squareup.okio:okio:1.11.0'
    force 'com.squareup.okhttp3:okhttp:3.6.0'
        force 'com.squareup.retrofit2:retrofit:2.2.0'
        force 'com.android.support:recyclerview-v7:25.0.0'
        force 'com.android.support:support-v4:25.0.0'
        force 'com.android.support:cardview-v7:25.0.0'
        force 'com.android.support:appcompat-v7:25.0.0'
        force 'com.android.support:design:25.0.0'
        force 'com.android.support:support-annotations:25.0.0'
        force 'com.google.android.gms:play-services-ads:9.0.1'
        force 'com.google.android.gms:play-services-location:9.0.1'
        force 'com.google.android.gms:play-services-auth-base:9.0.1'
        force 'com.google.android.gms:play-services-base:9.0.1'

        }

configurations.all {
    resolutionStrategy {
        failOnVersionConflict()
    }
}

Kindly guide me what can be the reason of this crash, and why its only crashing on lollipop devices and working fine on Marshmallow and Nougat.

EDIT

If I don't use facebook sdk, everything seems fine, no crashes. Maybe Facebook sdk cause this problem but I don't know why

Body:
You are using too many libraries so your methods have crossed over 64k so
you have to enable Multidex for you project

inside your build.gradle

     android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

and in AndroidManifest.xml

  <application
        android:name="android.support.multidex.MultiDexApplication" >
    ...
</application>

see This for more info


问:
Working with Pandas DataFrame / Sorting
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

```<code>import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)
</code>```

答:
You can use groupby in conjunction with a dictionary comprehension here. The result is a dictionary containing your company names as keys and the sub dataframes with top 25 payments as values:

```<code>def aggregate(sub_df):
    return sub_df.sort_values('PAC contribution', ascending=False).head(25)

grouped = df.groupby('Final PAC ID')
results = {company: aggregate(sub_df)
           for company, sub_df in grouped}
</code>```

Title: Working with Pandas DataFrame / Sorting

Body:
I'm working with a big dataset within Excel in which I'm trying to sort a number by top 25 per index value.

The datasite looks like this:

The Final PAC ID is the company number and changes (this does not show in the given data). The PAC contribution is the number I want to sort by.

So for example, there will be 50 contributions done by company C00003590, to different candidates with amount 'PAC contribution', I would like to sort the top 25 contributions done per company.

I've tried working with dictionaries, creating a dictionary for each company and adding in the candidate numbers as a string key, and the contribution as a value.

The code I have so far is the following (this might be the completely wrong way to go about it though):

import pandas as pd

df1 = pd.read_excel('Test2.xlsx')

dict_company = {}
k1 = str(df1['Final PAC ID'])
k2 = str(df1['Candidate ID'])

for each in range(0,100):
    dict_company[k1)[each]] = {}
    dict_company[k1)[each]] = k2[each]
    if each % 50 == 0:
        print(each)

print(dict_company)

for each in range(0,100):
    dict_company[k1][k2][each] = round(float(k1[each]))
    if each % 50:
        print(each)

print(dict_company)

Body:
You can use groupby in conjunction with a dictionary comprehension here. The result is a dictionary containing your company names as keys and the sub dataframes with top 25 payments as values:

def aggregate(sub_df):
    return sub_df.sort_values('PAC contribution', ascending=False).head(25)

grouped = df.groupby('Final PAC ID')
results = {company: aggregate(sub_df)
           for company, sub_df in grouped}


问:
Ember.js component rerender not rerendering
I'm trying to render some data into a table. The data is organized by years, and users can add years to the index.

When the user adds a year, the data for that year is loaded via AJAX and added to an Ember.Object info, like this:

```<code>var self=this;
Ember.$.getJSON('url'+year, function(data) {
  var info = self.get("info");
  info['total'][year] = data.total;
  info['commission'][year] = data.commission;
}
</code>```

In the template, the data is shown via each-in helpers:

```<code>{{#each-in info.total as |k t|}}
  {{t}}
{{/each-in}}
</code>```

Following the manual, here, since each-in is not bound to new properties, I added self.rerender(); after the ajax assigments in the component.

My issue is that the component is NOT rerendering. If I change routes and come back, the page is rerendered and the data shows, so the issue is clearly on the rerender() call.

PS: The code shown here is a simplified example; there is a reason why I must use each-in and any solution that necessitates changing the data structure won't help. I just need to know why rerender() is not rerendering and how to make it do so.

答:
What is your Ember version? The guide you had provided is for 2.6.0, and yet the following twiddle that works at Ember 2.6.0 seems to be working. However; after Glimmer 2 introduction (I mean since release 2.10.0) this does not seem to be working. As you can see in the guide of 2.10.0, the part explaining re-rendering is removed. Hence, it means you can no longer achieve what you want the same way.

If using each-in helper is a must for you; you can check the following twiddle that runs at Ember 2.12.0 and still works. Instead of forcing re-rendering via self.rerender within component; you can just rely on Ember's set just like Lux stated. I updated twiddle to reflect that.

Body:
I'm trying to render some data into a table. The data is organized by years, and users can add years to the index.

When the user adds a year, the data for that year is loaded via AJAX and added to an Ember.Object info, like this:

var self=this;
Ember.$.getJSON('url'+year, function(data) {
  var info = self.get("info");
  info['total'][year] = data.total;
  info['commission'][year] = data.commission;
}

In the template, the data is shown via each-in helpers:

{{#each-in info.total as |k t|}}
  {{t}}
{{/each-in}}

Following the manual, here, since each-in is not bound to new properties, I added self.rerender(); after the ajax assigments in the component.

My issue is that the component is NOT rerendering. If I change routes and come back, the page is rerendered and the data shows, so the issue is clearly on the rerender() call.

PS: The code shown here is a simplified example; there is a reason why I must use each-in and any solution that necessitates changing the data structure won't help. I just need to know why rerender() is not rerendering and how to make it do so.


问:
Shape Button with reducing height in CSS
We require guidance to create a button CSS like below . Kindly let us know if its possible with CSS, let us know if there are any examples from which i can evolve the shape.

答:
Easy with pseudoelement :before

.box {
  height:40px;
  width:200px;
  background-color:Orange;
  position:relative;
  display:inline-block;
  border-radius:0px 0px 5px 0;
  text-align:center;
  font-weight:bold;
  font-family:arial;
  color:#fff;
  font-size:20px;
  line-height:50px;
}
.box:before {
  position:absolute;
  content: "";
  width: 0;
  height: 0;
  border-top: 20px solid Orange;
  border-right: 197px solid transparent;
  bottom:-20px;
  left:0;
  border-radius:0px 0px 0px 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">+ADD NEW</div></code>```

Body:
Easy with pseudoelement :before

.box {
  height:40px;
  width:200px;
  background-color:Orange;
  position:relative;
  display:inline-block;
  border-radius:0px 0px 5px 0;
  text-align:center;
  font-weight:bold;
  font-family:arial;
  color:#fff;
  font-size:20px;
  line-height:50px;
}
.box:before {
  position:absolute;
  content: "";
  width: 0;
  height: 0;
  border-top: 20px solid Orange;
  border-right: 197px solid transparent;
  bottom:-20px;
  left:0;
  border-radius:0px 0px 0px 5px;
}

<div class="box">+ADD NEW</div>


问:
How to perform multiple left outer join using neo4j
How can I create multiple relationship in neo4j for performing the left outer join

My query in sql in as given below

```<code>Select SI.SendId,MC.CampaignName,SI.Name,
SI.SendDate,G.Name As GName,C.Name as FN From SendItem SI
LEFT OUTER JOIN Campaign MC ON MC.CampaignId=SI.MessageCampaignId
LEFT OUTER JOIN Groups G ON G.Id=SI.GroupId
LEFT OUTER JOIN Contact C ON C.ContactId=SI.Contact
order by SI.SendDate desc
</code>```

I am new to neo4j so please anyone help me to create relationship to execute the above query in neo4j

答:
Think about tables as nodes with a label, and about join as a relationships:

Query to create:

```<code>// Create campaign
MERGE (MC:Campaign {name: 'CampaignName'})

// Create group
MERGE (G:Groups {name: 'GroupsName'})

// Create contact
MERGE (C:Contact {name: 'ContactName'})

// Create item
MERGE (SI:SendItem {name: 'SendItemName', sendDate: timestamp()})

// Create relationships
MERGE (SI)-[:hasContact]->(C)
MERGE (SI)-[:inGroup]->(G)
MERGE (SI)-[:inCampaign]->(MC)
</code>```

Query to get:

```<code>MATCH (SI:SendItem)
WITH SI
     OPTIONAL MATCH (SI)-[:hasContact]->(C:Contact)
     OPTIONAL MATCH (SI)-[:inGroup]->(G:Group)
     OPTIONAL MATCH (SI)-[: inCampaign]->(MC:Campaign)
RETURN ID(SI) as id,
       SI.name as sendItemName,
       SI.sendDate as date,
       C.name as contactName,
       G.name as groupName,
       MC.name as campaignName
ORDER BY SI.sendDate desc
</code>```

Body:
How can I create multiple relationship in neo4j for performing the left outer join

My query in sql in as given below

Select SI.SendId,MC.CampaignName,SI.Name,
SI.SendDate,G.Name As GName,C.Name as FN From SendItem SI
LEFT OUTER JOIN Campaign MC ON MC.CampaignId=SI.MessageCampaignId
LEFT OUTER JOIN Groups G ON G.Id=SI.GroupId
LEFT OUTER JOIN Contact C ON C.ContactId=SI.Contact
order by SI.SendDate desc

I am new to neo4j so please anyone help me to create relationship to execute the above query in neo4j

Body:
Think about tables as nodes with a label, and about join as a relationships:

Query to create:

// Create campaign
MERGE (MC:Campaign {name: 'CampaignName'})

// Create group
MERGE (G:Groups {name: 'GroupsName'})

// Create contact
MERGE (C:Contact {name: 'ContactName'})

// Create item
MERGE (SI:SendItem {name: 'SendItemName', sendDate: timestamp()})

// Create relationships
MERGE (SI)-[:hasContact]->(C)
MERGE (SI)-[:inGroup]->(G)
MERGE (SI)-[:inCampaign]->(MC)

Query to get:

MATCH (SI:SendItem)
WITH SI
     OPTIONAL MATCH (SI)-[:hasContact]->(C:Contact)
     OPTIONAL MATCH (SI)-[:inGroup]->(G:Group)
     OPTIONAL MATCH (SI)-[: inCampaign]->(MC:Campaign)
RETURN ID(SI) as id,
       SI.name as sendItemName,
       SI.sendDate as date,
       C.name as contactName,
       G.name as groupName,
       MC.name as campaignName
ORDER BY SI.sendDate desc


问:
Wireshark/Winpcap Filter ICMPv6 Router Advertisement
What is the filter expression syntax on wireshark or winpcap to only display icmpv6 router advertisement?</p>

答:
Use Wireshark filters with these codes to filter out what you need respectively

neighbor advertisement:

icmpv6.type == 136

neighbour solicitation:

icmpv6.type == 135

router solicitation:

icmpv6.type == 133

router advertisement:

icmpv6.type == 134

Redirect:

icmpv6.type == 137