问:
awk preventing white spaces
I have the following code:

```<code>#!/bin/bash

FILE=source.txt
RES=res.txt

VAR1=match

rm -f $RES
sudo cat $FILE | while IFS= read LINE; do
    if [[ ! $(echo "$LINE" | grep $VAR1 ) ]]; then
        echo -e "$LINE" >> $RES
    else
                NEW_LINE=$(awk '{gsub("'"${VAR1}"'", ""); print}' <<< $LINE)
                echo -e "$NEW_LINE" | xargs >> $RES
    fi
done
</code>```

source.txt:

```<code>rob     math
        science match something
  something match
hary    math linux
</code>```

after executing the code, I would like to receive the following:

```<code>rob     math
        science something
  something
hary    math linux
</code>```

But it removes the white spaces in the both affected lines. So I end up with the following result:

```<code>rob     math
science something
something
hary    math linux
</code>```

Could you please help.

答:
All your code can be summed up to this line in Awk, unless you are not sharing the whole requirement,

```<code>awk '{gsub("match","",$0)}1' source.txt
rob     math
        science  something
  something
hary
</code>```

I would make the match configurable from a bash variable as

```<code>myVAR="match"
awk -v pat="${myVAR}" '{gsub(pat,"",$0)}1' source.txt
</code>```

The -v flag allows you to import bash variables to the context of Awk. To complete your answer to write to a new file, I would do

```<code>awk -v pat="${myVAR}" '{gsub(pat,"",$0)}1' source.txt > res.txt
</code>```

To answer your original attempt's  claim of eating up white-spaces, couple of points to be noted, the line

```<code>awk '{gsub("'"${VAR1}"'", ""); print}' <<< $LINE
</code>```

is wrong if you want to preserve the spaces in each line you read, it should be double quoted as

```<code>awk '{gsub("'"${VAR1}"'", ""); print}' <<<"$LINE"
</code>```

Even with that change, you have an xargs before writing to the file ( Not sure of the reason) but you have to know that it swallows whitespaces from the input stream. Removing it should solve your problem.

Just assuming you want to do such a trivial script for a such a simple use-case, the syntactically right approach (using your logic) would be,

```<code>while IFS= read -r line; do
    if grep -q "$VAR1" <<<"$line" ; then
        printf "%s\n" "$line" >> "$RES"
    else
        newLine=$(awk -v pat="${VAR1}" '{gsub(pat, "",$0); }1' <<<"$line")
        printf "%s\n" "$newLine" >> "$RES"
    fi
done <"$FILE"
</code>```

Title: awk preventing white spaces

Body:
I have the following code:

#!/bin/bash

FILE=source.txt
RES=res.txt

VAR1=match

rm -f $RES
sudo cat $FILE | while IFS= read LINE; do
    if [[ ! $(echo "$LINE" | grep $VAR1 ) ]]; then
        echo -e "$LINE" >> $RES
    else
                NEW_LINE=$(awk '{gsub("'"${VAR1}"'", ""); print}' <<< $LINE)
                echo -e "$NEW_LINE" | xargs >> $RES
    fi
done

source.txt:

rob     math
        science match something
  something match
hary    math linux

after executing the code, I would like to receive the following:

rob     math
        science something
  something
hary    math linux

But it removes the white spaces in the both affected lines. So I end up with the following result:

rob     math
science something
something
hary    math linux

Could you please help.

Body:
All your code can be summed up to this line in Awk, unless you are not sharing the whole requirement,

awk '{gsub("match","",$0)}1' source.txt
rob     math
        science  something
  something
hary

I would make the match configurable from a bash variable as

myVAR="match"
awk -v pat="${myVAR}" '{gsub(pat,"",$0)}1' source.txt

The -v flag allows you to import bash variables to the context of Awk. To complete your answer to write to a new file, I would do

awk -v pat="${myVAR}" '{gsub(pat,"",$0)}1' source.txt > res.txt

To answer your original attempt's  claim of eating up white-spaces, couple of points to be noted, the line

awk '{gsub("'"${VAR1}"'", ""); print}' <<< $LINE

is wrong if you want to preserve the spaces in each line you read, it should be double quoted as

awk '{gsub("'"${VAR1}"'", ""); print}' <<<"$LINE"

Even with that change, you have an xargs before writing to the file ( Not sure of the reason) but you have to know that it swallows whitespaces from the input stream. Removing it should solve your problem.

Just assuming you want to do such a trivial script for a such a simple use-case, the syntactically right approach (using your logic) would be,

while IFS= read -r line; do
    if grep -q "$VAR1" <<<"$line" ; then
        printf "%s\n" "$line" >> "$RES"
    else
        newLine=$(awk -v pat="${VAR1}" '{gsub(pat, "",$0); }1' <<<"$line")
        printf "%s\n" "$newLine" >> "$RES"
    fi
done <"$FILE"


来源: stackexchange

问:
Strange MySQL IN behavior
OK this is not a question 100%.
I got a big headache today with this and just wanted to know if anyone else had this problem.

Let's say we have a table named "products":

```<code>ID | product_code
4  | 5201279007942_AKYRO
</code>```

If we run this query:

```<code>SELECT *
FROM `products`
WHERE product_code
IN ( '5201279007942' )
</code>```

Mysql will return 0 rows as expected.

If we run this query:

```<code>SELECT *
FROM `products`
WHERE product_code
IN ( 5201279007942 )
</code>```

Mysql will return the above row.

So the "IN" query will act as a "LIKE" query.

Is this behavior normal? Am i missing something here?

ContentLicense: CC BY-SA 3.0

Title: Strange MySQL IN behavior

Body:
OK this is not a question 100%.
I got a big headache today with this and just wanted to know if anyone else had this problem.

Let's say we have a table named "products":

ID | product_code
4  | 5201279007942_AKYRO

If we run this query:

SELECT *
FROM `products`
WHERE product_code
IN ( '5201279007942' )

Mysql will return 0 rows as expected.

If we run this query:

SELECT *
FROM `products`
WHERE product_code
IN ( 5201279007942 )

Mysql will return the above row.

So the "IN" query will act as a "LIKE" query.

Is this behavior normal? Am i missing something here?

Body:
see the output. There is a difference between string ant int

SELECT
    '5201279007942_AKYRO' IN ('5201279007942') AS string_with_string
    , '5201279007942_AKYRO' IN (5201279007942) AS string_with_num
    , CAST( '5201279007942_AKYRO' AS UNSIGNED) IN (5201279007942) AS cast_to_int_with_num;

sample

mysql> SELECT
    ->     '5201279007942_AKYRO' IN ('5201279007942') AS string_with_string
    ->     , '5201279007942_AKYRO' IN (5201279007942) AS string_with_num
    ->     , CAST( '5201279007942_AKYRO' AS UNSIGNED) IN (5201279007942) AS cast_to_int_with_num;
+--------------------+-----------------+----------------------+
| string_with_string | string_with_num | cast_to_int_with_num |
+--------------------+-----------------+----------------------+
|                  0 |               1 |                    1 |
+--------------------+-----------------+----------------------+
1 row in set, 2 warnings (0,00 sec)

mysql>


问:
Set a default schema for Hibernate via JNDI reference
I use Spring 4, Hibernate 4 and WebSphere 8.5.7. Having such a class:

```<code>@Entity
@Table(name = "APPLICATION", schema = "NEW_SCHEMA")
public class Application {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_NEW")
    @SequenceGenerator(name = "SEQUENCE_NEW", schema = "NEW_SCHEMA", sequenceName = "SEQUENCE_NEW", allocationSize = 1, initialValue = 1)
    @Column(name = "ID")
    @Getter @Setter private Long id;
</code>```

I want to have an ability to change a schema in the @Table signature via JNDI name. I expect to get something like this:

```<code>@Table(name = "APPLICATION", schema = "${schema.jndi}")
</code>```

Assuming that ${schema.jndi} will be provided by Websphere.

Another words, in business context, the task looks as follows. I need to exclude any mention of the schema in a whole project code (Java, xml, props). And make it possible changing a schema directly from WebShpere.

What is the simplest way to implement a solution?

Any suggestion will be greatly appreciated.

答:
If you want to configure a schema for the entire application (for every entity) , you can do that in your Hibernate configuraton file (typically WAS will have a reference to this config file)</p>

```<code><property name="hibernate.default_schema">myschema</property>
</code>```

Body:
I use Spring 4, Hibernate 4 and WebSphere 8.5.7. Having such a class:

@Entity
@Table(name = "APPLICATION", schema = "NEW_SCHEMA")
public class Application {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_NEW")
    @SequenceGenerator(name = "SEQUENCE_NEW", schema = "NEW_SCHEMA", sequenceName = "SEQUENCE_NEW", allocationSize = 1, initialValue = 1)
    @Column(name = "ID")
    @Getter @Setter private Long id;

I want to have an ability to change a schema in the @Table signature via JNDI name. I expect to get something like this:

@Table(name = "APPLICATION", schema = "${schema.jndi}")

Assuming that ${schema.jndi} will be provided by Websphere.

Another words, in business context, the task looks as follows. I need to exclude any mention of the schema in a whole project code (Java, xml, props). And make it possible changing a schema directly from WebShpere.

What is the simplest way to implement a solution?

Any suggestion will be greatly appreciated.

Body:
If you want to configure a schema for the entire application (for every entity) , you can do that in your Hibernate configuraton file (typically WAS will have a reference to this config file)

<property name="hibernate.default_schema">myschema</property>


问:
jQuery serialize does not register checkboxes
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
</code>```

but not this

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
</code>```

How can I get "values" of checkboxes that is not checked?

答:
You Can Get inputs value with jquery serialize

<input type="checkbox" id="event_allDay" name="event_allDay" checked="checked" onchange="isChecked(this)" value="" />
```

ContentLicense: CC BY-SA 2.5

Body:
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />

but not this

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />

How can I get "values" of checkboxes that is not checked?

Body:
You Can Get inputs value with jquery serialize

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="event_allDay" name="event_allDay" checked="checked" onchange="isChecked(this)" value="" />
<script>
    function isChecked(element) {
        $(element).val($(element).is(':checked').toString());
    }
    isChecked('#event_allDay');
</script>


问:
on deleting any row always deleting last row and not working for deleting more then one row in ios objective c
```<code>     - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

