问:
Receive an array of strings from a function and find out it's length
I have this code:

```<code>char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}
</code>```

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

```<code>wordarr = SplitToWords(str);
</code>```

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks

答:
Yes, you could solve it by using a function with return value char **. However, there's no way to find out how many words there are afterwards.

You can solve this by allocating one more element for the return pointer and set it to NULL. Then you can get the number of words with this code:

```<code>wordarr = SplitToWords(str);
char **ptr=wordarr;
int noWords=0;
while(!*(ptr+noWords))
    noWords++;
</code>```

But if you want to return multiple data in C, you either need to define a return struct or using return arguments. In this case, it could look like this for the first option:

```<code>typedef struct wordList {
    char **wordarr;
    int noWords;
}

wordList SplitToWords(char* str);
</code>```

And the second:

```<code>char** SplitToWords(char* str, int *noWords);
</code>```

or

```<code>void SplitToWords(char* str, char*** wordarr, int *noWords);
</code>```

Note that there's three *. That's because we want it to be a pointer to char **

Body:
I have this code:

char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

wordarr = SplitToWords(str);

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks

Body:
Yes, you could solve it by using a function with return value char **. However, there's no way to find out how many words there are afterwards.

You can solve this by allocating one more element for the return pointer and set it to NULL. Then you can get the number of words with this code:

wordarr = SplitToWords(str);
char **ptr=wordarr;
int noWords=0;
while(!*(ptr+noWords))
    noWords++;

But if you want to return multiple data in C, you either need to define a return struct or using return arguments. In this case, it could look like this for the first option:

typedef struct wordList {
    char **wordarr;
    int noWords;
}

wordList SplitToWords(char* str);

And the second:

char** SplitToWords(char* str, int *noWords);

or

void SplitToWords(char* str, char*** wordarr, int *noWords);

Note that there's three *. That's because we want it to be a pointer to char **


来源: stackexchange

问:
onClick event - Run a javascript AFTER previous one has finished in the same onClick event
Code looks like this (My PHP server generates this line replacing the %% variables):

```<code><button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;
</code>```

I want THIS

```<code>ShowFieldTotal('inv_items','iprice','sub-total',2);
</code>```

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

```<code>ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')
</code>```

答:
ControlAltDel's answer makes it simple and easy. I actually added another parameter to my ServInfo which catches a string which it converts to code. Basically, I called the "eval" function to parse the code written in a string I pass to ServInfo. My new onClick event looks like this:

```<code><button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y','ShowFieldTotal(\'inv_items\',\'iprice\',\'sub-total\',2)');">+</button>
</code>```

I added the following to my ServInfo code:

```<code>// Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }
</code>```

For the curious, My ServInfo function now looks like this:

```<code>// AJAX simple HTTP GET request
function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "") {

var sparams = params;
var swpage = web_page;
var eobj = document.getElementById(pop_field_id);

// Get form field values if a form id is specified
if (form_id != "") {
    var efrm = document.getElementById(form_id);
    sparams += "&"+GetDivFields(form_id);
}

// If HTML element to populate does not exist, exit
if (typeof(eobj) == "!undefined" || eobj == null)   {return;}

if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else {
    // IE6-
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (append_data_to_output == "y") {
            document.getElementById(pop_field_id).innerHTML += this.responseText;
        }
        if (append_data_to_output == "") {
            document.getElementById(pop_field_id).innerHTML = this.responseText;
        }
        // Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }
    }
};
// Add the question mark if there is any parameters to pass
if (sparams != "") {swpage += "?";}

xmlhttp.open("GET",swpage+sparams,true);
xmlhttp.send();

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Code looks like this (My PHP server generates this line replacing the %% variables):

<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;

I want THIS

ShowFieldTotal('inv_items','iprice','sub-total',2);

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')

Body:
ControlAltDel's answer makes it simple and easy. I actually added another parameter to my ServInfo which catches a string which it converts to code. Basically, I called the "eval" function to parse the code written in a string I pass to ServInfo. My new onClick event looks like this:

<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y','ShowFieldTotal(\'inv_items\',\'iprice\',\'sub-total\',2)');">+</button>

I added the following to my ServInfo code:

// Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }

For the curious, My ServInfo function now looks like this:

// AJAX simple HTTP GET request
function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "") {

var sparams = params;
var swpage = web_page;
var eobj = document.getElementById(pop_field_id);

// Get form field values if a form id is specified
if (form_id != "") {
    var efrm = document.getElementById(form_id);
    sparams += "&"+GetDivFields(form_id);
}

// If HTML element to populate does not exist, exit
if (typeof(eobj) == "!undefined" || eobj == null)   {return;}

if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else {
    // IE6-
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (append_data_to_output == "y") {
            document.getElementById(pop_field_id).innerHTML += this.responseText;
        }
        if (append_data_to_output == "") {
            document.getElementById(pop_field_id).innerHTML = this.responseText;
        }
        // Execute a string if a user defined one
        if (exec_string != "") {
            eval(exec_string);
        }
    }
};
// Add the question mark if there is any parameters to pass
if (sparams != "") {swpage += "?";}

xmlhttp.open("GET",swpage+sparams,true);
xmlhttp.send();

}


问:
Change interior color based on cell value of color constant
I have an Excel range with the 8 color constants.  I just wanted to simply change the interior color of the cell in the adjacent column based on the cell value.  Unfortunately, I get a type mismatch which is because it is treating the value as a string, but I don't know how to convert it to constant.

For example, to change interior color to blue this works
rng.interior.color = vbblue

but not this
rng.interior.color = rng.value 'because it is a string "vbblue"

What can I do to convert rng.value from string to the color constant so the range in column E gets background color based on value in column D?

```<code>Dim colorRange As Range
Dim rng As Range
Set colorRange = Range("D1", Range("D1").End(xlDown).Address)

For Each rng In colorRange
  rng.Offset(, 1).Interior.Color = rng.Value
Next rng
</code>```

答:
You can do it directly with ColorIndex instead.  So if the cell says 5 or the related color index number, there's no need to change the code other than this line:

rng.Offset(, 1).Interior.ColorIndex = rng.Value

Body:
I have an Excel range with the 8 color constants.  I just wanted to simply change the interior color of the cell in the adjacent column based on the cell value.  Unfortunately, I get a type mismatch which is because it is treating the value as a string, but I don't know how to convert it to constant.

For example, to change interior color to blue this works
rng.interior.color = vbblue

but not this
rng.interior.color = rng.value 'because it is a string "vbblue"

What can I do to convert rng.value from string to the color constant so the range in column E gets background color based on value in column D?

Dim colorRange As Range
Dim rng As Range
Set colorRange = Range("D1", Range("D1").End(xlDown).Address)

For Each rng In colorRange
  rng.Offset(, 1).Interior.Color = rng.Value
Next rng


问:
Passing more data @input angular 2
How can we switch more than one component to another component? I need to use the "two way data binding".

I tried the following way:

```<code><app-drawer-menu [popup]="getPopupInstance" [appHeader]="getAppHeaderInstance"></app-drawer-menu>

 export class DrawerMenuComponent implements OnInit {

    @Input() private popup: DialogLoginSignupComponent;
    @Input() private appHeader: AppHeaderComponent;

    ....
</code>```

I need to go to the "DrawerMenuComponent" component "DialogLoginSignupComponent" and "AppHeaderComponent"

this does not work. Where am I wrong?

thx!

答:
If you want to do so, You'll have to use a Service and pass the component class name to use to your child component. Then, use the ComponentFactoryResolver to create the component like this :

```<code>let factory = this.cfr.resolveComponentFactory(MyComponent);
this.cmp = this.modalBody.createComponent(factory);
</code>```

If you want more details, please looks the file modal.component.ts here : Github link

Title: Passing more data @input angular 2

Body:
How can we switch more than one component to another component? I need to use the "two way data binding".

I tried the following way:

<app-drawer-menu [popup]="getPopupInstance" [appHeader]="getAppHeaderInstance"></app-drawer-menu>

 export class DrawerMenuComponent implements OnInit {

    @Input() private popup: DialogLoginSignupComponent;
    @Input() private appHeader: AppHeaderComponent;

    ....

I need to go to the "DrawerMenuComponent" component "DialogLoginSignupComponent" and "AppHeaderComponent"

this does not work. Where am I wrong?

thx!

Body:
If you want to do so, You'll have to use a Service and pass the component class name to use to your child component. Then, use the ComponentFactoryResolver to create the component like this :

let factory = this.cfr.resolveComponentFactory(MyComponent);
this.cmp = this.modalBody.createComponent(factory);

If you want more details, please looks the file modal.component.ts here : Github link


问:
C- Comparison operator instead of strcmp
What will happen if I use comparison operators to compare strings instead of strcmp in C? Will it compare its ASCII value and return results?</p>

答:
It will compare the addresses of the two pointers.

so:

```<code>char* a = "hello";
char* b = "test";
char* c = "hello";
char* d = a;

a == d; // true
a == b; // false
a == c; // true or false, depending on the compiler's behavior.
</code>```

The third example will be true if the compiler decides to recycle the actual string data for "hello", but it has no obligation to do so.

Body:
It will compare the addresses of the two pointers.

so:

char* a = "hello";
char* b = "test";
char* c = "hello";
char* d = a;

a == d; // true
a == b; // false
a == c; // true or false, depending on the compiler's behavior.

The third example will be true if the compiler decides to recycle the actual string data for "hello", but it has no obligation to do so.


问:
Conditional appending items from a list into multiple documents
I am pretty new to python. My question is related to appending data based on index[0] into a set of documents (e.g. doc1,doc2).

```<code>g = [('elsiescdesign', 'flowers', 6),('elsiescdesign', 'running', 6), ('fulviomeloni', 'flowers', 1), ('connor-burrows', 'flowers', 1), ('withoutroots', 'flowers', 1), ('thegreenraven', 'flowers', 2), ('taylor-music', 'flowers', 2), ('eda11y', 'flower', 7), ('2liice', 'flower', 1)]
</code>```

Above is the sample data: [(blogger,tag,countsoftagusedbyblooger)]

I want to append all the bloggers tags into a document each e.g.

```<code>elsiescdesign =['flowers','flowers','flowers','flowers','flowers','flowers','running','running','running','running','running','running']
</code>```

But not just for one bloggers, all the bloggers here. The reason for this is so that I can build my topic model.

答:
try this </p>

```<code>bloggers = {}
for b in g:
    bloggers.setdefault(b[0], []).extend([b[1]] * b[2])
</code>```

Body:
I am pretty new to python. My question is related to appending data based on index[0] into a set of documents (e.g. doc1,doc2).

g = [('elsiescdesign', 'flowers', 6),('elsiescdesign', 'running', 6), ('fulviomeloni', 'flowers', 1), ('connor-burrows', 'flowers', 1), ('withoutroots', 'flowers', 1), ('thegreenraven', 'flowers', 2), ('taylor-music', 'flowers', 2), ('eda11y', 'flower', 7), ('2liice', 'flower', 1)]

Above is the sample data: [(blogger,tag,countsoftagusedbyblooger)]

I want to append all the bloggers tags into a document each e.g.

elsiescdesign =['flowers','flowers','flowers','flowers','flowers','flowers','running','running','running','running','running','running']

But not just for one bloggers, all the bloggers here. The reason for this is so that I can build my topic model.

Body:
try this

bloggers = {}
for b in g:
    bloggers.setdefault(b[0], []).extend([b[1]] * b[2])


问:
Filtering with Django-Taggit: Is it possible to filter for model entries that include all tags?
The code:

```<code>Food.objects.filter(tags__name__in=["Tag 1","Tag 2","Tag 3"]).distinct()
</code>```

More precisely, if I want to filter for Food(s) where Food(s) has at least all three tags (not just one or two of the three, but could have more than the three), is there a modification to the filter provided in docs that achieves this result?

http://django-taggit.readthedocs.io/en/latest/api.html

答:
Try:

```<code>tag_list = ["Tag 1","Tag 2","Tag 3"]
</code>```

one way is to use multiple filters in a chained manner. Like this

```<code>Food.objects.filter(tags__name=tag_list[0]).filter(tags__name=tag_list[1]).filter(tags__name=tag_list[3]).distinct()
</code>```

another way is to use annotation approach

```<code>Food.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).distinct()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The code:

Food.objects.filter(tags__name__in=["Tag 1","Tag 2","Tag 3"]).distinct()

More precisely, if I want to filter for Food(s) where Food(s) has at least all three tags (not just one or two of the three, but could have more than the three), is there a modification to the filter provided in docs that achieves this result?

http://django-taggit.readthedocs.io/en/latest/api.html

Body:
Try:

tag_list = ["Tag 1","Tag 2","Tag 3"]

one way is to use multiple filters in a chained manner. Like this

Food.objects.filter(tags__name=tag_list[0]).filter(tags__name=tag_list[1]).filter(tags__name=tag_list[3]).distinct()

another way is to use annotation approach

Food.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).distinct()


问:
@InjectMocks causes NPE
I have the following ApplicationConfiguration:

```<code>class ApplicationConfiguration {
    private SQSConfig SQSConfig;
    // Other configs and getters/setters
}
</code>```

Then I have in my Application

```<code>class Application {
   private Dequeuer dequeuer;

   public void run(ApplicationConfiguration config) {
       // I need to pass ApplicationConfiguration because there are other variables that I need to use
      dequeuer = new Dequeuer(config);
      // Start dequeuer
   }
}
</code>```

So in my test for Application, I want to use @InjectMethod for the Dequeuer:

```<code>class ApplicationTest {
    @Mock
    private ApplicationConfig config;
    @Mock
    private SQSConfig sqsConfig;
    @InjectMocks
    private Dequeuer dequeuer = new Dequeuer(config);

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(config.getSQSConfig()).thenReturn(sqsConfig);
    }
}
</code>```

The problem is, the @InjectMethod is initialized before the when, so I get a NPE. What do I do?

答:
The problem is, the @InjectMethod is initialized before the when, so I
  get a NPE. What do I do?

MockitoAnnotations.initMocks(this) will indeed first create mocks, and this is the way which it should work. You don't record a mock behavior before instantiating a mock.

Besides, it is not @InjectMock but @InjectMocks.

And you don't use it correctly.

Don't pass the parameter to the constructor, it will be directly injected by the Mockito framework if your Dequeuer class declares a Dequeuer(ApplicationConfig appConfig) constructor:

```<code>@Mock
private ApplicationConfig config;
...
@InjectMocks
private Dequeuer dequeuer;
</code>```

The NPE is probably caused by a bad use of the Mockito Framework but with the code shown in your question, this is hard to identify.

Title: @InjectMocks causes NPE

Body:
I have the following ApplicationConfiguration:

class ApplicationConfiguration {
    private SQSConfig SQSConfig;
    // Other configs and getters/setters
}

Then I have in my Application

class Application {
   private Dequeuer dequeuer;

   public void run(ApplicationConfiguration config) {
       // I need to pass ApplicationConfiguration because there are other variables that I need to use
      dequeuer = new Dequeuer(config);
      // Start dequeuer
   }
}

So in my test for Application, I want to use @InjectMethod for the Dequeuer:

class ApplicationTest {
    @Mock
    private ApplicationConfig config;
    @Mock
    private SQSConfig sqsConfig;
    @InjectMocks
    private Dequeuer dequeuer = new Dequeuer(config);

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(config.getSQSConfig()).thenReturn(sqsConfig);
    }
}

The problem is, the @InjectMethod is initialized before the when, so I get a NPE. What do I do?

Body:
The problem is, the @InjectMethod is initialized before the when, so I
  get a NPE. What do I do?

MockitoAnnotations.initMocks(this) will indeed first create mocks, and this is the way which it should work. You don't record a mock behavior before instantiating a mock.

Besides, it is not @InjectMock but @InjectMocks.

And you don't use it correctly.

Don't pass the parameter to the constructor, it will be directly injected by the Mockito framework if your Dequeuer class declares a Dequeuer(ApplicationConfig appConfig) constructor:

@Mock
private ApplicationConfig config;
...
@InjectMocks
private Dequeuer dequeuer;

The NPE is probably caused by a bad use of the Mockito Framework but with the code shown in your question, this is hard to identify.


问:
2 classes for 1 div, class has space in name
I want to give a div 2 classes, however, one of the class names has a space in it. I want to give a div the "section scrollspy" class and carousel class.

Will putting a space in between classes still work?

For example:

```<code><div class="section scrollspy carousel">
</code>```

Or is there a better way to do this?

答:
Spaces are invalid in class names, the normal way to do it is to use a hyphen instead of a space so it would be:

```<code><div class="section-scrollspy carousel">
</code>```

Theres a good post here that talks about valid CSS names.

Body:
I want to give a div 2 classes, however, one of the class names has a space in it. I want to give a div the "section scrollspy" class and carousel class.

Will putting a space in between classes still work?

For example:

Or is there a better way to do this?

Body:
Spaces are invalid in class names, the normal way to do it is to use a hyphen instead of a space so it would be:

<div class="section-scrollspy carousel">

Theres a good post here that talks about valid CSS names.


问:
How can I allocate memory in Linux that meets paging and cacheability requirements?
I want to allocate space for a large array that will be write-only until the very end of the program.  For that reason, I don't care if it's it cached.

I also want to access this very frequently, so I don't want to have to do a page walk more than once.  For that reason I want it to be allocated in a large a page (e.g. 4M).

So how can I...

...request the memory to be either uncacheable or write-through?

...request the memory to be placed in a large page?

I am working in Linux.