           return result.count;

        }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

       static NSString *CellIdentifier = @"cell";

       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

       if (cell) {

           name = (UILabel *)[cell viewWithTag:10];
           name.text = [result objectAtIndex : indexPath.row];
       }

       else{

           name.tag=indexPath.row;
       }

       return cell;

    }

    - (IBAction)butn:(id)sender {

       [myTbl setEditing:YES animated:YES];

    }
    - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {

       if (self.tbl.editing)
       {
           return UITableViewCellEditingStyleDelete;
       }

       return UITableViewCellEditingStyleNone;
    }

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

       if (editingStyle == UITableViewCellEditingStyleDelete) {

           [result removeObjectAtIndex:indexPath.row];
           [self myMethod];//in this method i'm deleting the data from api also
           [tableView reloadData];

       }

    }

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
       return YES;
    }

  -(void)myMethod{

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.remove.php"]];
        NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:data];

        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable
 response, NSError * _Nullable error) {
            NSDictionary *JSON= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers
 error:nil];

            NSArray *alertArray = [JSON objectForKey:@"removebookmark"];

      for (NSDictionary *alert in alertArray )

          {

                if ([[alert objectForKey:@"status"] isEqualToString:@"remove"])

                {
                                nslog(@"removebookmark");
                                [spinner stopAnimating];

                }

            }

        }]resume];

     }

@end
</code>```

答:
I can see that you are removing object from your local array, and not updating your server about the record you have removed.

Now you are requesting the list of removed record(by myMethod function), obviously that record will not be in your web list.

So that record will be visible after reloading your list and as you have decrements total record by one so you wont be able to see last record.

Also don't reload full table, just reload rows and sections as required.


问:
Cannot install UWP app from hockey app
I'm doing an app using Xamarin.Forms and I've already deployed the Android and iOS version to HockeyApp but I have a problem with the UWP (Windows 10 version)...

These are the steps I do:

Right click on my UWP project

Select "Store" option

Select "Create app packages"

A window pops and I select "No" and click "Next"

Then I only select the ARM configuration

Click "Next"

My package has been created and I drag n drop the .appxbundle file to hockeyapp.

Once the package is uploaded, I start my Windows 10 Mobile emulator and try to install it...
I download it from HockeyApp and when I install it, nothing happens...

Do you have any idea where this problem comes from?

I'm using Visual Studio 2015.

答:
I was experiencing exactly the same, but I've managed to fix it. Here's what I've done:

I associated the app with Store in Visual Studio

I installed Windows 10 Mobile Anniversary update (OS Build: 10.0.14383.953), since my app was targeting Anniversary Update.

I installed the certificate which was included in the .ZIP file next to the .appxbudnle

Then I run the .appxbundle and clicked install. The installer exited without any message, just like before, but after a minute or so the app appeared in the installed apps on my Microsoft Lumia 650.

Title: Cannot install UWP app from hockey app


问:
Android Flash support
Can Android applications can use flash content in them?</p>

答:
From android 2.2 (Froyo) flash is supported.

If you want to use it in an app you could use a WebView

Title: Android Flash support


问:
Youtube API PHP upload limit exceeded
I am using cron job to upload videos from server to youtube channel.

i am getting this error

Caught Google service Exception 400 message is

```<code>{
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}
</code>```

in google console it is showing quota as 20,871 / 50,000,000

i have quota , but videos are not uploading.

one video is uploading per 15 min. i have to upload 200 videos to my account, but this rate it takes some days to upload.

anyone have solutions for this?

答:
This is a quota set by the YouTube API for users. It means that you have hit your upload limit for the day on their platform. The YouTube API works differently to the other Google APIs and you can find out more details here about quotas for YouTube.

You are therefore able to carry out the following each day:

200,000 read operations that each retrieve two resource parts.

10,000 write operations and 90,000 additional read operations that
  each retrieve two resource parts.

400 video uploads, 1500 write operations, and 50,000 read operations that each retrieve two resource parts.

The quote should reset at midnight on West Coast US time.

Title: Youtube API PHP upload limit exceeded

Body:
I am using cron job to upload videos from server to youtube channel.

i am getting this error

Caught Google service Exception 400 message is

{
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}

in google console it is showing quota as 20,871 / 50,000,000

i have quota , but videos are not uploading.

one video is uploading per 15 min. i have to upload 200 videos to my account, but this rate it takes some days to upload.

anyone have solutions for this?


问:
Maven: best way of linking custom external JAR to my project?
It's my first couple of days learning Maven and I'm still struggling with the basics. I have an external .jar file (not available in the public repos) that I need to reference in my project and I'm trying to figure out what my best option is.

It's a small scale project without a central repository for libraries, so it has to be either a local repository (somehow added to source control, don't know if it's supposed to work that way?) or the .jar needs to be stored on disk outside of any formal repository.

1) What's my best option for adding the .jar file to my project's references with maven given that I want both the project and the library to be in source control?

2) I still can't seem to have Eclipse see the dependency. I manually added it to the  section of the pom, and it shows up fine in the Dependencies list in m2eclipse. mvn compile and mvn package both succeed, but running the program results in:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problems:
        LibraryStuff cannot be resolved to a type
</code>```

This is after editing the POM as:

```<code><dependency>
  <groupId>stuff</groupId>
  <artifactId>library</artifactId>
  <version>1.0</version>
  <systemPath>${lib.location}/MyLibrary.jar</systemPath>
  <scope>system</scope>
</dependency>
</code>```

Should I be executing mvn install:install-file even thought I already have the pom.xml edited as above?

Thanks!

答:
If you meet the same problem and you are using spring-boot v1.4+, you can do it in this way.

There is an includeSystemScope that you can use to add system-scope dependencies to the jar.

e.g.

I'm using oracle driver into my project.

```<code><dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>10.2.0.3.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/src/main/resources/extra-jars/ojdbc14-10.2.0.3.0.jar</systemPath>
    </dependency>
</code>```

then make includeSystemScope=true to include the jar into path /BOOT-INF/lib/**

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>
</code>```

and exclude from resource to avoid duplicated include, the jar is fat enought~

```<code><build>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>**/*.jar</exclude>
            </excludes>
        </resource>
    </resources>
</build>
</code>```

Good luck!

Body:
It's my first couple of days learning Maven and I'm still struggling with the basics. I have an external .jar file (not available in the public repos) that I need to reference in my project and I'm trying to figure out what my best option is.

It's a small scale project without a central repository for libraries, so it has to be either a local repository (somehow added to source control, don't know if it's supposed to work that way?) or the .jar needs to be stored on disk outside of any formal repository.

1) What's my best option for adding the .jar file to my project's references with maven given that I want both the project and the library to be in source control?

2) I still can't seem to have Eclipse see the dependency. I manually added it to the  section of the pom, and it shows up fine in the Dependencies list in m2eclipse. mvn compile and mvn package both succeed, but running the program results in:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
        LibraryStuff cannot be resolved to a type

This is after editing the POM as:

<dependency>
  <groupId>stuff</groupId>
  <artifactId>library</artifactId>
  <version>1.0</version>
  <systemPath>${lib.location}/MyLibrary.jar</systemPath>
  <scope>system</scope>
</dependency>

Should I be executing mvn install:install-file even thought I already have the pom.xml edited as above?

Thanks!

Body:
If you meet the same problem and you are using spring-boot v1.4+, you can do it in this way.

There is an includeSystemScope that you can use to add system-scope dependencies to the jar.

e.g.

I'm using oracle driver into my project.

<dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>10.2.0.3.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/src/main/resources/extra-jars/ojdbc14-10.2.0.3.0.jar</systemPath>
    </dependency>

then make includeSystemScope=true to include the jar into path /BOOT-INF/lib/**

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

and exclude from resource to avoid duplicated include, the jar is fat enought~

<build>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>**/*.jar</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Good luck!


问:
NelmioApiDoc - Hide documentation section by default
By default, ApiDoc lists out all operations for each API endpoint, like this:

In the Swagger demo, however, operations are hidden by default until the user chooses to show them.

Is there a configuration option for ApiDoc that will hide operations by default? I haven't found anything like this in the documentation.

答:
You must change your config.yml file like this (default_sections_opened to false):</p>

```<code>nelmio_api_doc:
   name: 'API documentation'
   exclude_sections:     []
   **default_sections_opened:  false**
  motd:
    template:             'NelmioApiDocBundle::Components/motd.html.twig'
  request_listener:
    enabled:              true
    parameter:            _doc
  sandbox:
    enabled:              false
</code>```

Body:
You must change your config.yml file like this (default_sections_opened to false):

nelmio_api_doc:
   name: 'API documentation'
   exclude_sections:     []
   **default_sections_opened:  false**
  motd:
    template:             'NelmioApiDocBundle::Components/motd.html.twig'
  request_listener:
    enabled:              true
    parameter:            _doc
  sandbox:
    enabled:              false


问:
Getting single PID from pgrep
When I execute the following command on shell it returns the expected PID of e.g. 4676:

```<code>pgrep -f konakart
</code>```

But when using that line on a script it returns two IDs (the expected one, and I guess the other one from itself):

```<code># vim test.sh
#!/bin/ksh
echo $(pgrep -f $1)