答:
With transparent hugepages, simply allocating a 4M-aligned buffer will work.  Use aligned_alloc or posix_memalign to get a pointer you can free.  (Note that aligned_alloc is required to fail if the buffer size isn't a multiple of the alignment.  /facepalm).

Depending on your setting for /sys/kernel/mm/transparent_hugepage/defrag, you may need to use madvise(MADV_HUGEPAGE) on the buffer to strongly encourage the kernel to use hugepages.

Also note that x86-64 uses 2M hugepages.  x86-32 uses 4M hugepages.  Aligning to 4M is fine if you want the easy solution for both.

request the memory to be either uncacheable or write-through?

AFAIK, you can't easily do that through normal Linux APIs.  NT stores work to normal write-back memory, so use that instead. (They over-ride the memory type and are weakly-ordered cache-bypassing).

But if you're not writing full cache-lines at a time, you definitely want cached writes.  Especially if there's any spatial or temporal locality, but even if not then letting the store buffer do its job (hiding the latency of cache-miss stores) is a good thing.


问:
AWS Android SDK not able to access s3 in "sub-directory"
I'm using the android sdk generated by AWS API Gateway to get a pre-signed URL for objects in s3 (lambda behind API gateway).

My s3 bucket looks like this:

```<code>* module_a
|\
| * file_a
| * subdir_a
|  \
|   * file_sa
* module_b
</code>```

This works perfectly for file_a, but for file_sa it doesn't. At least not when I use the android SDK, there I get an URL where the slash is replaced with %25252F.
However, when I test the api in the console, I get the correct URL.

Is there anything I can do with the SDK to fix this?

Update

Here's the chain of code snippets involved in this problem.

Android code to download file (exception happens in last line)

```<code>fileName = "css/style.css"; // file in s3
moduleName = "main"; // folder in s3
[...]
ApiClientFactory factory = new ApiClientFactory().credentialsProvider(
    aws.credentialsProvider);
apiClient = factory.build(myAPIClient.class);
apiClient.modulesModuleFileGet(fileName.replace("/", "%2F"), moduleName);
URL url = new URL(url_path.getUrl());
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
</code>```

API Gateway

The api endpoint used above is configured with two path parameters (module name and file name). The body mapping template for the call to lambda looks like this:

```<code>#set($inputRoot = $input.path('$'))
{
  "module" : "$input.params('module')",
  "file": "$input.params('file')"
}
</code>```

Lambda

```<code>from __future__ import print_function

import json
import urllib
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
        key = event['module'] + "/" + event['file'].replace("%2F", "/")
        url = s3.generate_presigned_url(
                "get_object",
                Params={'Bucket':"mybucket",
                        'Key': key},
                ExpiresIn=60)
        return {"url": url}
</code>```

答:
I've got it to work after following the comments. However I still somehow get double quoted slashes. Here's the working code

Android

```<code>public Url modulesModuleFileGet(String fileName, String moduleName) {
    try {
        String fileNameEnc = URLEncoder.encode(fileName, "UTF-8");
        Url ret = getApiClient().modulesModuleFileGet(fileNameEnc, moduleName);
        return ret;
    } catch (UnsupportedEncodingException e){
        Log.e(TAG, "> modulesModuleFileGet(", e);
        return null;
    }
}
</code>```

Lambda

```<code>def lambda_handler(event, context):
        key = event['module'] + "/" + urllib.unquote_plus(urllib.unquote_plus(event['file']))
        url = s3.generate_presigned_url(
                "get_object",
                Params={'Bucket':"my",
                        'Key': key},
                ExpiresIn=60)
        return {"url": url}
</code>```

I'd still welcome further suggestions on how to improve this, but for now it is working. Thanks for the comments pointing me in the right direction.

Body:
I'm using the android sdk generated by AWS API Gateway to get a pre-signed URL for objects in s3 (lambda behind API gateway).

My s3 bucket looks like this:

* module_a
|\
| * file_a
| * subdir_a
|  \
|   * file_sa
* module_b

This works perfectly for file_a, but for file_sa it doesn't. At least not when I use the android SDK, there I get an URL where the slash is replaced with %25252F.
However, when I test the api in the console, I get the correct URL.

Is there anything I can do with the SDK to fix this?

Update

Here's the chain of code snippets involved in this problem.

Android code to download file (exception happens in last line)

fileName = "css/style.css"; // file in s3
moduleName = "main"; // folder in s3
[...]
ApiClientFactory factory = new ApiClientFactory().credentialsProvider(
    aws.credentialsProvider);
apiClient = factory.build(myAPIClient.class);
apiClient.modulesModuleFileGet(fileName.replace("/", "%2F"), moduleName);
URL url = new URL(url_path.getUrl());
URLConnection connection = url.openConnection();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());

API Gateway

The api endpoint used above is configured with two path parameters (module name and file name). The body mapping template for the call to lambda looks like this:

#set($inputRoot = $input.path('$'))
{
  "module" : "$input.params('module')",
  "file": "$input.params('file')"
}

Lambda

from __future__ import print_function

import json
import urllib
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
        key = event['module'] + "/" + event['file'].replace("%2F", "/")
        url = s3.generate_presigned_url(
                "get_object",
                Params={'Bucket':"mybucket",
                        'Key': key},
                ExpiresIn=60)
        return {"url": url}

Body:
I've got it to work after following the comments. However I still somehow get double quoted slashes. Here's the working code

Android

public Url modulesModuleFileGet(String fileName, String moduleName) {
    try {
        String fileNameEnc = URLEncoder.encode(fileName, "UTF-8");
        Url ret = getApiClient().modulesModuleFileGet(fileNameEnc, moduleName);
        return ret;
    } catch (UnsupportedEncodingException e){
        Log.e(TAG, "> modulesModuleFileGet(", e);
        return null;
    }
}

Lambda

def lambda_handler(event, context):
        key = event['module'] + "/" + urllib.unquote_plus(urllib.unquote_plus(event['file']))
        url = s3.generate_presigned_url(
                "get_object",
                Params={'Bucket':"my",
                        'Key': key},
                ExpiresIn=60)
        return {"url": url}

I'd still welcome further suggestions on how to improve this, but for now it is working. Thanks for the comments pointing me in the right direction.


问:
printing list of objects as links in vanilla javascript
I am trying to print a list of objects using vanilla javascript. In my loop, only the last item is getting printed. How do I fix this? I tried appending each li to a variable (node) and then append it to my ul id but that did not work. Here is the fiddle:

https://codepen.io/anon/pen/LLgZzw?editors=1011

HTML

```<code><ul id="list"></ul>
</code>```

JS

```<code>let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};
function printList(obj){
  for(let key in obj){
    console.log(key);
    list.innerHTML = `<li><a href= ${obj[key]}>${key}</a></li>`;
  }
  //list.appendChild(li);
}
printList(obj);
</code>```

答:
You need to concat value to innerHTML.In your case it is always the last value of the iteration that will be set in innerHTML

let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};

function printList(obj) {
  for (let key in obj) {
    console.log(key);
    //Changed here. added + before ==.It will concat the current value with previous value
    list.innerHTML += `<li>${key}</li>`;
  }
  //list.appendChild(li);
}
printList(obj);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list"></ul></code>```

Body:
I am trying to print a list of objects using vanilla javascript. In my loop, only the last item is getting printed. How do I fix this? I tried appending each li to a variable (node) and then append it to my ul id but that did not work. Here is the fiddle:

https://codepen.io/anon/pen/LLgZzw?editors=1011

HTML

JS

let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};
function printList(obj){
  for(let key in obj){
    console.log(key);
    list.innerHTML = `<li><a href= ${obj[key]}>${key}</a></li>`;
  }
  //list.appendChild(li);
}
printList(obj);

Body:
You need to concat value to innerHTML.In your case it is always the last value of the iteration that will be set in innerHTML

let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};

function printList(obj) {
  for (let key in obj) {
    console.log(key);
    //Changed here. added + before ==.It will concat the current value with previous value
    list.innerHTML += `<li><a href= ${obj[key]}>${key}</a></li>`;
  }
  //list.appendChild(li);
}
printList(obj);

<ul id="list"></ul>