# ./test.sh konakart
4676 17847
</code>```

What is wrong on these lines?

答:
As mentioned (in grails answer) here is my check-snipped for icinga:</p>

```<code># vim check_process
#!/bin/ksh
rc=0
#kkPID=$(pgrep -f konakart)
#kkPID=$(ps -ef | awk '/[k]onakart/{print $2}')
#kkPID=$(ps -eo pid,command | grep "konakart" | grep -v grep | awk '{print $1}')
pid=$(pgrep -fl $1 | grep -v "check_process" | sed "s/\(\d*\) .*/\1/")
if [ -z "$pid" ]
then
  msg="CRITICAL - No $1 process found"
  rc=2
else
  msg="OK - $1 runs on PID: $pid"
fi
echo $msg
return $rc
</code>```

Title: Getting single PID from pgrep

Body:
When I execute the following command on shell it returns the expected PID of e.g. 4676:

pgrep -f konakart

But when using that line on a script it returns two IDs (the expected one, and I guess the other one from itself):

# vim test.sh
#!/bin/ksh
echo $(pgrep -f $1)

# ./test.sh konakart
4676 17847

What is wrong on these lines?

Body:
As mentioned (in grails answer) here is my check-snipped for icinga:

# vim check_process
#!/bin/ksh
rc=0
#kkPID=$(pgrep -f konakart)
#kkPID=$(ps -ef | awk '/[k]onakart/{print $2}')
#kkPID=$(ps -eo pid,command | grep "konakart" | grep -v grep | awk '{print $1}')
pid=$(pgrep -fl $1 | grep -v "check_process" | sed "s/\(\d*\) .*/\1/")
if [ -z "$pid" ]
then
  msg="CRITICAL - No $1 process found"
  rc=2
else
  msg="OK - $1 runs on PID: $pid"
fi
echo $msg
return $rc


问:
Vim - difference between typed keys and keys from mapping?
In Vim's documentation of feedkeys(), the description of mode t reads:

```<code>    't' Handle keys as if typed; otherwise they are handled as
        if coming from a mapping.  This matters for undo,
        opening folds, etc.
</code>```

What is this difference?  In what ways do keys coming from mappings behave differently and why does this difference matter for undo, opening folds, etc.?

答:
Mapping sequence is atomized for undo.

If you change the text with many command, then undo will undo it back changes by changes.

If you map same sequence of command to mapping, and try undo it, it will bring back changes in state before running mapping.

For example: you have text '12345' with cursor on 2. You 3 time hit 'x'. You need 3 time hit 'u' to bring the text back.

If you make mapping:

```<code>:map q xxx
</code>```

After you press q, you can bring back change with only one pressing 'u'.

Also from :h map-undo:

If you include an undo command inside a mapped sequence, this will bring the text back in the state before executing the macro. This is compatible with
  the original Vi

Body:
In Vim's documentation of feedkeys(), the description of mode t reads:

    't' Handle keys as if typed; otherwise they are handled as
        if coming from a mapping.  This matters for undo,
        opening folds, etc.

What is this difference?  In what ways do keys coming from mappings behave differently and why does this difference matter for undo, opening folds, etc.?

Body:
Mapping sequence is atomized for undo.

If you change the text with many command, then undo will undo it back changes by changes.

If you map same sequence of command to mapping, and try undo it, it will bring back changes in state before running mapping.

For example: you have text '12345' with cursor on 2. You 3 time hit 'x'. You need 3 time hit 'u' to bring the text back.

If you make mapping:

:map q xxx

After you press q, you can bring back change with only one pressing 'u'.

Also from :h map-undo:

If you include an undo command inside a mapped sequence, this will bring the text back in the state before executing the macro. This is compatible with
  the original Vi


问:
What is best and most active open source .Net search technology?
I'm trying to decide on an open source search/indexing technology for a .Net project.  It seems like the standard out there for Java projects is Lucene, but as far as .Net is concerned, the Lucene.Net project seems to be pretty inactive.  Is this still the best option out there?  Or are there other viable alternatives?</p>

答:
I used to use DotLucene but ran into a number of problems. a major one was the fact that it required full trust to run.

I have since moved to using SearchAroo: http://www.searcharoo.net/

it uses an XML data store, and i have found its performance to be VERY similar to dot lucene.

if you are looking for another option, i'd definitely take a look.


问:
Laravel query builder strange result with join
I have a query

```<code>$orders = DB::table('orders')->where('user_id', $user->id)->get();
</code>```

And this is what I have in view:

```<code>@foreach ($orders as $order)
   {{ $order->id }}
@endforeach
</code>```

It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.

```<code>$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
</code>```

It gives 2 1 1. Result is the same with rightJoin() and join().

I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?

答:
I have tried ->select('orders.*') but it did not change the result.

But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.

```<code>$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
</code>```

Probably this could be done in more pretty way, but this works.
Thank you who commented the post.

UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship

```<code>$orders = Order::with('status')->where('user_id', '=', $user->id)->get();
</code>```

Body:
I have a query

$orders = DB::table('orders')->where('user_id', $user->id)->get();

And this is what I have in view:

@foreach ($orders as $order)
   {{ $order->id }}
@endforeach

It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.

$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();

It gives 2 1 1. Result is the same with rightJoin() and join().

I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?

Body:
I have tried ->select('orders.*') but it did not change the result.

But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.

$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();

Probably this could be done in more pretty way, but this works.
Thank you who commented the post.

UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship

$orders = Order::with('status')->where('user_id', '=', $user->id)->get();


问:
How can I test $rootScope.$emit event?
I have below code in abc controller:

```<code>   $rootScope.$on('selectedItem', function (event, data) {
       vm.selectedItem = data;
   });
</code>```

And the caller function is in xyz controller:

```<code>  function doThis(){
     $rootScope.$emit('selectedItem', 'somedata');
  }
</code>```

How can I reproduce or mock this scenario in karma test?

答:
For first controller (abc), where you listen to it using $rootScope.$on, you can first $rootScope.$emit it and $scope.$digest() it. So that you can receive it in $on.

```<code>var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
}));

describe("some function", function() {
    it("should receive selectedItem with $on", function() {
        rootScope.$emit('selectedItem', 'somedata');
        $scope.$digest();
        expect(vm.selectedItem).toEqual('somedata');
    });
});
</code>```

And for second controller (xyz), You can spy on $rootScope.$emit. And expect it to be called in xyz controller. Like this:

```<code>var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
    spyOn(rootScope, '$emit');
}));

describe("doThis function", function() {
    it("should $emit selectedItem", function() {
        vm.doThis(); // or if you use $scope, call it that way
        expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
    });
});
</code>```

Title: How can I test $rootScope.$emit event?

Body:
I have below code in abc controller:

   $rootScope.$on('selectedItem', function (event, data) {
       vm.selectedItem = data;
   });

And the caller function is in xyz controller:

  function doThis(){
     $rootScope.$emit('selectedItem', 'somedata');
  }

How can I reproduce or mock this scenario in karma test?

Body:
For first controller (abc), where you listen to it using $rootScope.$on, you can first $rootScope.$emit it and $scope.$digest() it. So that you can receive it in $on.

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
}));

describe("some function", function() {
    it("should receive selectedItem with $on", function() {
        rootScope.$emit('selectedItem', 'somedata');
        $scope.$digest();
        expect(vm.selectedItem).toEqual('somedata');
    });
});

And for second controller (xyz), You can spy on $rootScope.$emit. And expect it to be called in xyz controller. Like this:

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
    spyOn(rootScope, '$emit');
}));

describe("doThis function", function() {
    it("should $emit selectedItem", function() {
        vm.doThis(); // or if you use $scope, call it that way
        expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
    });
});


问:
Problems authenticating against Adform PHP
I'm trying to authenticate against Adforms API, but am getting an error when I try.

Can anyone point me in the right direction as to what is wrong? Here are some details:
- The script is being run on a fresh install of EasyPHP (with cUrl enabled).
- The same script is being launched from another computer, on which it works just fine (it runs on a mac - I'm on Windows).
- User and password below are fake, of course.

The code fails with this error:

```<code>Fatal error: Uncaught exception 'Exception' with message 'We did not get a HTTP 200 when retrieving a ticket. We recieved this: { "url": "https:\/\/api.adform.com\/Services\/Security\/Login", "content_type": null, "http_code": 0, "header_size": 0, "request_size": 0, "filetime": -1, "ssl_verify_result": 1, "redirect_count": 0, "total_time": 0.187, "namelookup_time": 0.14, "connect_time": 0.156, "pretransfer_time": 0, "size_upload": 0, "size_download": 0, "speed_download": 0, "speed_upload": 0, "download_content_length": -1, "upload_content_length": -1, "starttransfer_time": 0, "redirect_time": 0, "redirect_url": "", "primary_ip": "37.157.5.109", "certinfo": [], "primary_port": 443, "local_ip": "192.168.1.7", "local_port": 49460 }false' in C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php:60 Stack trace: #0 C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php(66): Adform->ticket() #1 {main} thrown in C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php on line 60
</code>```

Here is my code:

```<code><?php

class Adform
{
    protected $user;
    protected $pass;

    public function __construct($user, $pass)
    {
        $this->user = $user;
        $this->pass = $pass;
    }

    # Authenticate to Adform by retrieving a ticket
    public function ticket()
    {
        $curl = curl_init();

        $credentials = json_encode(array(
            'UserName' => $this->user,
            'Password' => $this->pass
            ));

        $options = array(
            CURLOPT_URL => 'https://api.adform.com/Services/Security/Login',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $credentials,
            CURLOPT_HEADER => TRUE,
            CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
            CURLOPT_RETURNTRANSFER => TRUE,
            );

        curl_setopt_array($curl, $options);

        $result = curl_exec($curl);

        if(curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200')
        {
            $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $header_size);
            $body = json_decode(substr($result, $header_size), TRUE);

            curl_close($curl);

            if(array_key_exists('Ticket', $body))
            {
                # We successfully retrieved a ticket!
                return $body['Ticket'];
            }
            else
            {
                # We connected to Adforms server but did not get a ticket..
                throw new Exception('We connected to Adforms server but did not retrieve a ticket. We recieved this: ' . $result);
            }

        }
        else
        {
            #We did not get a HTTP 200 from the request to Adform..
            throw new Exception('We did not get a HTTP 200 when retrieving a ticket. We recieved this: ' . json_encode(curl_getinfo($curl), JSON_PRETTY_PRINT) . json_encode($result, JSON_PRETTY_PRINT));
        }
    }
}

$adform = new Adform("notsharing","thatwithyouguys");
echo $adform->ticket();
</code>```

Any help would be much appreciated!

Thanks,
Ding

答:
Check $result for error

$result = curl_exec($curl);
if($result === false) {
    echo curl_error($curl);
    echo curl_errno($curl);
}

or better way: curl_exec() always returns false

In my case the problem was: "SSL certificate problem: unable to get local issuer certificate"
Solution that hepled me: https://stackoverflow.com/a/21377070/5569198

Body:
I'm trying to authenticate against Adforms API, but am getting an error when I try.

Can anyone point me in the right direction as to what is wrong? Here are some details:
- The script is being run on a fresh install of EasyPHP (with cUrl enabled).
- The same script is being launched from another computer, on which it works just fine (it runs on a mac - I'm on Windows).
- User and password below are fake, of course.

The code fails with this error:

Fatal error: Uncaught exception 'Exception' with message 'We did not get a HTTP 200 when retrieving a ticket. We recieved this: { "url": "https:\/\/api.adform.com\/Services\/Security\/Login", "content_type": null, "http_code": 0, "header_size": 0, "request_size": 0, "filetime": -1, "ssl_verify_result": 1, "redirect_count": 0, "total_time": 0.187, "namelookup_time": 0.14, "connect_time": 0.156, "pretransfer_time": 0, "size_upload": 0, "size_download": 0, "speed_download": 0, "speed_upload": 0, "download_content_length": -1, "upload_content_length": -1, "starttransfer_time": 0, "redirect_time": 0, "redirect_url": "", "primary_ip": "37.157.5.109", "certinfo": [], "primary_port": 443, "local_ip": "192.168.1.7", "local_port": 49460 }false' in C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php:60 Stack trace: #0 C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php(66): Adform->ticket() #1 {main} thrown in C:\Users\Mikkel\PHP\adformdsp\adf-ticket.php on line 60

Here is my code:

<?php

class Adform
{
    protected $user;
    protected $pass;

    public function __construct($user, $pass)
    {
        $this->user = $user;
        $this->pass = $pass;
    }

    # Authenticate to Adform by retrieving a ticket
    public function ticket()
    {
        $curl = curl_init();

        $credentials = json_encode(array(
            'UserName' => $this->user,
            'Password' => $this->pass
            ));

        $options = array(
            CURLOPT_URL => 'https://api.adform.com/Services/Security/Login',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $credentials,
            CURLOPT_HEADER => TRUE,
            CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
            CURLOPT_RETURNTRANSFER => TRUE,
            );

        curl_setopt_array($curl, $options);

        $result = curl_exec($curl);

        if(curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200')
        {
            $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $header_size);
            $body = json_decode(substr($result, $header_size), TRUE);

            curl_close($curl);

            if(array_key_exists('Ticket', $body))
            {
                # We successfully retrieved a ticket!
                return $body['Ticket'];
            }
            else
            {
                # We connected to Adforms server but did not get a ticket..
                throw new Exception('We connected to Adforms server but did not retrieve a ticket. We recieved this: ' . $result);
            }

        }
        else
        {
            #We did not get a HTTP 200 from the request to Adform..
            throw new Exception('We did not get a HTTP 200 when retrieving a ticket. We recieved this: ' . json_encode(curl_getinfo($curl), JSON_PRETTY_PRINT) . json_encode($result, JSON_PRETTY_PRINT));
        }
    }
}

$adform = new Adform("notsharing","thatwithyouguys");
echo $adform->ticket();

Any help would be much appreciated!

Thanks,
Ding


问:
laravel cron job windows
Iam trying to develop a cron job for a command to send email. I am completely new to cron jobs so I dont really know how it works.

Trying the command by myself in the console works perfectly. But when a set a cron job in CPANEL its not workingrs. I am using Laravel 5, can anyone help please?

Thanks!

My cron job: php /home/reporting/public_html/bsk/artisan schedule:run >> /dev/null 2>&1

My Kernel.php

My class emailUser

答:
In Cpanel: (cPanel & WHM version 62)

Follow the menus : Home → Advanced → Cron Jobs and add :

```<code>php /home/reporting/public_html/bsk/artisan schedule:run >> /dev/null 2>&1
</code>```

For Reference : /home/user/public_html/index.php

On a Unix/Linux Server: use the cmdline crontab -e to enter the cron editor and add the line :

```<code>* * * * * php /var/www/project/artisan schedule:run >> /dev/null 2>&1
</code>```

Title: laravel cron job windows

Body:
In Cpanel: (cPanel & WHM version 62)

Follow the menus : Home → Advanced → Cron Jobs and add :

php /home/reporting/public_html/bsk/artisan schedule:run >> /dev/null 2>&1

For Reference : /home/user/public_html/index.php

On a Unix/Linux Server: use the cmdline crontab -e to enter the cron editor and add the line :

* * * * * php /var/www/project/artisan schedule:run >> /dev/null 2>&1

ContentLicense: CC BY-SA 4.0


问:
Why we need nock to do http request unit test?
Below is the sample code from redux document

```<code>describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { body: { todos: ['do something'] }})

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]

    const store = mockStore({ todos: [] })

    return store.dispatch(actions.fetchTodos())
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})
</code>```

Why we nee to use nock for this unit test?
I did not see any where use the data from nock in this sample code.

答:
Nock is used to mock http requests - if you mock http request it means that your code doesn't perform real http requests to the server.

Nock (and any other http mocking library) overrides native http requests methods so that real http requests will be never sent. It has many benefits - for example you don't have to wait for actual server response because mocked request returns response in no time and of course your test are independent of server. You can focus on testing application code and don't worry about server - even if server doesn't work you test can be run.

You don't have to explictly use data returned by mocked request if you don't need to test it - the main reason of using nock in your code sample is to prevent actual http request to the server that FETCH_TODOS_REQUEST action would normally sent. Besides, even if mocked response data is not explicily  used in tests it's probably used in the application code (probably FETCH_TODOS_SUCCESS action expects todos array to be returend) so you have to mock response data so that your application gets data it expects.

If nock wasn't used the test would take much more time because real http request to the server would be sent.

Body:
Below is the sample code from redux document

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { body: { todos: ['do something'] }})

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]

    const store = mockStore({ todos: [] })

    return store.dispatch(actions.fetchTodos())
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})

Why we nee to use nock for this unit test?
I did not see any where use the data from nock in this sample code.


问:
Good idea to resolve XAML in Silverlight 4 with WIndsor container?
Currently, I am resolving xamls from the container so that i can make use of dependency injection much more easily and ellegantly. It's a web application all written in Silverlight 4 with windsor castle container. I have a 2007 office ribbon and when an menu item is clicked, and the content control below the ribbon is replaced with the relevant xaml.

But is it a good idea to resolve xaml from the container? I am worried about perfomance issue.

Can someone please show me a proper of doing masterpages like in ASP.NET ? I would only like to resolve the xaml when an menu item is clicked. How can i do that? Currently, i resolved every XAML from the constructor before the menu is clicked! So very inefficient!

Any better suggestions?

答:
It's not hard, but to me it's somewhat underspecified, even strange question.

What do you mean by 'resolving XAML with Windsor'? I'm not aware of any IoC container capable of XAML integration of any kind.

However, if all you need to do is to have some kind of master page-like concept in Silverlight, you have several options:

Use Prism and their Region concept.

Use some other MVVM library and their equivalent for Region (Caliburn is great), but note that ultimately this boils down to replacing 'placeholders' that are ContentControls

Do the same as (2), use ContentControls and replace their content by hand (probably what you're doing now I suppose)

If you provided more information with a more specific inquiry, we might be able to help you more.


问:
python sqlite3 can't execute a valid sqlite3 command
I have a feeling that this will be obvious but when I run a command in sqlite3 it's fine but then I run the same command from python sqlite3 it doesn't work.

Schema:

```<code>sqlite> .schema transcriptionUnit
CREATE TABLE "transcriptionUnit" (
    id INTEGER NOT NULL,
    name VARCHAR NOT NULL,
    PRIMARY KEY (id)
);
</code>```

Python function:

```<code>def getValue(path2db, tableName, columnName, findColumn, findValue):
    import sqlite3
    db = sqlite3.connect(path2db)
    cursor = db.cursor()
    query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
    print(query)
    cursor.execute(query)
    all_rows = cursor.fetchall()
    db.close()

    return all_rows
</code>```

Command in sqlite3:

```<code>sqlite> select id from transcriptionUnit where name = 'TU_001';
1
</code>```

Command in ipython:

```<code>In [13]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-13-1797c506d95e> in <module>()
----> 1 db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')

/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/python/read_db_funcs.pyc in getValue(path2db, tableName, columnName, findColumn, findValue)
 19         cursor = db.cursor()
 20         query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
---> 21         cursor.execute(query)
 22         all_rows = cursor.fetchall()
 23         db.close()