问:
Swift: Nested type erasure
Using Swift 3.0 (I could use Swift 4.0 if that would help me... But I don't think it will) I would like to Type Erase two levels. I what to type erase a protocol having an associatedtype, which conforms to a protocol that in turn itself has an associatedtype. So one could say that I want to type erase nested associatedtypes.

The code below is an extremely simplified version of my code, but it is more clear that way. So what I really want is something like this:

Original Scenario - Unsolved

```<code>protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedType Engine: Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedType Transport: Vehicle
    var transport: Transport { get }
}
</code>```

And then I would like to type erase Transportation and be able to store an array of AnyTransportation which could have any Vehicle which in turn could have any Motor.

So this is a scenario with 3 protocols, where 2 of them have (nested) associatedtypes.

I do not know how to do this. Actually, I do not even know how to solve the even more simple scenario:

Simplified Scenario - Unsolved

We could simplify the original scenario above to a version where we have 2 protocols, where only 1 of them have an associatedtype:

```<code>protocol Vehicle {
    var speed: Int { get }
}

protocol Transportation {
    associatedtype Transport: Vehicle
    var transport: Transport { get }
    var name: String { get }
}
</code>```

Then lets say that we have a Bus conforming to Vehicle:

```<code>struct Bus: Vehicle {
    var speed: Int { return 60 }
}
</code>```

And then we have two different BusLines, RedBusLine and BlueBusLine both conforming to Transportation

```<code>struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

struct BlueBusLine: Transportation {
    let transport: Bus
    var name = "Blue line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}
</code>```

We can then type erase Transportation using the base and box pattern and classes, as described by bignerdranch here:

```<code>final class AnyTransportation<_Transport: Vehicle>: Transportation {
    typealias Transport = _Transport
    private let box: _AnyTransportationBase<Transport>
    init<Concrete: Transportation>(_ concrete: Concrete) where Concrete.Transport == Transport {
        box = _AnyTransportationBox(concrete)
    }
    init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { return box.transport }
    var name: String { return box.name }
}

final class _AnyTransportationBox<Concrete: Transportation>: _AnyTransportationBase<Concrete.Transport> {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    override var transport: Transport { return concrete.transport }
    override var name: String {return concrete.name }
}

class _AnyTransportationBase<_Transport: Vehicle> : Transportation {
    typealias Transport = _Transport
    init() { if type(of: self) == _AnyTransportationBase.self { fatalError("Use Box class") } }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { fatalError("abstract") }
    var name: String { fatalError("abstract") }
}
</code>```

We can then put either RedBusLine or BlueBusLine in

```<code>let busRides: [AnyTransportation<Bus>] = [AnyTransportation(RedBusLine()), AnyTransportation(BlueBusLine())]
busRides.forEach { print($0.name) } // prints "Red line\nBlue line"
</code>```

In the blog post about type erasure linked to above, what I want is actually a workaround for Homogeneous Requirement.

Imagine we have another Vehicle, e.g a Ferry and a FerryLine:

```<code>struct Ferry: Vehicle {
    var speed: Int { return 40 }
}

struct FerryLine: Transportation {
    let transport: Ferry = Ferry()
    var name = "Ferry line"
}
</code>```

I guess we want to type erase Vehicle now? Because we want an array of AnyTransportation<AnyVehicle>, right?

```<code>final class AnyVehicle: Vehicle {
    private let box: _AnyVehicleBase
    init<Concrete: Vehicle>(_ concrete: Concrete) {
        box = _AnyVehicleBox(concrete)
    }
    var speed: Int { return box.speed }
}

final class _AnyVehicleBox<Concrete: Vehicle>: _AnyVehicleBase {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    override var speed: Int { return concrete.speed }
}

class _AnyVehicleBase: Vehicle {
    init() { if type(of: self) == _AnyVehicleBase.self { fatalError("Use Box class") } }
    var speed: Int { fatalError("abstract") }
}

// THIS DOES NOT WORK
let rides: [AnyTransportation<AnyVehicle>] = [AnyTransportation(AnyVehicle(RedBusLine())), AnyTransportation(AnyVehicle(FerryLine()))] // COMPILE ERROR: error: argument type 'RedBusLine' does not conform to expected type 'Vehicle'
</code>```

Of course this does not work... because AnyTransportation expects passing in a type conforming to Transportation, but AnyVehicle does not conform to it of course.

But I have not been able to figure out a solution for this. Is there any?

Question 1: Is it possible to type erase the Simple Scenario allowing for: [AnyTransportation<AnyVehicle>]?

Question 2: If the Simple Scenario is solvable, is the original scenario also solvable?

Below follows only a more detailed explanation of what I want to achieve with the Original Scenario

Original Scenario - Expanded

My original need is to put any Transportation, having any Vehicle, that in itself has any Motor inside the same array:

```<code>let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array
</code>```

答:
Hamish's solution is definitely the correct way to do what you've asked, but when you get into this much type erasure, you need to ask yourself some questions.

Let's start at the end:

```<code>let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array
</code>```

What can you possibly do with transportations? Seriously, what code would you write that iterated over it without doing as? checking? The only general method available is name. You couldn't really call anything else because the types would mismatch at compile time.

This is really close to the example from my Beyond Crusty talk, and I think you should be looking to the same place for solutions. For example, rather than this:

```<code>struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}
</code>```

consider solutions that look like this (i.e. no protocols and all the PAT problems evaporate):

```<code>let redBusLine = Transportation(name: "Red line",
                                transport: Vehicle(name: "Bus",
                                                   motor: Motor(power: 100))
</code>```

Next, think really hard about whether you mean Bus to be a struct. Are two busses with the same properties the same bus?

```<code>let red = Bus()
let blue = Bus()
</code>```

Are red and blue the same bus? If they're not, then this is not a value type. This is a reference type and should be a class. A lot of Swift talks push us towards protocols and shame us about classes, but the actual design of Swift encourages exactly the opposite. Make sure you're avoiding classes because these are real value types, and not just out of peer pressure. Don't use protocols just because it's Swift. I find PATs to be a tool for very specialized needs (like Collection), not a go-to solution for most problems. (Until Swift 4, even Collection was a total mess of a protocol.)

Title: Swift: Nested type erasure

Body:
Using Swift 3.0 (I could use Swift 4.0 if that would help me... But I don't think it will) I would like to Type Erase two levels. I what to type erase a protocol having an associatedtype, which conforms to a protocol that in turn itself has an associatedtype. So one could say that I want to type erase nested associatedtypes.

The code below is an extremely simplified version of my code, but it is more clear that way. So what I really want is something like this:

Original Scenario - Unsolved

protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedType Engine: Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedType Transport: Vehicle
    var transport: Transport { get }
}

And then I would like to type erase Transportation and be able to store an array of AnyTransportation which could have any Vehicle which in turn could have any Motor.

So this is a scenario with 3 protocols, where 2 of them have (nested) associatedtypes.

I do not know how to do this. Actually, I do not even know how to solve the even more simple scenario:

Simplified Scenario - Unsolved

We could simplify the original scenario above to a version where we have 2 protocols, where only 1 of them have an associatedtype:

protocol Vehicle {
    var speed: Int { get }
}

protocol Transportation {
    associatedtype Transport: Vehicle
    var transport: Transport { get }
    var name: String { get }
}

Then lets say that we have a Bus conforming to Vehicle:

struct Bus: Vehicle {
    var speed: Int { return 60 }
}

And then we have two different BusLines, RedBusLine and BlueBusLine both conforming to Transportation

struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

struct BlueBusLine: Transportation {
    let transport: Bus
    var name = "Blue line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

We can then type erase Transportation using the base and box pattern and classes, as described by bignerdranch here:

final class AnyTransportation<_Transport: Vehicle>: Transportation {
    typealias Transport = _Transport
    private let box: _AnyTransportationBase<Transport>
    init<Concrete: Transportation>(_ concrete: Concrete) where Concrete.Transport == Transport {
        box = _AnyTransportationBox(concrete)
    }
    init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { return box.transport }
    var name: String { return box.name }
}

final class _AnyTransportationBox<Concrete: Transportation>: _AnyTransportationBase<Concrete.Transport> {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    override var transport: Transport { return concrete.transport }
    override var name: String {return concrete.name }
}

class _AnyTransportationBase<_Transport: Vehicle> : Transportation {
    typealias Transport = _Transport
    init() { if type(of: self) == _AnyTransportationBase.self { fatalError("Use Box class") } }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { fatalError("abstract") }
    var name: String { fatalError("abstract") }
}

We can then put either RedBusLine or BlueBusLine in

let busRides: [AnyTransportation<Bus>] = [AnyTransportation(RedBusLine()), AnyTransportation(BlueBusLine())]
busRides.forEach { print($0.name) } // prints "Red line\nBlue line"

In the blog post about type erasure linked to above, what I want is actually a workaround for Homogeneous Requirement.

Imagine we have another Vehicle, e.g a Ferry and a FerryLine:

struct Ferry: Vehicle {
    var speed: Int { return 40 }
}

struct FerryLine: Transportation {
    let transport: Ferry = Ferry()
    var name = "Ferry line"
}

I guess we want to type erase Vehicle now? Because we want an array of AnyTransportation<AnyVehicle>, right?

final class AnyVehicle: Vehicle {
    private let box: _AnyVehicleBase
    init<Concrete: Vehicle>(_ concrete: Concrete) {
        box = _AnyVehicleBox(concrete)
    }
    var speed: Int { return box.speed }
}

final class _AnyVehicleBox<Concrete: Vehicle>: _AnyVehicleBase {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    override var speed: Int { return concrete.speed }
}

class _AnyVehicleBase: Vehicle {
    init() { if type(of: self) == _AnyVehicleBase.self { fatalError("Use Box class") } }
    var speed: Int { fatalError("abstract") }
}

// THIS DOES NOT WORK
let rides: [AnyTransportation<AnyVehicle>] = [AnyTransportation(AnyVehicle(RedBusLine())), AnyTransportation(AnyVehicle(FerryLine()))] // COMPILE ERROR: error: argument type 'RedBusLine' does not conform to expected type 'Vehicle'

Of course this does not work... because AnyTransportation expects passing in a type conforming to Transportation, but AnyVehicle does not conform to it of course.

But I have not been able to figure out a solution for this. Is there any?

Question 1: Is it possible to type erase the Simple Scenario allowing for: [AnyTransportation<AnyVehicle>]?

Question 2: If the Simple Scenario is solvable, is the original scenario also solvable?

Below follows only a more detailed explanation of what I want to achieve with the Original Scenario

Original Scenario - Expanded

My original need is to put any Transportation, having any Vehicle, that in itself has any Motor inside the same array:

let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array

Body:
Hamish's solution is definitely the correct way to do what you've asked, but when you get into this much type erasure, you need to ask yourself some questions.

Let's start at the end:

let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array

What can you possibly do with transportations? Seriously, what code would you write that iterated over it without doing as? checking? The only general method available is name. You couldn't really call anything else because the types would mismatch at compile time.

This is really close to the example from my Beyond Crusty talk, and I think you should be looking to the same place for solutions. For example, rather than this:

struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

consider solutions that look like this (i.e. no protocols and all the PAT problems evaporate):

let redBusLine = Transportation(name: "Red line",
                                transport: Vehicle(name: "Bus",
                                                   motor: Motor(power: 100))

Next, think really hard about whether you mean Bus to be a struct. Are two busses with the same properties the same bus?

let red = Bus()
let blue = Bus()

Are red and blue the same bus? If they're not, then this is not a value type. This is a reference type and should be a class. A lot of Swift talks push us towards protocols and shame us about classes, but the actual design of Swift encourages exactly the opposite. Make sure you're avoiding classes because these are real value types, and not just out of peer pressure. Don't use protocols just because it's Swift. I find PATs to be a tool for very specialized needs (like Collection), not a go-to solution for most problems. (Until Swift 4, even Collection was a total mess of a protocol.)


问:
convert RGB to grayscale in C
I used many formulas to convert from RGB to grayscale, but didn't get good results compared to GIMP.

I already tested the following formulas:

```<code>gray = (int)(0.299 * r + 0.587 * g + 0.144 * b);

gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);

gray = (int)(0.2126 * r + 0.7152 * g + 0.0722 * b);

gray = (int) (0.35*r + 0.50*g + 0.15*b);

gray = ((r * 61) + (g * 174) + (b * 21)) / 256;

gray = (int)((4897 * r + 9617 * g + 1868 * b) >> 14);

gray = r; if(g > gray) gray = g; if(b > gray) gray = b;
</code>```

答:
The gimp help for the desaturate tool states three available formulas corresponding to the options named "Lighness", "Luminosity" and "Average". Those would be:

Lightness: 0.5 * (max(R,G,B) + min(R,G,B))

Luminosity: (0.21 * R) + (0.72 * G) + (0.07 * B)

Average: (R + G + B)/3

Title: convert RGB to grayscale in C

Body:
I used many formulas to convert from RGB to grayscale, but didn't get good results compared to GIMP.

I already tested the following formulas:

gray = (int)(0.299 * r + 0.587 * g + 0.144 * b);

gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);

gray = (int)(0.2126 * r + 0.7152 * g + 0.0722 * b);

gray = (int) (0.35*r + 0.50*g + 0.15*b);

gray = ((r * 61) + (g * 174) + (b * 21)) / 256;

gray = (int)((4897 * r + 9617 * g + 1868 * b) >> 14);

gray = r; if(g > gray) gray = g; if(b > gray) gray = b;


问:
Right align text in an HTML.TextAreaFor
How to right align arabic text in TextArea? For TextBox dir = "rtl" property works fine. But for TextArea it is not. </p>

```<code><div class="col-md-12">
   <div class="form-group">
      @Html.LabelFor(model => model.DescriptionAr, new { @class = "control-label" })
      @Html.ValidationMessageFor(model => model.DescriptionAr)
      @Html.TextAreaFor(model => model.DescriptionAr, 10, 10, new { @class = "ckeditor form-control", dir = "rtl" })
   </div>
</div>
</code>```

答:
So i solved it by changing the config settings of the "CKEDITOR" plugin.

HTML Code:

```<code>  <div class="col-md-12">
                            <div class="form-group">
                                @Html.LabelFor(model => model.DescriptionAr, new { @class = "control-label" })
                                @Html.ValidationMessageFor(model => model.DescriptionAr)
                                @Html.TextAreaFor(model => model.DescriptionAr, 10, 10, new { @class = "ckeditor form-control", id = "descArEditor" })
                            </div>
                        </div>
</code>```

Javascript:

```<code>CKEDITOR.replace('descArEditor',
        {
            contentsLangDirection: 'rtl'
        });
</code>```

Title: Right align text in an HTML.TextAreaFor

Body:
How to right align arabic text in TextArea? For TextBox dir = "rtl" property works fine. But for TextArea it is not.

      @Html.LabelFor(model => model.DescriptionAr, new { @class = "control-label" })
      @Html.ValidationMessageFor(model => model.DescriptionAr)
      @Html.TextAreaFor(model => model.DescriptionAr, 10, 10, new { @class = "ckeditor form-control", dir = "rtl" })

Body:
So i solved it by changing the config settings of the "CKEDITOR" plugin.

HTML Code:

  <div class="col-md-12">
                            <div class="form-group">
                                @Html.LabelFor(model => model.DescriptionAr, new { @class = "control-label" })
                                @Html.ValidationMessageFor(model => model.DescriptionAr)
                                @Html.TextAreaFor(model => model.DescriptionAr, 10, 10, new { @class = "ckeditor form-control", id = "descArEditor" })
                            </div>
                        </div>

Javascript:

CKEDITOR.replace('descArEditor',
        {
            contentsLangDirection: 'rtl'
        });


问:
Running Code with Python 3.5.0 + Sublime 3.0 on Mac
My question is, can Sublime 3 be setup to run the code that has been written with in Sublime.   I've have searched on here and the internet and have tried numerous different suggestions.   If the answer has already been posted and someone could point me in the proper direction / URL I'd appreciate it.   If it cannot be done and you have other suggestion's I'll give it a try.</p>

答:
For python 3.6 i'm using:

```<code>{
    "cmd": ["/usr/local/bin/python3.6", "$file"]
}
</code>```

And everything works fine! Don't forget to get full path to your python interpreter.

Body:
For python 3.6 i'm using:

{
    "cmd": ["/usr/local/bin/python3.6", "$file"]
}

And everything works fine! Don't forget to get full path to your python interpreter.


问:
Is this better approach of creating Objects in Java than this?
Approach of creating objects

At present,

I have the following
structure

```<code>Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}
</code>```

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?

答:
Hi it really depends on what your program does whether this is an appropriate structure or not. If methods B, C and D are not used, perhaps it may not be appropriate for class Z to extend the A.

So maybe think over if it makes sense

To prevent yourself from coding an error you could throw an UnsupportedOperationException(String message) on all the overriding methods.

Another idea may be to add the @Deprecated annotation to that method. This should warn you if you accidentally use that method in your code. This is a hack and abusing it though.

ContentLicense: CC BY-SA 2.5

Body:
Approach of creating objects

At present,

I have the following
structure

Abstract Class A{

public abstract void B();
public abstract void C();
public abstract void D();

public void E(){
 sample Statements;

}
}

public class Z extends A{

    public void B() {
        // TODO Auto-generated method stub

    }

    public void C() {
        // TODO Auto-generated method stub

    }

    public void D() {
        // TODO Auto-generated method stub

    }

    public void X() {
        Sample Statements;;
        Whcih is very specific to this Class;

    }

}

My Question in the above class Z, I dont want to impl
I will define only method X which is very specific to

in the Same Way I will define a new Class P, which im
but other 2 methods are not implemented.

Is this the right way to implement the way of Creatin
suit my requirements to create an object?

Or is there any better approach to go about to create

I am worried in Class Z, since methods C & D are not
be any unforeseen effects during my programing later

One More Thought I have Got

Shall I Use the factory Design Pattern to implement the Same Objects?


问:
background-image property can't be changed by jquery
Like the title say, for some reason my function don't want to perform a change to the background-image property. I also made the function change the background-color to check if it is working and it does. So it seems that the problem is not in the syntax.

function feedSlide () {
  var x = [
    '../img/feed1.png',
    '../img/feed2.png',
    '../img/feed3.png',
    '../img/feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      $('#feedback').css({"background-image" : "url(" + x[z] + ")"});
      $('#feedback').css({"background-color" : y[z] });
    }; }(i), 1000*i);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#feedback {
  width: 400px;
  text-align: justify;
  padding: 10px;
  height: 200px;
}</code>```

```

I'm on that for hours now and everything seems to be changeable but the background-image. Any information is very welcome.

答:
After every attempt to solve this problem failed, I found the solution in a CSS animation.</p>

```<code> #feedback {
  height: 110px;
  width: 380px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  animation-name: feedSlide;
  animation-duration: 40s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
 }

@keyframes feedSlide {
 0.00% {background-image: url(../img/feed1.png); opacity: 0;}
 3% {opacity: 1;}
 22% {opacity: 1;}
 25% {background-image: url(../img/feed1.png); opacity: 0;}
 26% {background-image: url(../img/feed2.png); opacity: 0;}
 29% {opacity: 1;}
 47% {opacity: 1;}
 50% {background-image: url(../img/feed2.png); opacity: 0;}
 51% {background-image: url(../img/feed3.png); opacity: 0;}
 54% {opacity: 1;}
 72% {opacity: 1;}
 75% {background-image: url(../img/feed3.png); opacity: 0;}
 76% {background-image: url(../img/feed4.png); opacity: 0;}
 79% {opacity: 1;}
 97% {opacity: 1;}
 100% {background-image: url(../img/feed4.png); opacity: 0;}
}
</code>```

Body:
Like the title say, for some reason my function don't want to perform a change to the background-image property. I also made the function change the background-color to check if it is working and it does. So it seems that the problem is not in the syntax.

function feedSlide () {
  var x = [
    '../img/feed1.png',
    '../img/feed2.png',
    '../img/feed3.png',
    '../img/feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      $('#feedback').css({"background-image" : "url(" + x[z] + ")"});
      $('#feedback').css({"background-color" : y[z] });
    }; }(i), 1000*i);
  }
}

#feedback {
  width: 400px;
  text-align: justify;
  padding: 10px;
  height: 200px;
}

I'm on that for hours now and everything seems to be changeable but the background-image. Any information is very welcome.

Body:
After every attempt to solve this problem failed, I found the solution in a CSS animation.

 #feedback {
  height: 110px;
  width: 380px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  animation-name: feedSlide;
  animation-duration: 40s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
 }