OperationalError: no such column: TU_001
</code>```

Just to show that the function generally works:

```<code>In [15]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'name', 'id', str(1))
Out[15]: [(u'TU_001',)]
</code>```

My brain is now fried thinking about this so long so any help would be much appreciated.

答:
In SQL, strings must be quoted. You did this with the command in sqlite3, but not when constructing the command in Python.

But to avoid string formatting problems like this (and SQL injection attacks), better use parameters (which work only for values, not for table/column names):

```<code>query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = ?'
cursor.execute(query, [findValue])
</code>```

Body:
I have a feeling that this will be obvious but when I run a command in sqlite3 it's fine but then I run the same command from python sqlite3 it doesn't work.

Schema:

sqlite> .schema transcriptionUnit
CREATE TABLE "transcriptionUnit" (
    id INTEGER NOT NULL,
    name VARCHAR NOT NULL,
    PRIMARY KEY (id)
);

Python function:

def getValue(path2db, tableName, columnName, findColumn, findValue):
    import sqlite3
    db = sqlite3.connect(path2db)
    cursor = db.cursor()
    query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
    print(query)
    cursor.execute(query)
    all_rows = cursor.fetchall()
    db.close()

    return all_rows

Command in sqlite3:

sqlite> select id from transcriptionUnit where name = 'TU_001';
1

Command in ipython:

In [13]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-13-1797c506d95e> in <module>()
----> 1 db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')

/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/python/read_db_funcs.pyc in getValue(path2db, tableName, columnName, findColumn, findValue)
 19         cursor = db.cursor()
 20         query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
---> 21         cursor.execute(query)
 22         all_rows = cursor.fetchall()
 23         db.close()

OperationalError: no such column: TU_001

Just to show that the function generally works:

In [15]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'name', 'id', str(1))
Out[15]: [(u'TU_001',)]

My brain is now fried thinking about this so long so any help would be much appreciated.

Body:
In SQL, strings must be quoted. You did this with the command in sqlite3, but not when constructing the command in Python.

But to avoid string formatting problems like this (and SQL injection attacks), better use parameters (which work only for values, not for table/column names):

query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = ?'
cursor.execute(query, [findValue])


问:
Add active class to button in react
I'm trying to add an active class to my buttons in react, however this doesn't add my class and does nothing when I click on a button.

I get no errors in the console and I have similar code for radio buttons which does work but I am not sure how to modify that code to work for my group of buttons.

I can see in the react dev tools that my class nav-active is being applied to the first button as expected but I dont see the black bg color on the button:

答:
You just need send your id in yor function setActiveTab(id).

```<code>onClick={() => this.setActiveTab(item.id)}
</code>```

And i advice you to change key from item.id to index which you send with arrow function.

```<code>const tabs = items.map(item => // const tabs = items.map((item, index) =>
  <div key={item.id}> // <div key={index}>
    <TestBtn
      isActive={item.id}
      className={this.state.isActive === item.id ? 'nav-active' : ''}
      onClick={this.setActiveTab}
    >
      {item.name}
    </TestBtn>
  </div>, // what is , ?
)
</code>```

Title: Add active class to button in react

Body:
You just need send your id in yor function setActiveTab(id).

onClick={() => this.setActiveTab(item.id)}

And i advice you to change key from item.id to index which you send with arrow function.

const tabs = items.map(item => // const tabs = items.map((item, index) =>
  <div key={item.id}> // <div key={index}>
    <TestBtn
      isActive={item.id}
      className={this.state.isActive === item.id ? 'nav-active' : ''}
      onClick={this.setActiveTab}
    >
      {item.name}
    </TestBtn>
  </div>, // what is , ?
)


问:
Python GUI Tkinter is not including all libraries or modules to use
I am using Pycharm version: Pycharm Community Edition 2017.1 on Windows 7 64 bit edition, and my environment variables are set as below:

PYTHONPATH: C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\Lib;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\DLLs;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6;

PATH: C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\;C:\Tcl\bin;C:\Program Files\Java\jdk1.8.0_60\bin;%PATH%

CLASSPATH:  C:\Program Files\Java\jdk1.8.0_60\bin;C:\Program Files\Java\jre1.8.0_60\bin;.

When I open a new python file using pycharm and type in:

```<code>import tkinter this works
</code>```

Whereas :

tkinter.[functions popup] would display very few options:

as in image, Looks like I have to update the path variable or either some things to change in my Pycharm IDE. I am a newbie for a tkinter GUI programming.

答: You have a file named tkinter.py, so it's importing that file rather than the tkinter module. rename tkinter.py to something else.

Body:
I am using Pycharm version: Pycharm Community Edition 2017.1 on Windows 7 64 bit edition, and my environment variables are set as below:

PYTHONPATH: C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\Lib;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\DLLs;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6;

PATH: C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\vinsow\AppData\Local\Programs\Python\Python36-32\;C:\Tcl\bin;C:\Program Files\Java\jdk1.8.0_60\bin;%PATH%

CLASSPATH:  C:\Program Files\Java\jdk1.8.0_60\bin;C:\Program Files\Java\jre1.8.0_60\bin;.

When I open a new python file using pycharm and type in:

import tkinter this works

Whereas :

tkinter.[functions popup] would display very few options:

as in image, Looks like I have to update the path variable or either some things to change in my Pycharm IDE. I am a newbie for a tkinter GUI programming.


问:
Find existing object into an array in nodejs
Hi this is my collection i just want to look userId into subcriber array if both userId exist into the subcriber array than not create new collection return same channelId. If both userId not exist into subcriber array then create new document how can i search userids in an array.
this is my collection.

```<code>{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
    {
        "userId" : "58dcc3cd9a7a301308b62857",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743444"),
        "status" : "accepted"
    },
    {
        "userId" : "58dcc3ec9a7a301308b62859",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743445"),
        "status" : "pending"
    }
],
"__v" : 0
</code>```

}

I have tried this but not working.

```<code>Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }
</code>```

答:
for this type of problem can use $elemMatch of mongodb.</p>

```<code>db.getCollection('channels').find({subcriber:{"$elemMatch":{userId:"58dcc3cd9a7a301308b62857",userId:'58dcc3ec9a7a301308b62859'}}})
</code>```

Body:
Hi this is my collection i just want to look userId into subcriber array if both userId exist into the subcriber array than not create new collection return same channelId. If both userId not exist into subcriber array then create new document how can i search userids in an array.
this is my collection.

{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
    {
        "userId" : "58dcc3cd9a7a301308b62857",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743444"),
        "status" : "accepted"
    },
    {
        "userId" : "58dcc3ec9a7a301308b62859",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743445"),
        "status" : "pending"
    }
],
"__v" : 0

}

I have tried this but not working.

Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }

Body:
for this type of problem can use $elemMatch of mongodb.

db.getCollection('channels').find({subcriber:{"$elemMatch":{userId:"58dcc3cd9a7a301308b62857",userId:'58dcc3ec9a7a301308b62859'}}})


问:
Sizable input file and submit button on same line
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

```

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

答:
Here is a snippet. I hope this is what you are looking.

.Row {
  width: 100%;
  table-layout: fixed;
  float: left;
}