@keyframes feedSlide {
 0.00% {background-image: url(../img/feed1.png); opacity: 0;}
 3% {opacity: 1;}
 22% {opacity: 1;}
 25% {background-image: url(../img/feed1.png); opacity: 0;}
 26% {background-image: url(../img/feed2.png); opacity: 0;}
 29% {opacity: 1;}
 47% {opacity: 1;}
 50% {background-image: url(../img/feed2.png); opacity: 0;}
 51% {background-image: url(../img/feed3.png); opacity: 0;}
 54% {opacity: 1;}
 72% {opacity: 1;}
 75% {background-image: url(../img/feed3.png); opacity: 0;}
 76% {background-image: url(../img/feed4.png); opacity: 0;}
 79% {opacity: 1;}
 97% {opacity: 1;}
 100% {background-image: url(../img/feed4.png); opacity: 0;}
}


问:
Count years of increasing profits
I want to count how many years a company has increased the profit from now. So if the previous year had lower profits than this year it counts as 1 and goes one year back in past to count until there is one years profit higher than the year after that. So it must be a ongoing trend from this year (2017) so that it counts the years.

(Years of increases should be 5 not 4, sorry!)

In the picture it has to count until 2011 because there was a year(2012) without increasing profits relative to last year(2011).

So maybe its even possible with a Excel Function. Otherwise VBA is probably the way to do this.

EDIT: Is it possible to count years of steady profits, too? Like if 2015 = 5 and 2016 = 5 then this should not stop streak.

答:
You can use the below array formula, if you are looking for number of time the profit is increased starting from current year. Enter the below formula and press Shift+Control+Enter. The last -1 is to align this with your answer. If you want 5 instead of four, you can remove that -1.

```<code>=COUNT(B2:H2)-MAX(IF(C2:I2<B2:H2,COLUMN(C2:I2)-COLUMN(B2)))
</code>```

by using this, with only one formula you can achieve what you want.

Title: Count years of increasing profits

Body:
You can use the below array formula, if you are looking for number of time the profit is increased starting from current year. Enter the below formula and press Shift+Control+Enter. The last -1 is to align this with your answer. If you want 5 instead of four, you can remove that -1.

=COUNT(B2:H2)-MAX(IF(C2:I2<B2:H2,COLUMN(C2:I2)-COLUMN(B2)))

by using this, with only one formula you can achieve what you want.


问:
Can't install csv module
I am a mac user and today I tried installing csv today and here is command
pip install csv.But unfortunately it returned the following error

Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
```

I have Python version 2.7.13 and I have installed other dependencies like scikit-learn,numpy and matplotlib, but for some reason I can't install csv.

答:
csv is part of python's standard library so you don't need to install it with pip.  Just use it with:

```<code>import csv
</code>```

Title: Can't install csv module

Body:
I am a mac user and today I tried installing csv today and here is command
pip install csv.But unfortunately it returned the following error

Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv

I have Python version 2.7.13 and I have installed other dependencies like scikit-learn,numpy and matplotlib, but for some reason I can't install csv.

Body:
csv is part of python's standard library so you don't need to install it with pip.  Just use it with:

import csv


问:
Can't create virtual device on Android Studio on Windows
I am new on Android Studio and don't know much. I am using on Windows. I am unable to create virtual device through AVD manager, every time I create it gives this message:

An error occurred while creating the AVD. See idea.log for details.

答:
you always need virtualization for android emulator I guess
without virtualization how will you create an abstract environment to support android kernel and its features?

emulator details


问:
problem with conditional switch
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

```<code><?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>
</code>```

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

答:
Others have mentioned why this is occurring (misuse of a conditional in the case statement), but they haven't offered alternatives. Switch is meant to cover specific arguments like { 0, 1, 2, 3..100, 101 } etc. It separates out specific arguments or ranges rather than performing a simple if/else (as you've used it). You can rewrite your arguments to pull it off though:

```<code>switch ($totaltime) {

    case (0):
        echo "That was fast!";
        break;

    case (1..PHP_INT_MAX):
        echo "Not fast!";
        break;

    default:
        echo "That's slooooow";
        break;
}
</code>```

Here the .. allows a range to be covered, so anything from 1 to integer max is covered by that case. The 0 is handled explicitly and all others (re: < 0) are covered by the default case.

Title: problem with conditional switch

Body:
The example below is an extráct from http://php.net/manual/de/control-structures.switch.php

<?php
$totaltime = 0;
switch ($totaltime) {

    case ($totaltime < 1):
        echo "That was fast!";
        break;

    case ($totaltime > 1):
        echo "Not fast!";
        break;

    case ($totaltime > 10):
        echo "That's slooooow";
        break;
}

?>

I expected the result as "That was fast." But actual result is "Not fast!". It would be great if some one can explain me why?

But if i add another case, case 0: echo "That was super fast!". Then it is echoing properly. i.e "That was super fast!". Please help me how to use conditional switch statement.

EDIT:-

Thanks all for your responses. I am able to overcome the above problem by modifyong switch($totaltime) to switch(1)

Body:
Others have mentioned why this is occurring (misuse of a conditional in the case statement), but they haven't offered alternatives. Switch is meant to cover specific arguments like { 0, 1, 2, 3..100, 101 } etc. It separates out specific arguments or ranges rather than performing a simple if/else (as you've used it). You can rewrite your arguments to pull it off though:

switch ($totaltime) {

    case (0):
        echo "That was fast!";
        break;

    case (1..PHP_INT_MAX):
        echo "Not fast!";
        break;

    default:
        echo "That's slooooow";
        break;
}

Here the .. allows a range to be covered, so anything from 1 to integer max is covered by that case. The 0 is handled explicitly and all others (re: < 0) are covered by the default case.


问:
Is it possible to 301 redirect a domain but still send 404 headers when appropriate?
I am using RewriteCond %{HTTP_HOST} ^(www\.)?oldsite\.com$ [NC]
RewriteRule ^.+$ http://newsite.com%{REQUEST_URI} [L,R=301] to redirect users from one site to another. The root exception in this instance is deliberate; that is, I want visitors to oldsite.com to not be redirected, but visitors to oldsite.com/anypage to be redirected to newsite.com/anypage.

However, when someone manually types in oldsite.com/qwerty (a non-existing page), they (and presumably any search engine) get a 301 redirect and not a 404 error. Is there a rule-based way to avoid this behaviour or do I need to change my .htaccess so that there are individual 301 redirects listed (so that anything else will then give the desired 404 result)?

答:
For simplicity I will refer to "Google" here, but it applies to any search engine.

This is basically a non-issue. The 301 redirects are mostly there to keep your Google ranking from the old domain on the new domain and keep bookmarks valid. If a page existed on the old domain, it should still exist on the new domain.

If someone types a non-existing page on the old domain, the user will see the 404 message on the new domain, but that is okay. Google does not crawl that url. In fact any automated crawler should never encounter that url, so semantics about getting a 301 redirect before a 404 status code does not really apply.

There are two things to look out for:

You had a page on the old domain that now exists under a different name on the new domain. You should add a manual exception for this:

```<code>RewriteRule ^mypage$ https://newsite.com/new-page-with-something-fancy [R=301,L]
</code>```

You had a page on the old domain that no longer exists on the new domain. You should manually add an exception that returns the "Gone" status code

```<code>RewriteRule ^i-no-longer-exist$ - [G,L]
</code>```

There does not really exist a way of checking the status code of the redirected page, unless you go into the land of rewriting to a script that uses something like curl to check the other site, or use something like a proxy. Both are awfully inefficient and hurt your site's ranking more than it could ever gain.

Body:
For simplicity I will refer to "Google" here, but it applies to any search engine.

This is basically a non-issue. The 301 redirects are mostly there to keep your Google ranking from the old domain on the new domain and keep bookmarks valid. If a page existed on the old domain, it should still exist on the new domain.

If someone types a non-existing page on the old domain, the user will see the 404 message on the new domain, but that is okay. Google does not crawl that url. In fact any automated crawler should never encounter that url, so semantics about getting a 301 redirect before a 404 status code does not really apply.

There are two things to look out for:

You had a page on the old domain that now exists under a different name on the new domain. You should add a manual exception for this:

RewriteRule ^mypage$ https://newsite.com/new-page-with-something-fancy [R=301,L]

You had a page on the old domain that no longer exists on the new domain. You should manually add an exception that returns the "Gone" status code

RewriteRule ^i-no-longer-exist$ - [G,L]

There does not really exist a way of checking the status code of the redirected page, unless you go into the land of rewriting to a script that uses something like curl to check the other site, or use something like a proxy. Both are awfully inefficient and hurt your site's ranking more than it could ever gain.


问:
Exporting inline code to html in org-mode
What I want in org-mode is like the inline code block syntax in Markdown language X <- 3. I googled and attempted (reference):

```<code>src_R{X <- 3}
</code>```

inline in org-mode, but exporting to html (with C-cC-eh) did not show the inline code. Other code block like #+begin_src R stuff works fine, but anyhow there is a warning message while exporting:

```<code>htmlize.el 1.34 or later is needed for source code formatting [14 times]
</code>```

Could that be the reason ?

Update:

Thanks for @LeVieuxGildas opinion, I installed and loaded the latest htmlize.el version 1.43 now and did not get any error message when exporting. But still exporting html can not show inline code part.

system: OS X 10.8.2 ; emacs mac port https://github.com/railwaycat/emacs-mac-port ; built-in org-mode

答:
Fast and dirty solution is to modify the header arguments in your previous inline code.

```<code>src_R[:exports code]{X <- 3}
</code>```

In my opinion, inline code is much better than =code= or ~code~ because it can be syntax highlighted if you output your org file as Latex file.

Body:
What I want in org-mode is like the inline code block syntax in Markdown language X <- 3. I googled and attempted (reference):

src_R{X <- 3}

inline in org-mode, but exporting to html (with C-cC-eh) did not show the inline code. Other code block like #+begin_src R stuff works fine, but anyhow there is a warning message while exporting:

htmlize.el 1.34 or later is needed for source code formatting [14 times]

Could that be the reason ?

Update:

Thanks for @LeVieuxGildas opinion, I installed and loaded the latest htmlize.el version 1.43 now and did not get any error message when exporting. But still exporting html can not show inline code part.

system: OS X 10.8.2 ; emacs mac port https://github.com/railwaycat/emacs-mac-port ; built-in org-mode

Body:
Fast and dirty solution is to modify the header arguments in your previous inline code.

src_R[:exports code]{X <- 3}

In my opinion, inline code is much better than =code= or ~code~ because it can be syntax highlighted if you output your org file as Latex file.


问:
Wrong coverage calculation in sonarqube 6.2 on Gradle multi module project
I'm currently using a gradle multi module java project with good coverage and sonarqube 6.2 with sonarJava plugin 4.10.0.1026. I'm using Gradle 4.0.1, sonarqube plugin 2.5 and jacoco 0.7.9! The code is java 8.

Because of API driven development the API tests are written as abstract tests in the API projects and called from the implementation projects providing the constructors for the tests.

When analyzing the projekt on the sonarqube server the coverage for the implementation projects is measured correctly but the API projects included in the tests of the IMPL projects are on 0.0% coverage. The coverage results for these projects are ignored.

When simply using the jacoco plugin I was able to get the same behaviour. After doing some research I found a solution to get proper jacoco reports:

```<code>task codeCoverageReport(type: JacocoReport) {
  description "Creates a unified JaCoCo test report for the project."

  // Gather execution data from all subprojects
  // (change this if you e.g. want to calculate unit test/integration test coverage separately)
  executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")

  // Add all relevant sourcesets from the subprojects
  subprojects.each {
    sourceSets it.sourceSets.main
  }

  reports {
    xml.enabled true
    html.enabled true
    html.destination file("${buildDir}/reports/jacoco")
    csv.enabled false
  }
}

// always run the tests before generating the report
codeCoverageReport.dependsOn {
  subprojects*.test
}
</code>```

My current result is the following:

JaCoCo:

JaCoCo (codeCoverageReport-Task)

73% Instruction Coverage

91% Branch Coverage

Sonar

43.1% Line Coverage (only ~30% lines considered in calculation!)

82.1% Condition Coverage (only ~20% conditions covered!)

So the coverage results in sonar are not usable. I have read an post announcing the "sonar.jacoco.reportPaths"-parameter starting with sonar 6.2 and I think java-analyzer 4.4 or sth. like that. When adding this parameter to my gradle build script, the script does not compile anymore. When adding the jacoco .exec files to sonar via sonar project administration nothing changes.

It would be great if there would be a way to manage sonar to calculate the correct coverage.

答:
If your tests are in a different project to the sources that you want coverage reports on then you'll need to set additionalSourceDirs and additionalClassDirs. Eg:

```<code>evaluationDependsOn ':foo'
task codeCoverageReport(type: JacocoReport) {
    additionalSourceDirs.add project(':foo').sourceSets.main.java.sourceDirectories
    additionalClassDirs.add project(':foo').sourceSets.main.output.classesDirs
    // etc
}
</code>```

Body:
I'm currently using a gradle multi module java project with good coverage and sonarqube 6.2 with sonarJava plugin 4.10.0.1026. I'm using Gradle 4.0.1, sonarqube plugin 2.5 and jacoco 0.7.9! The code is java 8.

Because of API driven development the API tests are written as abstract tests in the API projects and called from the implementation projects providing the constructors for the tests.

When analyzing the projekt on the sonarqube server the coverage for the implementation projects is measured correctly but the API projects included in the tests of the IMPL projects are on 0.0% coverage. The coverage results for these projects are ignored.

When simply using the jacoco plugin I was able to get the same behaviour. After doing some research I found a solution to get proper jacoco reports:

task codeCoverageReport(type: JacocoReport) {
  description "Creates a unified JaCoCo test report for the project."

  // Gather execution data from all subprojects
  // (change this if you e.g. want to calculate unit test/integration test coverage separately)
  executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")

  // Add all relevant sourcesets from the subprojects
  subprojects.each {
    sourceSets it.sourceSets.main
  }

  reports {
    xml.enabled true
    html.enabled true
    html.destination file("${buildDir}/reports/jacoco")
    csv.enabled false
  }
}

// always run the tests before generating the report
codeCoverageReport.dependsOn {
  subprojects*.test
}

My current result is the following:

JaCoCo:

JaCoCo (codeCoverageReport-Task)

73% Instruction Coverage

91% Branch Coverage

Sonar

43.1% Line Coverage (only ~30% lines considered in calculation!)

82.1% Condition Coverage (only ~20% conditions covered!)

So the coverage results in sonar are not usable. I have read an post announcing the "sonar.jacoco.reportPaths"-parameter starting with sonar 6.2 and I think java-analyzer 4.4 or sth. like that. When adding this parameter to my gradle build script, the script does not compile anymore. When adding the jacoco .exec files to sonar via sonar project administration nothing changes.

It would be great if there would be a way to manage sonar to calculate the correct coverage.

Body:
If your tests are in a different project to the sources that you want coverage reports on then you'll need to set additionalSourceDirs and additionalClassDirs. Eg:

evaluationDependsOn ':foo'
task codeCoverageReport(type: JacocoReport) {
    additionalSourceDirs.add project(':foo').sourceSets.main.java.sourceDirectories
    additionalClassDirs.add project(':foo').sourceSets.main.output.classesDirs
    // etc
}


问:
Ionic 2: ReferenceError: webpackJsonp is not defined
I'm new to Ionic. I have started project with super template. But when I try to run the app in browser. It throws an error saying:

```<code>ReferenceError: webpackJsonp is not defined
    at http://localhost:8100/build/main.js:1:1
</code>```

I have tried putting vendor.js in index.html but that has not worked.

Here's the index.html file. I have removed vendor.js as it didn't work.

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>

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

答:
Literally just went through the same thing as you are. I added the vendor.js script BEFORE the main.js in /src/index.html - now it runs locally.

```<code>  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <script src="build/vendor.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>
</code>```

Body:
I'm new to Ionic. I have started project with super template. But when I try to run the app in browser. It throws an error saying:

ReferenceError: webpackJsonp is not defined
    at http://localhost:8100/build/main.js:1:1

I have tried putting vendor.js in index.html but that has not worked.

Here's the index.html file. I have removed vendor.js as it didn't work.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <link href="build/main.css" rel="stylesheet">

  <ion-app></ion-app>

Body:
Literally just went through the same thing as you are. I added the vendor.js script BEFORE the main.js in /src/index.html - now it runs locally.

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <script src="build/vendor.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>


问:
count element on the basis of matching id javascript
```<code>var data = [{
    id: '1',
    status: 'pending'
}, {
    id: '2',
    status: 'delivered'
}, {
    id: '2',
    status: 'pending'
}, {
    id: '1',
    status: 'shipped'
}, {
    id: '1',
    status: 'pending'
}, {
    id: '2',
    status: 'delivered'
}, {
    id: '2',
    status: 'shipped'
}]