.Column {
  display: inline-block;
  background-color: red;
  resize:both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Row">
  <label class="Column">Text</label>
  <input class="Column" type="file" />
  <input class="Column" type="submit" value="Upload" />
</div></code>```

Body:
I want to display a label, an input file and a submit button on the same line. The input file needs to be sizable (this means it will change size when the parent changes size and NOT dragable to resize). I tried to use display: table and display: table-cell and for some reason it works for other combinations but not this one

        Text
        <input type="file" style="display:table-cell; width: 100%;"/>
        <input style="display: table-cell; width:50px;" type="submit" value = "Upload"/>

Here is the fiddle: https://jsfiddle.net/danbenedek/wxn976oe/2/

Here is the original fiddle: http://jsfiddle.net/danbenedek/un9qae0x/1/ from where I got inspired but all the elements are div and it works. The moment I changed them to label and input it stop working.

Body:
Here is a snippet. I hope this is what you are looking.

.Row {
  width: 100%;
  table-layout: fixed;
  float: left;
}

.Column {
  display: inline-block;
  background-color: red;
  resize:both;
}

<div class="Row">
  <label class="Column">Text</label>
  <input class="Column" type="file" />
  <input class="Column" type="submit" value="Upload" />
</div>


问:
Adding icon on WPF XAML window causes error/crash VS2012
I found a bug in WPF XAML when specifying an icon for a XAML Window, trying to run the program generates an error message on the line:

```<code> System.Windows.Application.LoadComponent(Me, resourceLocater)
</code>```

XamlParseException occurred

Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '5' and line position '100'.

I've set the icon to Always Create on the Copy To Output Directory with no luck.

I changed the icon from Resource to EmbeddedResource  - no luck there either.

I added it to the Resources for the project - still no luck.

I've verified the file and its location 100%.

The XAML of the window is correct, the name is correct, the path is correct.

```<code>Icon="Resources/VisualizerIcon.ico"
</code>```

Stumped - online forums say to Copy to output Directory is the solution, but, after building the solution, only the Folder is copied over (even though I explicitly set the ICO file to be copied).

Anyone?

答:
Try check for the inner exception. If the call site looks like:

at System.Windows.Media.Imaging.BitmapSource.CriticalCopyPixels(System.Windows.Int32Rect, IntPtr, Int32, Int32)
    at System.Windows.Media.Imaging.BitmapSource.CriticalCopyPixels(System.Windows.Int32Rect, System.Array, Int32, Int32)
    at System.Windows.Media.Imaging.BitmapSource.CopyPixels(System.Windows.Int32Rect, System.Array, Int32, Int32)
    at System.Windows.Media.Imaging.BitmapSource.CopyPixels(System.Array, Int32, Int32)
    at MS.Internal.AppModel.IconHelper.CreateIconHandleFromBitmapFrame(System.Windows.Media.Imaging.BitmapFrame)
    at MS.Internal.AppModel.IconHelper.CreateIconHandleFromImageSource(System.Windows.Media.ImageSource, System.Windows.Size)
    at MS.Internal.AppModel.IconHelper.GetIconHandlesFromImageSource(System.Windows.Media.ImageSource, IconHandle ByRef, IconHandle ByRef)
    at System.Windows.Window.UpdateIcon()
    at System.Windows.Window.SetupInitialState(Double, Double, Double, Double)
    at System.Windows.Window.CreateSourceWindow(Boolean)
    at System.Windows.Window.ShowHelper(System.Object)
    at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
    at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
    at System.Windows.Threading.DispatcherOperation.InvokeImpl()
    at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
    at MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext, System.Threading.ContextCallback, System.Object)
    at System.Windows.Threading.DispatcherOperation.Invoke()
    at System.Windows.Threading.Dispatcher.ProcessQueue()
    at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
    at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
    at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
    at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
    at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
    at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
    at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
    at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
    at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
    at System.Windows.Application.RunDispatcher(System.Object)
    at System.Windows.Application.RunInternal(System.Windows.Window)
    at ClientLauncher.App.Main()

Then you might be running into a bug like this, except for it could happen on newer OS, like Windows 10. Some of our clients have this kind of crashes on Windows 10 machines.

The solution is to simplify the icon file, don't let it contain frames larger than 64*64, or simply use a PNG for window icon instead. That being said, high resolution icons could still be used as app icon.

Body:
I found a bug in WPF XAML when specifying an icon for a XAML Window, trying to run the program generates an error message on the line:

 System.Windows.Application.LoadComponent(Me, resourceLocater)

XamlParseException occurred

Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '5' and line position '100'.

I've set the icon to Always Create on the Copy To Output Directory with no luck.

I changed the icon from Resource to EmbeddedResource  - no luck there either.

I added it to the Resources for the project - still no luck.

I've verified the file and its location 100%.

The XAML of the window is correct, the name is correct, the path is correct.

Icon="Resources/VisualizerIcon.ico"

Stumped - online forums say to Copy to output Directory is the solution, but, after building the solution, only the Folder is copied over (even though I explicitly set the ICO file to be copied).

Anyone?


问:
keep table(rows) together with OpenXML SDK 2.5
I'd like to generate multiple tables with 2 rows each inside of a word document. But I want to keep these two rows together (if possible).

new KeepNext()on the first row doesn't work

new KeepNext()on the last paragraph of the first row doesn't work

new CantSplit() on the table doesn't work

In all cases the second row (if too large) lands on the second page. A new CantSplit() on the last cell ( the one with large content) avoids a break of the cell. But none of the options avoids a split of the table (rowwise).

答:
```<code>i did it like this when I had to apply this to all tables:

private static void AlterTableType(List<Table> t)
    {
        foreach (Table table in t)
        {
            foreach (TableRow row in table.Descendants<TableRow>())
            {
                TableRowProperties trP = new TableRowProperties();
                CantSplit split = new CantSplit();
                trP.Append(split);
                row.AppendChild(trP);
            }
        }
    }
</code>```

getting all tables

```<code>var t = package.MainDocumentPart.Document.Body.Descendants<Table>().ToList()
</code>```

Body:
i did it like this when I had to apply this to all tables:

private static void AlterTableType(List<Table> t)
    {
        foreach (Table table in t)
        {
            foreach (TableRow row in table.Descendants<TableRow>())
            {
                TableRowProperties trP = new TableRowProperties();
                CantSplit split = new CantSplit();
                trP.Append(split);
                row.AppendChild(trP);
            }
        }
    }

getting all tables

var t = package.MainDocumentPart.Document.Body.Descendants<Table>().ToList()


问:
Beego ORM with MySQL
I am new to Beego as well as Go. I read its documentation but it puts every ORM operation in the main package instead of model package. I can't understand how to organize the code. I am really very confused.</p>

答:
You can feel free to follow steps as below, and try to build your first database program.

Build [Models]
According to the table structure of your database.

Initialize the ORM

New an ORM instance

Operate CRUD as your want

Link:

Guidance for Beego/orm configuration

https://beego.me/docs/mvc/model/orm.md

Guidance for operating CRUD on Beego/orm

https://beego.me/docs/mvc/model/object.md

Title: Beego ORM with MySQL


问:
Setting the day of the date to the 1st with moment.js
I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.

In brief this should be the out come:

today's date: 21/05/2017

startDate = 01/04/2017

endDate = 30/06/2017

My code:

```<code>var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');
</code>```

答:
Simply use add and subtract method to get next and previous month and startOf and endOf to get the first and the last day of the month.

Here a working sample:

var date = moment([2017, 4, 21]); // one way to get 21/05/2017
// If your input is a string you can do:
//var date = moment('21/05/2017', 'DD/MM/YYYY');
var startDate = date.clone().subtract(1, 'month').startOf('month');
var endDate = date.clone().add(1, 'month').endOf('month');

console.log(startDate.format('DD/MM/YYYY')); // 01/04/2017
console.log(endDate.format('DD/MM/YYYY'));   // 30/06/2017```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.

In brief this should be the out come:

today's date: 21/05/2017

startDate = 01/04/2017

endDate = 30/06/2017

My code:

var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');

Body:
Simply use add and subtract method to get next and previous month and startOf and endOf to get the first and the last day of the month.

Here a working sample:

var date = moment([2017, 4, 21]); // one way to get 21/05/2017
// If your input is a string you can do:
//var date = moment('21/05/2017', 'DD/MM/YYYY');
var startDate = date.clone().subtract(1, 'month').startOf('month');
var endDate = date.clone().add(1, 'month').endOf('month');

console.log(startDate.format('DD/MM/YYYY')); // 01/04/2017
console.log(endDate.format('DD/MM/YYYY'));   // 30/06/2017

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Can we trim the text stream [DT_TEXT] lnput column length to 1000 characters in SSIS before sending it to output column
I am new to SSIS so please bear with me.

I have a external column in my SSIS package with text stream [DT_TEXT] data type (length 0) the output column is string [DT_STR] (length 1000).

Is there a way to trim the length of external column text stream [DT_TEXT] to 1000 before sending to output.

Any help will be really appreciated.

I have tried Advanced Editor Column length column is disabled(as obvious) for text stream [DT_TEXT] data types.

Any input will be really appreciated. Thanks

答:
You probably want to take a look at using a Data Conversion Transformation Editor:

Use the Data Conversion Transformation Editor dialog box to select the columns to convert, select the data type to which the column is converted, and set conversion attributes.

You can set the input column, output alias, data type and length. This would then produce a new aliased column in the new type.

This link provides sample of how this can be achieved:

SSIS Data Conversion

You can see how various input columns are being transformed, with an output Data Type and Length.


问:
Forcing "+0000" timezone for RFC2822 times in Ruby
How can I force the Time.rfc2822 function to spit out +0000?

Ruby lets me parse RFC2822 formatted times pretty easily:

```<code>require 'time'
time = Time.parse('14 Aug 2009 09:28:32 +0000')
puts time
=> "2009-08-14 05:28:32 -0400"
</code>```

But what about displaying times?  Notice that the time it parsed is a local time.  No worries, I can convert it back to a UTC time with gmtime:

```<code>puts time.gmtime
=> "2009-08-14 09:28:32 UTC"
</code>```

I can then put it back into RFC2822 format:

```<code>puts time.gmtime.rfc2822
=> "Fri, 14 Aug 2009 09:28:32 -0000"
</code>```

Unfortunately, this is not quite what I want.  Notice that the +0000 is now -0000.  According to RFC2822, this is because:

The form "+0000" SHOULD be used to indicate a time zone at
     Universal Time.  Though "-0000" also indicates Universal Time, it is
     used to indicate that the time was generated on a system that may be
     in a local time zone other than Universal Time and therefore
     indicates that the date-time contains no information about the local
     time zone.

Great - so how can I force +0000 other than monkey-patching the rfc2822 function?

答:
simplest way if you don't need to use on multiple places

```<code> Time.now.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
 => "Fri, 31 Mar 2017 08:39:04 +0000"
</code>```

or as a static (singleton) method version

```<code>require 'time'
module MyCustomTimeRFC
  def custom_rfc2822(time)
    time.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
  end

  module_function :custom_rfc2822
end

t = Time.now
p MyCustomTimeRFC.custom_rfc2822(t)
#=> "Fri, 31 Mar 2017 08:43:15 +0000"
</code>```

or as module extension if you like the oop style with ruby flexibility.

```<code>require 'time'
module MyCustomTimeRFC
  def custom_rfc2822
    gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
  end
end

t = Time.now
t.extend(MyCustomTimeRFC)
p t.custom_rfc2822
#=> "Fri, 31 Mar 2017 08:43:15 +0000"
</code>```

Body:
How can I force the Time.rfc2822 function to spit out +0000?

Ruby lets me parse RFC2822 formatted times pretty easily:

require 'time'
time = Time.parse('14 Aug 2009 09:28:32 +0000')
puts time
=> "2009-08-14 05:28:32 -0400"

But what about displaying times?  Notice that the time it parsed is a local time.  No worries, I can convert it back to a UTC time with gmtime:

puts time.gmtime
=> "2009-08-14 09:28:32 UTC"

I can then put it back into RFC2822 format:

puts time.gmtime.rfc2822
=> "Fri, 14 Aug 2009 09:28:32 -0000"

Unfortunately, this is not quite what I want.  Notice that the +0000 is now -0000.  According to RFC2822, this is because:

The form "+0000" SHOULD be used to indicate a time zone at
     Universal Time.  Though "-0000" also indicates Universal Time, it is
     used to indicate that the time was generated on a system that may be
     in a local time zone other than Universal Time and therefore
     indicates that the date-time contains no information about the local
     time zone.

Great - so how can I force +0000 other than monkey-patching the rfc2822 function?

Body:
simplest way if you don't need to use on multiple places

 Time.now.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
 => "Fri, 31 Mar 2017 08:39:04 +0000"

or as a static (singleton) method version

require 'time'
module MyCustomTimeRFC
  def custom_rfc2822(time)
    time.gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
  end

  module_function :custom_rfc2822
end

t = Time.now
p MyCustomTimeRFC.custom_rfc2822(t)
#=> "Fri, 31 Mar 2017 08:43:15 +0000"

or as module extension if you like the oop style with ruby flexibility.

require 'time'
module MyCustomTimeRFC
  def custom_rfc2822
    gmtime.rfc2822.sub(/(-)(0+)$/, '+\2')
  end
end

t = Time.now
t.extend(MyCustomTimeRFC)
p t.custom_rfc2822
#=> "Fri, 31 Mar 2017 08:43:15 +0000"


问:
How to change image and text on hover
I am trying to change the image and text on hover and I have got this in codepen but it doesnt seem to be working?

$(".service_1").hover(function() {
  $(".hello").hide();

  $(".text").append("Appended text");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.service_item img {
  position: absolute;
}

.service_item {
  height: 307px;
  width: 700px;
  background-size: cover;
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
  float: left;
  position: relative;
}

.service_item:hover {
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 50%;
  display: block;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  position: relative;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item img:hover {
  opacity: 0;
}

.service_item span {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  text-align: center;
}</code>```

Hello there

```

Can someone point me to where im going wrong please?

答:
Css can handle what you are trying to achieve. Here is a working example using css transitions and flex-box to align your text:

.service_item img {
  position: absolute;
  z-index: -1;
}

.service_item {
  height: 307px;
  width: 700px;
  float: left;
  position: relative;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 307px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item:hover img:last-of-type {
  opacity: 0;
}

.service_item:hover .append-text {
  opacity: 1;
}

.append-text {
  opacity: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="service_item service_1">

    <img src="http://www.edwards-immigration.co.uk/wp-content/uploads/2017/02/mikhail-pavstyuk-8436.png">
    <img src="http://www.edwards-immigration.co.uk/wp-content/uploads/2017/02/Untitled-1.png">
    <div class="hello">Hello there</div>
    <div class="append-text">APPENDED TEXT</div>

</div></code>```

Title: How to change image and text on hover

Body:
I am trying to change the image and text on hover and I have got this in codepen but it doesnt seem to be working?

$(".service_1").hover(function() {
  $(".hello").hide();

  $(".text").append("Appended text");
});

.service_item img {
  position: absolute;
}

.service_item {
  height: 307px;
  width: 700px;
  background-size: cover;
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
  float: left;
  position: relative;
}

.service_item:hover {
  transition: background-image 0.5s linear;
  -webkit-transition: background-image 0.5s linear;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 50%;
  display: block;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  position: relative;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item img:hover {
  opacity: 0;
}

.service_item span {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  text-align: center;
}

Hello there

Can someone point me to where im going wrong please?

Body:
Css can handle what you are trying to achieve. Here is a working example using css transitions and flex-box to align your text:

.service_item img {
  position: absolute;
  z-index: -1;
}

.service_item {
  height: 307px;
  width: 700px;
  float: left;
  position: relative;
}

.serviceimg {
  margin-top: 66px;
  height: 949px;
}

.service_item a {
  height: 307px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
}

.service_item img {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 300px;
  transition: opacity .5s ease;
}

.service_item:hover img:last-of-type {
  opacity: 0;
}

.service_item:hover .append-text {
  opacity: 1;
}

.append-text {
  opacity: 0;
}

<div class="service_item service_1">
  <a href="/uk-marriage-spouse-civil-partner-visa/">
    <img src="http://www.edwards-immigration.co.uk/wp-content/uploads/2017/02/mikhail-pavstyuk-8436.png">
    <img src="http://www.edwards-immigration.co.uk/wp-content/uploads/2017/02/Untitled-1.png">
    <div class="hello">Hello there</div>
    <div class="append-text">APPENDED TEXT</div>
  </a>
</div>


问:
Apple rejected my app for problems with IPv6 (crashing)
I have an App that doesn't use internet connexion, but apple send me a message where says that I have a crash in my first view controller for problem with the IPv6. Apple send me a report for the crash but i'm not able to learn it, i need your help. Or maybe if u had the same problem with this conexión(IPv6) and you were find the error.

pleas help me!!

Heres one file from the crash, that apple send me but i don't understand, pleas help me to know what they say.

```<code>{"app_name":"idWallet","timestamp":"2017-03-03 19:35:40.34 -0800","app_version":"1.1","slice_uuid":"7670eb49-b5ca-3334-b398-6cdb6982530e","adam_id":0,"build_version":"3","bundleID":"fernandorey.idWallet","share_with_app_devs":false,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 10.2.1 (14D27)","incident_id":"195A9217-8AF8-47BA-A8C2-4FC808AF587F","name":"idWallet"}
Incident Identifier: 195A9217-8AF8-47BA-A8C2-4FC808AF587F
CrashReporter Key:   0ec021c8a7f1efb30dfc7eceb07eaa3fd8f82c46
Hardware Model:      xxx
Process:             idWallet [8539]
Path:                /private/var/containers/Bundle/Application/E974F007-2A8F-4724-A766-6E542BCDD035/idWallet.app/idWallet
Identifier:          fernandorey.idWallet
Version:             3 (1.1)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           fernandorey.idWallet [4123]

Date/Time:           2017-03-03 19:35:40.1752 -0800
Launch Time:         2017-03-03 19:26:24.4423 -0800
OS Version:          iPhone OS 10.2.1 (14D27)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Last Exception Backtrace:
(0x18e1a91b8 0x18cbe055c 0x1904c0b90 0x10005f17c 0x10005e8c8 0x194057924 0x1940574ec 0x194a19cf0 0x1943a24ac 0x1943c3a54 0x1943c6920 0x19414a154 0x1943ca0e4 0x194706808 0x194814854 0x19481465c 0x1943ba9b8 0x100067b98 0x100068804 0x10006841c 0x100068218 0x19408cd30 0x19408ccb0 0x194077128 0x19408c59c 0x19408c0c4 0x194087328 0x194057da0 0x19484175c 0x19483b130 0x18e156b5c 0x18e1564a4 0x18e1540a4 0x18e0822b8 0x18fb36198 0x1940c27fc 0x1940bd534 0x10005d3b4 0x18d0655b8)

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018d177014 0x18d158000 + 126996
1   libsystem_pthread.dylib         0x000000018d23f450 0x18d23a000 + 21584
2   libsystem_c.dylib               0x000000018d0eb400 0x18d088000 + 406528
3   libc++abi.dylib                 0x000000018cbb52d4 0x18cbb4000 + 4820
4   libc++abi.dylib                 0x000000018cbd2cc0 0x18cbb4000 + 126144
5   libobjc.A.dylib                 0x000000018cbe0844 0x18cbd8000 + 34884
6   libc++abi.dylib                 0x000000018cbcf66c 0x18cbb4000 + 112236
7   libc++abi.dylib                 0x000000018cbcf234 0x18cbb4000 + 111156
8   libobjc.A.dylib                 0x000000018cbe071c 0x18cbd8000 + 34588
9   CoreFoundation                  0x000000018e08232c 0x18e079000 + 37676
10  GraphicsServices                0x000000018fb36198 0x18fb2a000 + 49560
11  UIKit                           0x00000001940c27fc 0x194048000 + 501756
12  UIKit                           0x00000001940bd534 0x194048000 + 480564
13  idWallet                        0x000000010005d3b4 0x100054000 + 37812
14  libdyld.dylib                   0x000000018d0655b8 0x18d061000 + 17848

Thread 1 name:  com.apple.uikit.eventfetch-thread
Thread 1:
0   libsystem_kernel.dylib          0x000000018d159188 0x18d158000 + 4488
1   libsystem_kernel.dylib          0x000000018d158ff8 0x18d158000 + 4088
2   CoreFoundation                  0x000000018e1565d0 0x18e079000 + 906704
3   CoreFoundation                  0x000000018e1541ec 0x18e079000 + 897516
4   CoreFoundation                  0x000000018e0822b8 0x18e079000 + 37560
5   Foundation                      0x000000018ebbf26c 0x18ebb3000 + 49772
6   Foundation                      0x000000018ebdfdd0 0x18ebb3000 + 183760
7   UIKit                           0x0000000194a36c38 0x194048000 + 10415160
8   Foundation                      0x000000018ecbce68 0x18ebb3000 + 1089128
9   libsystem_pthread.dylib         0x000000018d23d850 0x18d23a000 + 14416
10  libsystem_pthread.dylib         0x000000018d23d760 0x18d23a000 + 14176
11  libsystem_pthread.dylib         0x000000018d23ad94 0x18d23a000 + 3476

Thread 2:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 3:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 4:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000000000000   x1: 0x0000000000000000   x2: 0x0000000000000000   x3: 0x00000001780e8437
    x4: 0x000000018cbd3bc3   x5: 0x000000016fdab520   x6: 0x000000000000006e   x7: 0xffffffffffffffec
    x8: 0x0000000008000000   x9: 0x0000000004000000  x10: 0x000000000000000b  x11: 0x0000000000000010
   x12: 0x000000018d102772  x13: 0x0000000000000000  x14: 0x0000040000000400  x15: 0x0000000000000000
   x16: 0x0000000000000148  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000006
   x20: 0x00000001b3219c40  x21: 0x000000016fdab520  x22: 0x00000001b3220bb8  x23: 0x0000000000000001
   x24: 0x0000000178018be0  x25: 0x0000000000000000  x26: 0x0000000000000001  x27: 0x0000000000000000
   x28: 0x000000016fdabbc0   fp: 0x000000016fdab480   lr: 0x000000018d23f450
    sp: 0x000000016fdab460   pc: 0x000000018d177014 cpsr: 0x00000000
</code>```

.
.
.

i can't add all the message for question of limit characters.

答:
As @dan mentioned, try to symbolicate your crash report.

The following link will help you.

https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATEWITHXCODE

Body:
I have an App that doesn't use internet connexion, but apple send me a message where says that I have a crash in my first view controller for problem with the IPv6. Apple send me a report for the crash but i'm not able to learn it, i need your help. Or maybe if u had the same problem with this conexión(IPv6) and you were find the error.

pleas help me!!

Heres one file from the crash, that apple send me but i don't understand, pleas help me to know what they say.

{"app_name":"idWallet","timestamp":"2017-03-03 19:35:40.34 -0800","app_version":"1.1","slice_uuid":"7670eb49-b5ca-3334-b398-6cdb6982530e","adam_id":0,"build_version":"3","bundleID":"fernandorey.idWallet","share_with_app_devs":false,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 10.2.1 (14D27)","incident_id":"195A9217-8AF8-47BA-A8C2-4FC808AF587F","name":"idWallet"}
Incident Identifier: 195A9217-8AF8-47BA-A8C2-4FC808AF587F
CrashReporter Key:   0ec021c8a7f1efb30dfc7eceb07eaa3fd8f82c46
Hardware Model:      xxx
Process:             idWallet [8539]
Path:                /private/var/containers/Bundle/Application/E974F007-2A8F-4724-A766-6E542BCDD035/idWallet.app/idWallet
Identifier:          fernandorey.idWallet
Version:             3 (1.1)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           fernandorey.idWallet [4123]

Date/Time:           2017-03-03 19:35:40.1752 -0800
Launch Time:         2017-03-03 19:26:24.4423 -0800
OS Version:          iPhone OS 10.2.1 (14D27)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Last Exception Backtrace:
(0x18e1a91b8 0x18cbe055c 0x1904c0b90 0x10005f17c 0x10005e8c8 0x194057924 0x1940574ec 0x194a19cf0 0x1943a24ac 0x1943c3a54 0x1943c6920 0x19414a154 0x1943ca0e4 0x194706808 0x194814854 0x19481465c 0x1943ba9b8 0x100067b98 0x100068804 0x10006841c 0x100068218 0x19408cd30 0x19408ccb0 0x194077128 0x19408c59c 0x19408c0c4 0x194087328 0x194057da0 0x19484175c 0x19483b130 0x18e156b5c 0x18e1564a4 0x18e1540a4 0x18e0822b8 0x18fb36198 0x1940c27fc 0x1940bd534 0x10005d3b4 0x18d0655b8)

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018d177014 0x18d158000 + 126996
1   libsystem_pthread.dylib         0x000000018d23f450 0x18d23a000 + 21584
2   libsystem_c.dylib               0x000000018d0eb400 0x18d088000 + 406528
3   libc++abi.dylib                 0x000000018cbb52d4 0x18cbb4000 + 4820
4   libc++abi.dylib                 0x000000018cbd2cc0 0x18cbb4000 + 126144
5   libobjc.A.dylib                 0x000000018cbe0844 0x18cbd8000 + 34884
6   libc++abi.dylib                 0x000000018cbcf66c 0x18cbb4000 + 112236
7   libc++abi.dylib                 0x000000018cbcf234 0x18cbb4000 + 111156
8   libobjc.A.dylib                 0x000000018cbe071c 0x18cbd8000 + 34588
9   CoreFoundation                  0x000000018e08232c 0x18e079000 + 37676
10  GraphicsServices                0x000000018fb36198 0x18fb2a000 + 49560
11  UIKit                           0x00000001940c27fc 0x194048000 + 501756
12  UIKit                           0x00000001940bd534 0x194048000 + 480564
13  idWallet                        0x000000010005d3b4 0x100054000 + 37812
14  libdyld.dylib                   0x000000018d0655b8 0x18d061000 + 17848

Thread 1 name:  com.apple.uikit.eventfetch-thread
Thread 1:
0   libsystem_kernel.dylib          0x000000018d159188 0x18d158000 + 4488
1   libsystem_kernel.dylib          0x000000018d158ff8 0x18d158000 + 4088
2   CoreFoundation                  0x000000018e1565d0 0x18e079000 + 906704
3   CoreFoundation                  0x000000018e1541ec 0x18e079000 + 897516
4   CoreFoundation                  0x000000018e0822b8 0x18e079000 + 37560
5   Foundation                      0x000000018ebbf26c 0x18ebb3000 + 49772
6   Foundation                      0x000000018ebdfdd0 0x18ebb3000 + 183760
7   UIKit                           0x0000000194a36c38 0x194048000 + 10415160
8   Foundation                      0x000000018ecbce68 0x18ebb3000 + 1089128
9   libsystem_pthread.dylib         0x000000018d23d850 0x18d23a000 + 14416
10  libsystem_pthread.dylib         0x000000018d23d760 0x18d23a000 + 14176
11  libsystem_pthread.dylib         0x000000018d23ad94 0x18d23a000 + 3476

Thread 2:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 3:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 4:
0   libsystem_pthread.dylib         0x000000018d23ad88 0x18d23a000 + 3464

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000000000000   x1: 0x0000000000000000   x2: 0x0000000000000000   x3: 0x00000001780e8437
    x4: 0x000000018cbd3bc3   x5: 0x000000016fdab520   x6: 0x000000000000006e   x7: 0xffffffffffffffec
    x8: 0x0000000008000000   x9: 0x0000000004000000  x10: 0x000000000000000b  x11: 0x0000000000000010
   x12: 0x000000018d102772  x13: 0x0000000000000000  x14: 0x0000040000000400  x15: 0x0000000000000000
   x16: 0x0000000000000148  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000006
   x20: 0x00000001b3219c40  x21: 0x000000016fdab520  x22: 0x00000001b3220bb8  x23: 0x0000000000000001
   x24: 0x0000000178018be0  x25: 0x0000000000000000  x26: 0x0000000000000001  x27: 0x0000000000000000
   x28: 0x000000016fdabbc0   fp: 0x000000016fdab480   lr: 0x000000018d23f450
    sp: 0x000000016fdab460   pc: 0x000000018d177014 cpsr: 0x00000000

.
.
.

i can't add all the message for question of limit characters.


问:
using api's in node.js
i'm running the server using node.js on localhost:8080 and i want to use api's in my HTML document. the html document is external, so how would i go about sending the api data to the web page. for example, i have a weather api in my javascript file:

var yw = require('weather-yahoo');
var ans = {};
function loadWeather() {
  yw.getSimpleWeather('denver,co').then(function(res){
      console.log(res);
      ans=res;
      alert(ans);
  }); // pulls just some of the info from yahoo weather
}```
</div>
</div>
</p>

<p>and i've called it on button click in my html file like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <button onclick="loadWeather();">View article descriptions</button></code>```

but it doesn't work. i also have the included the source of the javascript file in this document by the way.

答:
You have a function on your node server, but now you'll need to expose it to your client. The simplest way to do this is using the express module.

If you are not completely familiar with node modules and express, there are plenty of startup tutorials available such as https://expressjs.com/en/starter/hello-world.html.

In your case you would need to create an API call that will call the weather data function.

```<code>var app = require('express')(),
yw = require('weather-yahoo');

function loadWeather() {
   return yw.getSimpleWeather('denver,co');
}

app.get('/weather', function(req, res){
    loadWeather().then(function(result){
        return res.json(result);
    },
    function(error){
        res.status(400).json(error);
    });
});

app.get('/', function(req, res){
     res.sendFile(process.cwd() + '/index.html', null, function(err) {
        if(err){
            res.sendStatus(404);
        }
    });

})

app.listen(3000, function () {
  console.log('Listening on port 3000');
})
</code>```

This is the simplest of API calls that can easily be extended to return weather for other regions by adding query parameters to the api call.

On the client side, you will now need a function to call your api.
As the example above serves the index file as it's main page, a simple JQuery get call to weather will return the data you want as it is on the same host.

```<code><script>
    //This call uses JQuery, make sure you have it referenced in your site
    function callAPI() {
        $.get("weather", function(data, status){
            $('#result').val(JSON.stringify(data));
        });
    }
</script>

<button onclick="callAPI()">Get Weather</button>
<br>
<textarea id="result" style="width:500px; height:500px"></textarea>
</code>```

Title: using api's in node.js

Body:
i'm running the server using node.js on localhost:8080 and i want to use api's in my HTML document. the html document is external, so how would i go about sending the api data to the web page. for example, i have a weather api in my javascript file:

var yw = require('weather-yahoo');
var ans = {};
function loadWeather() {
  yw.getSimpleWeather('denver,co').then(function(res){
      console.log(res);
      ans=res;
      alert(ans);
  }); // pulls just some of the info from yahoo weather
}

and i've called it on button click in my html file like so:

  <button onclick="loadWeather();">View article descriptions</button>

but it doesn't work. i also have the included the source of the javascript file in this document by the way.

Body:
You have a function on your node server, but now you'll need to expose it to your client. The simplest way to do this is using the express module.

If you are not completely familiar with node modules and express, there are plenty of startup tutorials available such as https://expressjs.com/en/starter/hello-world.html.

In your case you would need to create an API call that will call the weather data function.

var app = require('express')(),
yw = require('weather-yahoo');

function loadWeather() {
   return yw.getSimpleWeather('denver,co');
}

app.get('/weather', function(req, res){
    loadWeather().then(function(result){
        return res.json(result);
    },
    function(error){
        res.status(400).json(error);
    });
});

app.get('/', function(req, res){
     res.sendFile(process.cwd() + '/index.html', null, function(err) {
        if(err){
            res.sendStatus(404);
        }
    });

})

app.listen(3000, function () {
  console.log('Listening on port 3000');
})

This is the simplest of API calls that can easily be extended to return weather for other regions by adding query parameters to the api call.

On the client side, you will now need a function to call your api.
As the example above serves the index file as it's main page, a simple JQuery get call to weather will return the data you want as it is on the same host.

<script>
    //This call uses JQuery, make sure you have it referenced in your site
    function callAPI() {
        $.get("weather", function(data, status){
            $('#result').val(JSON.stringify(data));
        });
    }
</script>

<button onclick="callAPI()">Get Weather</button>
<br>
<textarea id="result" style="width:500px; height:500px"></textarea>