output: [{
    id: 1,
    order: {
        pending: 2,
        shipped: 1
    },
    id: 2,
    order: {
        pending: 1,
        delivered: 2,
        shipped: 1
    }
}]
</code>```

答:
One way of doing this using Array reduce & find.</p>

```<code>var ret = data.reduce(function(o, v) {
  //change id to Number
  var idNum = Number(v.id);

  var ele = o.find(function(e, i) {
    return idNum === e.id;
  });
  if (!ele) {
    //ID is not there in our output, let's create it
    ele = {
      id: idNum,
      order: {}
    };
    o.push(ele);
  }
  //update order status
  //if it's empty start with zero and increase it
  ele.order[v.status] = (ele.order[v.status] || 0) + 1;
  return o;
}, []);
console.log(JSON.stringify(ret));
</code>```

Body:
One way of doing this using Array reduce & find.

var ret = data.reduce(function(o, v) {
  //change id to Number
  var idNum = Number(v.id);

  var ele = o.find(function(e, i) {
    return idNum === e.id;
  });
  if (!ele) {
    //ID is not there in our output, let's create it
    ele = {
      id: idNum,
      order: {}
    };
    o.push(ele);
  }
  //update order status
  //if it's empty start with zero and increase it
  ele.order[v.status] = (ele.order[v.status] || 0) + 1;
  return o;
}, []);
console.log(JSON.stringify(ret));


问:
Undeclared object variable showing undefined instead of ReferenceError
```<code>var obj = {a : 2};
console.log(obj.b); //prints undefined
console.log(b);      //ReferenceError
</code>```

Here both obj.b and  b are not defined. Can anyone explain the reason behind the different outputs?

答: obj.b is undefined cause he don't exist in your object and var b does not exist too.

Body:
var obj = {a : 2};
console.log(obj.b); //prints undefined
console.log(b);      //ReferenceError

Here both obj.b and  b are not defined. Can anyone explain the reason behind the different outputs?


问:
How to store extensible metadata in an ORM-friendly way in .NET?
It seems I am unable to find any answers to "how to use EAV approach with ORM tools" question, so I'll try my luck here.

Suppose I have an Entities Table:

```<code>ID -> int
Name -> nvarchar(50)
</code>```

An Images Table:

```<code>EntityID -> int
Width -> int
Height -> int
</code>```

And a Songs Table:

```<code>EntityID -> int
Duration -> decimal(12,3)
</code>```

I need to add extensible metadata to the entities (unknown key-value pairs with type info), so that I'm able to issue queries like:

Find me all the Songs that have a Duration longer than 3 minutes, with a Name starting with 'The', with metadata fulfilling these criteria:

HasGuitarSolo is set to true

GuitarSoloDuration is greater than 30 seconds

And sort the results on GuitarSoloDuration in descending order.

I don't want to create HasGuitarSolo, GuitarSoloDuration, etc. columns in the database, Ideally I would like to store them in an EAV-like schema, or an alternative schema that doesn't require a knowledge of the keys up front.

答:
You can store the data in SQL Server and using LINQ to SQL ORM.

Updated:
You can also take a look at NH. LLBL, this is a ORM/Generator, your entities will have a lot of code pre-generated, and it starts from the database.

Body:
It seems I am unable to find any answers to "how to use EAV approach with ORM tools" question, so I'll try my luck here.

Suppose I have an Entities Table:

ID -> int
Name -> nvarchar(50)

An Images Table:

EntityID -> int
Width -> int
Height -> int

And a Songs Table:

EntityID -> int
Duration -> decimal(12,3)

I need to add extensible metadata to the entities (unknown key-value pairs with type info), so that I'm able to issue queries like:

Find me all the Songs that have a Duration longer than 3 minutes, with a Name starting with 'The', with metadata fulfilling these criteria:

HasGuitarSolo is set to true

GuitarSoloDuration is greater than 30 seconds

And sort the results on GuitarSoloDuration in descending order.

I don't want to create HasGuitarSolo, GuitarSoloDuration, etc. columns in the database, Ideally I would like to store them in an EAV-like schema, or an alternative schema that doesn't require a knowledge of the keys up front.


问:
i want that when the give input in employee_address is Banglore and salary is more than 25000,i get all the details of employee
I have written this code but when i am giving input Banglore and 26000 it is not returning desired condition.

I want to get all employee details when the employee address is Banglore and salary is more than 25000.

```<code>import java.util.Scanner;

public class ContactManager {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner s=new Scanner(System.in);

        int employee_id;
        String employee_name;
        String address;
        int mobile;
        int salary;
        String q;

        System.out.println("empolyee_id:");
        employee_id=s.nextInt();

        System.out.println("employee_name:");
        employee_name=s.next();

        System.out.println("mobile:");
        mobile=s.nextInt();

        System.out.println("address:");
        address=s.next();

        System.out.println("salary:");
        salary=s.nextInt();

        q = "Banglore";

        if(address==q && salary > 25000) {
            System.out.println(employee_name);
            System.out.println(employee_id);
            System.out.println(address);
            System.out.println(mobile);
            System.out.println(salary);
        } else {
            System.out.println("Sorry");
        }
    }
}
</code>```

答:
You must compare strings using equals() method.

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Variable String address and String q = "Banglore" are not the same objects, so address == q returns false.

Replace if(address==q && salary>25000) on if(q.equals(address) && salary>25000), and it will work perfectly.

Body:
I have written this code but when i am giving input Banglore and 26000 it is not returning desired condition.

I want to get all employee details when the employee address is Banglore and salary is more than 25000.

import java.util.Scanner;

public class ContactManager {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner s=new Scanner(System.in);

        int employee_id;
        String employee_name;
        String address;
        int mobile;
        int salary;
        String q;

        System.out.println("empolyee_id:");
        employee_id=s.nextInt();

        System.out.println("employee_name:");
        employee_name=s.next();

        System.out.println("mobile:");
        mobile=s.nextInt();

        System.out.println("address:");
        address=s.next();

        System.out.println("salary:");
        salary=s.nextInt();

        q = "Banglore";

        if(address==q && salary > 25000) {
            System.out.println(employee_name);
            System.out.println(employee_id);
            System.out.println(address);
            System.out.println(mobile);
            System.out.println(salary);
        } else {
            System.out.println("Sorry");
        }
    }
}


问:
gdb get different structure size when command run twice
I have a program run in such a way:

process A  ---write-->global structure---read by--->process B

whereas process B can't get what A once written

Using GDB, I found something weird like that:

Can any one explain why this happen?

答:
Can any one explain why this happen?

As you've already discovered, this is the result of violating the one definition rule -- you have the same struct defined different way in different parts of your program.

The specific GDB behavior is explained like so: GDB does not eagerly parse debug info until it needs to (it does so lazily).

When you execute the first print sizeof(struct rte_eth_stats), GDB finds the first definition of rte_eth_stats (it may already have loaded this definition earlier depending on which commands you have executed up to that point).

When you execute the second print sizeof(pstat_dpdk[2]), GDB looks up the definition of pstat_dpdk, and in doing so discovers the second definition of rte_eth_stats, and updates its notion of what that struct is.

When you execute the third print, GDB uses the updated state of rte_eth_stats, and prints its "new" size.

GDB could have printed a warning when replacing the first definition of rte_eth_stats with the second if the two definitions have different size.

However, it is not uncommon to have such differing definitions (e.g. where clients of a library only know about first (say) 3 members of struct, but the library itself knows about additional (private) members), and printing a warning in that case would be annoying.


答:
The first is a missing property, the second is a missing variable.

See also the difference here:

console.log(window.b);
console.log(b);  ```

Title: Undeclared object variable showing undefined instead of ReferenceError


问:
How to obtain the first letter in a Bash variable?
I have a Bash variable, $word, which is sometimes a word or sentence, e.g.:

```<code>word="tiger"
</code>```

Or:

```<code>word="This is a sentence."
</code>```

How can I make a new Bash variable which is equal to only the first letter found in the variable? E.g., the above would be:

```<code>echo $firstletter
t
</code>```

Or:

```<code>echo $firstletter
T
</code>```

答:
A portable way to do it is to use parameter expansion (which is a POSIX feature):</p>

```<code>$ word='tiger'
$ echo "${word%"${word#?}"}"
t
</code>```

Body:
I have a Bash variable, $word, which is sometimes a word or sentence, e.g.:

word="tiger"

Or:

word="This is a sentence."

How can I make a new Bash variable which is equal to only the first letter found in the variable? E.g., the above would be:

echo $firstletter
t

Or:

echo $firstletter
T

Body:
A portable way to do it is to use parameter expansion (which is a POSIX feature):

$ word='tiger'
$ echo "${word%"${word#?}"}"
t


问:
Graph algorithm/approach for finding two nodes that disrupts the graph the most
I'm trying to develop a way of retrieving a measure of disruptiveness when removing two nodes from a graph. So far I'm performing a collection of algorithms like multiple measures of centralities, degrees, pagerank etc.
Its obvious that it can be done by actually removing two nodes and then analyzing the resulting graph (or collection of graphs), but this is also time-consuming when there is O(N^2) combinations of two nodes.
Any help to steer me in the right direction would be appreciated.</p>

答:
I think what you are looking for is the KPP-Neg problem (Key Players Problem).

It is defined in terms of the extent to which the network depends on its key players to maintain its cohesiveness. It is a “negative” problem because it measures the amount of reduction in the cohesiveness of the network that would occur if the nodes were not present.

(As opposed to the KPP-Pos problem where you are looking for a set of network nodes that are optimally positioned to quickly diffuse information, attitudes, behaviors or goods).

Both KPP problems were defined in The key player problem [Borgatti, 2003] and Identifying sets of key players in a network [Borgatti, 2006]. See also "Key players" - a discussion by Yves Zenou here.

Many more approaches were suggested since these papers were presented. Just google Key Players Social Networks.


问:
insert a new element into array key in php
I have a array like this-

```<code>$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
</code>```

I want to add a new element in the 't' key of the array. The result will be like the following:

```<code>$array = array('o' => 'one', 't' => 'three','six', 'f' => 'four');
</code>```

How can i do this?

答:
You can't do it like that, For your target You have to use 2 dimension array, from other words array of array,

```<code>$array['t']=array('three','six');
</code>```

and you can see the results like this,

```<code>Array ( [o] => one [t] => Array ( [0] => three [1] => six ) [f] => four );
</code>```

You can easily access anything inside array using keys, if you want to access key "t",

```<code>$array['t'][0] = three and $array['t'][1] = six
</code>```

This is the right way to solve your question.

Body:
I have a array like this-

$array = array('o' => 'one', 't' => 'three', 'f' => 'four');

I want to add a new element in the 't' key of the array. The result will be like the following:

$array = array('o' => 'one', 't' => 'three','six', 'f' => 'four');

How can i do this?

Body:
You can't do it like that, For your target You have to use 2 dimension array, from other words array of array,

$array['t']=array('three','six');

and you can see the results like this,

Array ( [o] => one [t] => Array ( [0] => three [1] => six ) [f] => four );

You can easily access anything inside array using keys, if you want to access key "t",

$array['t'][0] = three and $array['t'][1] = six

This is the right way to solve your question.