问:
Zipping folders using a Powershell script
Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?

```<code># Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}
</code>```

The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month

答:
If you're using PowerShell v5 then you can use the Compress-Archive function:

```<code>Get-ChildItem $targetPath | Compress-Archive -DestinationPath "$targetPath.zip"
</code>```

This will compress D:\SalesXMLBackup to D:\SalesXMLBackup.zip

Body:
Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?

# Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month

Body:
If you're using PowerShell v5 then you can use the Compress-Archive function:

Get-ChildItem $targetPath | Compress-Archive -DestinationPath "$targetPath.zip"

This will compress D:\SalesXMLBackup to D:\SalesXMLBackup.zip


来源: stackexchange

问:
Facebook friend request API's
I am writing an application which allows the user to login to facebook and fetch their details for contact sharing. Now i need to send a friend request to another user using facebook API's (programmaticaly). I had tested both OLD REST based API's and Graph Based API's but i couldnt find an appropriate one. Please help me.</p>

答: There is no friend request API. The only way for a person to request somebody to be their friend is through the Facebook web interface.</p>

ContentLicense: CC BY-SA 2.5

Title: Facebook friend request API's


问:
Custom on hover and ul/li elements?
I'm new here, so please tell me if I formulated something wrongly, code or text-wise.

This is the code I'm currently using for my page. Yes, I know it's short and terrible, but I'm still learning HTML/CSS. If you run that on a page, you'll notice no hover events on the navbar buttons, and some fiddling with the logo will reveal that the actual navbar is a big bar. (width:100%?)

I was only wondering as to how I would go about creating an on hover that's only slightly there, something like this: (hovered on the left, not hovered on the right)
Hover showcase

I don't necessarily need it using my current setup or it being exact, but I'd like an explanation as to how this would be done. (the site I took it from has fancy fade on the text turning blue and a slide animation on the bar from the bottom, but I don't expect I'll be able to do that)

I was also wondering how I could have the logo be on the same bar as the other li elements, and then center it off how long logo + li elements (the whole bar) would be. (as opposing to having the li elements centered and a logo off to the left.) Also, a thick, colored bar above the navbar, but not below, like a margin, and having the navbar be a little thicker as well, as  the picture above depicts fairly well.

Thank you for any assistance I can recieve!

Hyao

答:
So for the hover color you can do something like:

```<code>li:hover {
    color: blue;
    border-bottom: 3px solid blue;
}
</code>```

To add more of the animation you might want to do:

```<code>    li {
        display: inline-block;
        vertical-align: middle;
    }
    li a:hover {
        color: blue;
    }

    li a:after {
        margin: 0 auto;
        width: 0px;
        height: 3px;
        display: block;
        content: "";
        background-color: blue;
        transition: width 0.5s linear;
    }

    li a:hover:after {
        width: 100%;
    }

    li img {
       padding: 14px 16px;
    }
</code>```

http://plnkr.co/edit/GrxqcRjoMa7aWjHvnBhA

basically you are creating a psuedo element :after which has an animation on its width. When you hover over an li element the psuedo element will grow to 100% of the width looking like an expanding underline.

To make the image inline with the other elements remove your position: absolute style for the #logo

ContentLicense: CC BY-SA 3.0

Title: Custom on hover and ul/li elements?

Body:
So for the hover color you can do something like:

li:hover {
    color: blue;
    border-bottom: 3px solid blue;
}

To add more of the animation you might want to do:

    li {
        display: inline-block;
        vertical-align: middle;
    }
    li a:hover {
        color: blue;
    }

    li a:after {
        margin: 0 auto;
        width: 0px;
        height: 3px;
        display: block;
        content: "";
        background-color: blue;
        transition: width 0.5s linear;
    }

    li a:hover:after {
        width: 100%;
    }

    li img {
       padding: 14px 16px;
    }

http://plnkr.co/edit/GrxqcRjoMa7aWjHvnBhA

basically you are creating a psuedo element :after which has an animation on its width. When you hover over an li element the psuedo element will grow to 100% of the width looking like an expanding underline.

To make the image inline with the other elements remove your position: absolute style for the #logo


问:
"No such file to load" error when running Rspec
```<code>Mac OS 10.4
rspec (1.1.11, 1.1.4, 1.1.3, 0.5.15)
rspec-rails (1.1.11)
rspec_generator (0.5.15)
rails 2.2.2
ruby 1.8.6 (2007-03-13 patchlevel 0) [universal-darwin8.0]
</code>```

Created a new project...

```<code>$ rails myproject
</code>```

Installed rspec into the project...

```<code>$ script/generate rspec
</code>```

Generated a resource...

```<code>$ script/generate rspec_scaffold myresource name:string description:text
</code>```

Tried to run specs...

```<code>$ rake spec
</code>```

Got this error:

```<code>/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- ./spec/models/../../vendor/generators/rspec/lib/rspec_on_rails (MissingSourceFile)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:155:in `require'
        from ./spec/models/../spec_helper.rb:3
        from ./spec/models/entry_spec.rb:1:in `require'
        from ./spec/models/entry_spec.rb:1
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `each'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/options.rb:98:in `run_examples'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/command_line.rb:10:in `run'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/bin/spec:4
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- /Users/ethan/project/project/spec/../vendor/generators/rspec/lib/rspec_on_rails (MissingSourceFile)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:155:in `require'
        from /Users/ethan/project/project/spec/spec_helper.rb:3
            from ./spec/controllers/entries_controller_spec.rb:1:in `require'
        from ./spec/controllers/entries_controller_spec.rb:1
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `each'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/options.rb:98:in `run_examples'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/command_line.rb:10:in `run'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/bin/spec:4
</code>```

Indeed, there is no such file...

vendor/generators, ls:

```<code>rspec_controller        rspec_model
</code>```

答:
For rails3

To get the list

```<code>$ rails generate
</code>```

To generate spec_helper.rb

```<code>$ rails g rspec:install
</code>```

OwnerDisplayName: Ethan

Body:
Mac OS 10.4
rspec (1.1.11, 1.1.4, 1.1.3, 0.5.15)
rspec-rails (1.1.11)
rspec_generator (0.5.15)
rails 2.2.2
ruby 1.8.6 (2007-03-13 patchlevel 0) [universal-darwin8.0]

Created a new project...

$ rails myproject

Installed rspec into the project...

$ script/generate rspec

Generated a resource...

$ script/generate rspec_scaffold myresource name:string description:text

Tried to run specs...

$ rake spec

Got this error:

/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- ./spec/models/../../vendor/generators/rspec/lib/rspec_on_rails (MissingSourceFile)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:155:in `require'
        from ./spec/models/../spec_helper.rb:3
        from ./spec/models/entry_spec.rb:1:in `require'
        from ./spec/models/entry_spec.rb:1
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `each'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/options.rb:98:in `run_examples'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/command_line.rb:10:in `run'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/bin/spec:4
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- /Users/ethan/project/project/spec/../vendor/generators/rspec/lib/rspec_on_rails (MissingSourceFile)
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:155:in `require'
        from /Users/ethan/project/project/spec/spec_helper.rb:3
            from ./spec/controllers/entries_controller_spec.rb:1:in `require'
        from ./spec/controllers/entries_controller_spec.rb:1
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:14:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `each'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/example_group_runner.rb:13:in `load_files'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/options.rb:98:in `run_examples'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/lib/spec/runner/command_line.rb:10:in `run'
        from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.1.11/bin/spec:4

Indeed, there is no such file...

vendor/generators, ls:

rspec_controller        rspec_model

LastEditorDisplayName: Ethan

Body:
For rails3

To get the list

$ rails generate

To generate spec_helper.rb

$ rails g rspec:install


问:
Running .jar file using Apache POI in Maven project
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>
</code>```

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

```<code>public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}
</code>```

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

```<code>java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App
</code>```

...and I get the following error message

```<code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
</code>```

If this question requires any more information let me know. I'm at a loss here.

答:
You are packaging your maven artifact as a jar and by default a jar packaged by the maven jar plugin doesn't include the dependency jars with the built artifact.
Whereas the missing class at runtime.

If you want to include dependency jars of your application inside your jar, you should use the maven assembly plugin and specify  jar-with-dependencies for the descriptorRef parameter.

You could bind the assembly singlegoal execution to the package phase so that the mvn package execution that you are using actually creates automatically the expected jar.

```<code><plugins>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <mainClass>YourMainClassPrefixedByItsPackage</mainClass>
        </manifest>
      </archive>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
    <executions>
      <execution>
        <id>make-assembly</id>
        <phase>package</phase> <!-- bind to the packaging phase -->
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</code>```

Body:
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App

...and I get the following error message

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

If this question requires any more information let me know. I'm at a loss here.

Body:
You are packaging your maven artifact as a jar and by default a jar packaged by the maven jar plugin doesn't include the dependency jars with the built artifact.
Whereas the missing class at runtime.

If you want to include dependency jars of your application inside your jar, you should use the maven assembly plugin and specify  jar-with-dependencies for the descriptorRef parameter.

You could bind the assembly singlegoal execution to the package phase so that the mvn package execution that you are using actually creates automatically the expected jar.

<plugins>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <mainClass>YourMainClassPrefixedByItsPackage</mainClass>
        </manifest>
      </archive>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
    <executions>
      <execution>
        <id>make-assembly</id>
        <phase>package</phase> <!-- bind to the packaging phase -->
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>


问:
Mobile Safari on iPhone/iPod CSS hack
Does anyone know a good modern CSS hack to target only mobile safari on iPhone and iPod Touch?

I keep seeing @media screen and (max-device-width: 480px), but that's from 3 years ago and matches Nexus S among others now.

(This is to fix a subtle layout issue. I realise browser sniffing is evil etc.)

答:
If you just need to target Safari on mobiles, just add a media query to this hack:

```<code>@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding: 10px; //or any property you need
    }
}
</code>```

And don't forget to add the .safari_only class to the element you want to target, example:

```<code><div class='safari_only'> This div will have a padding:10px in a mobile with Safari  </div>
</code>```

One detail: this is gonna affect also the Safari browser in Android devices but... anyway who use Safari in an Android device :)

Title: Mobile Safari on iPhone/iPod CSS hack

Body:
If you just need to target Safari on mobiles, just add a media query to this hack:

@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding: 10px; //or any property you need
    }
}

And don't forget to add the .safari_only class to the element you want to target, example:

<div class='safari_only'> This div will have a padding:10px in a mobile with Safari  </div>

One detail: this is gonna affect also the Safari browser in Android devices but... anyway who use Safari in an Android device :)


问:
BroadcastReceiver detects two calls when only one call is made
I have made a Service class and inside that class I have made my BroadcastReceiver which is as follows:

```<code>final BroadcastReceiver receiver = new BroadcastReceiver() {
            private ITelephony telephonyService;
            public void onReceive(Context context, Intent intent) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                try {
                    //Call Rejection
                    Class c = Class.forName(tm.getClass().getName());
                    Method m = c.getDeclaredMethod("getITelephony");
                    m.setAccessible(true);
                    ITelephony telephonyService = (ITelephony) m.invoke(tm);
                    Bundle bundle = intent.getExtras();
                    String phoneNumber = bundle.getString("incoming_number");
                    telephonyService.silenceRinger();
                    telephonyService.endCall();

                    //Checking if number is in contact list
                    String name=findNameByNumber(phoneNumber);
                    if(name.equals("Not Found"))
                    {
                        //Name Not Found
                    }
                    else
                    {
                        //name Found
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
</code>```

findNameByNumber checks if the number is present in my contact list:

```<code>private String findNameByNumber(String incomingNumber) {
        String res = "Not Found";
        try {
            ContentResolver resolver = getApplicationContext().getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incomingNumber));
            Cursor c = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

            if (c != null) {
                if (c.moveToFirst()) {
                    res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                }
                c.close();
            }
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_SHORT).show();
        }
        return res;
    }
</code>```

This is how my IntentFilter object, for using the receiver in the Service class looks like:

```<code>IntentFilter filter = new IntentFilter();
        filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        registerReceiver(receiver,filter);
</code>```

However, when one call comes, it is detected as two calls and not one. How can I solve this?

答:
Read from the intent to get the call state

There are two state changes involved here:
once is from idle to ringing
other is from ringing to idle

```<code>String phoneState = intent.getStringExtra(Phone.STATE_KEY);
                mPhoneState = (Phone.State) Enum.valueOf(
                        Phone.State.class, phoneState);

public class PhoneState extends PhoneStateListener {

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            //Some Action
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            //Some Action
            break;
        //case TelephonyManager.ANOTHER_STATE: ...
    }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have made a Service class and inside that class I have made my BroadcastReceiver which is as follows:

final BroadcastReceiver receiver = new BroadcastReceiver() {
            private ITelephony telephonyService;
            public void onReceive(Context context, Intent intent) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                try {
                    //Call Rejection
                    Class c = Class.forName(tm.getClass().getName());
                    Method m = c.getDeclaredMethod("getITelephony");
                    m.setAccessible(true);
                    ITelephony telephonyService = (ITelephony) m.invoke(tm);
                    Bundle bundle = intent.getExtras();
                    String phoneNumber = bundle.getString("incoming_number");
                    telephonyService.silenceRinger();
                    telephonyService.endCall();

                    //Checking if number is in contact list
                    String name=findNameByNumber(phoneNumber);
                    if(name.equals("Not Found"))
                    {
                        //Name Not Found
                    }
                    else
                    {
                        //name Found
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

findNameByNumber checks if the number is present in my contact list:

private String findNameByNumber(String incomingNumber) {
        String res = "Not Found";
        try {
            ContentResolver resolver = getApplicationContext().getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incomingNumber));
            Cursor c = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

            if (c != null) {
                if (c.moveToFirst()) {
                    res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                }
                c.close();
            }
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_SHORT).show();
        }
        return res;
    }

This is how my IntentFilter object, for using the receiver in the Service class looks like:

IntentFilter filter = new IntentFilter();
        filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        registerReceiver(receiver,filter);

However, when one call comes, it is detected as two calls and not one. How can I solve this?

Body:
Read from the intent to get the call state

There are two state changes involved here:
once is from idle to ringing
other is from ringing to idle

String phoneState = intent.getStringExtra(Phone.STATE_KEY);
                mPhoneState = (Phone.State) Enum.valueOf(
                        Phone.State.class, phoneState);

public class PhoneState extends PhoneStateListener {

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            //Some Action
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            //Some Action
            break;
        //case TelephonyManager.ANOTHER_STATE: ...
    }
    }
}


问:
get_categories order by last post
What is the best and shortest way in Wordpress to get_categories ordered by last posted article?

Means that categories with recent posts should appear first, is it available somehow?

答:
I think the easiest way would be to loop through all of your posts ordered by post_date and then save the categories to an array. You can then loop through the categories and display them. They will be in order.

Something like this:

```<code><?php

// Initiate array
$cats = array();

// Query arguments
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'orderby' = 'post_date'.
    'order' => 'DESC'
);

// The query
$query = new WP_Query($args);

// The loop
if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();

        // Get the term object
        $term = get_the_category();

        // Make sure the term doesn't already exist in the array
        if(!array_key_exists($term[0]->ID, $cats)) {
            // Add the terms to the array
            $cats[$term[0]->ID] = $term;
        }
    }
}

foreach($cats as $cid => $cat) {
    // Loop through the categories here
}
?>
</code>```

Of course, as mentioned in the comment above you could also do it the other way around and loop through the categories first then sort the array. Something like this could do:

```<code><?php

// Initiate array
$cats = get_categories();
$recent_cats = array();

foreach($cats as $k => $cat) {
    // Query arguments
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 1,
        'orderby' = 'post_date'.
        'order' => 'DESC',
        'cat' => $cat->term_id
    );

    // The query
    $query = new WP_Query($args);

    // The loop
    if($query->have_posts()) {
        while($query->have_posts()) {
            $query->the_post();
            $date_str = strtotime(the_date());
            if(!array_key_exists($date_str, $recent_cats)) {
                $recent_cats[$date_str] = $cat->name;
            }
        }
    }
}

krsort($recent_cats);

// Loop through $recent_cats here

?>
</code>```

Title: get_categories order by last post

Body:
I think the easiest way would be to loop through all of your posts ordered by post_date and then save the categories to an array. You can then loop through the categories and display them. They will be in order.

Something like this:

<?php

// Initiate array
$cats = array();

// Query arguments
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'orderby' = 'post_date'.
    'order' => 'DESC'
);

// The query
$query = new WP_Query($args);

// The loop
if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();

        // Get the term object
        $term = get_the_category();

        // Make sure the term doesn't already exist in the array
        if(!array_key_exists($term[0]->ID, $cats)) {
            // Add the terms to the array
            $cats[$term[0]->ID] = $term;
        }
    }
}

foreach($cats as $cid => $cat) {
    // Loop through the categories here
}
?>

Of course, as mentioned in the comment above you could also do it the other way around and loop through the categories first then sort the array. Something like this could do:

<?php

// Initiate array
$cats = get_categories();
$recent_cats = array();

foreach($cats as $k => $cat) {
    // Query arguments
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 1,
        'orderby' = 'post_date'.
        'order' => 'DESC',
        'cat' => $cat->term_id
    );

    // The query
    $query = new WP_Query($args);

    // The loop
    if($query->have_posts()) {
        while($query->have_posts()) {
            $query->the_post();
            $date_str = strtotime(the_date());
            if(!array_key_exists($date_str, $recent_cats)) {
                $recent_cats[$date_str] = $cat->name;
            }
        }
    }
}

krsort($recent_cats);

// Loop through $recent_cats here

?>


问:
Given path not supported error message when reading text files from folder
I have a log in page and I'm trying to get the form to read what's in the textbox + ".txt" so that it opens the corresponding page. I've managed to first check to see if it exists but then the second part doesn't work - the error message given path is not supported comes up at filePath + ".txt"

See code below:

```<code>public bool check_user(string pUsername)
{
    //checks first to see if user exists

    using (StreamReader sr = new StreamReader(pUsername + ".txt"))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            //read first bit of data from text file eg username, data split by ";"
            string[] data = line.Split(';');
            if (data[0] == pUsername)
            {
                MessageBox.Show("User found");
                return true;
            }
        }

        MessageBox.Show("User not found, try again");

        return false;
    }

}

private void btnLogin_Click(object sender, EventArgs e)
{
    //Read from file
    if (check_user(txtUsername.Text.Trim()))
    {

        string filePath = txtUsername + ".txt";
        using (StreamReader sr = new StreamReader(filePath + ".txt"))

        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                //read first bit of data from text file eg username, data split by ";"
                string[] data = line.Split(';');
                if (data[0] == txtUsername.Text.Trim())
                {
                    break;
                }

            }

            // read second bit of data from text file eg password, data split by ";"
            string[] user = line.Split(';');
            if (user[1] == txtPassword.Text.Trim())
            {
                // checks access levels by viewing the third part of data and corresponds to which form to open
                if (user[2] == "employee")
                {
                    EmployeeForm frm = new EmployeeForm();
                    frm.Show();

                }
                else if (user[2] == "admin")
                {
                    AdminForm frm = new AdminForm();
                    frm.Show();

                }
            }
            else
            {
                MessageBox.Show("Login not successful, try again", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
    }
}
</code>```

答:
First you do this:

```<code>check_user(txtUsername.Text.Trim())
</code>```

Indicating that txtUsername is some kind of control which has Text property. Two lines below you do:

```<code>string filePath = txtUsername + ".txt";
</code>```

This is equivalent of

```<code>string filePath = txtUsername.ToString() + ".txt";
</code>```

And because txtUsername is not string but some control that has Text property - you end up with invalid path. Change that to:

```<code>string filePath = txtUsername.Text.Trim() + ".txt";
</code>```

Body:
I have a log in page and I'm trying to get the form to read what's in the textbox + ".txt" so that it opens the corresponding page. I've managed to first check to see if it exists but then the second part doesn't work - the error message given path is not supported comes up at filePath + ".txt"

See code below:

public bool check_user(string pUsername)
{
    //checks first to see if user exists

    using (StreamReader sr = new StreamReader(pUsername + ".txt"))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            //read first bit of data from text file eg username, data split by ";"
            string[] data = line.Split(';');
            if (data[0] == pUsername)
            {
                MessageBox.Show("User found");
                return true;
            }
        }

        MessageBox.Show("User not found, try again");

        return false;
    }

}

private void btnLogin_Click(object sender, EventArgs e)
{
    //Read from file
    if (check_user(txtUsername.Text.Trim()))
    {

        string filePath = txtUsername + ".txt";
        using (StreamReader sr = new StreamReader(filePath + ".txt"))

        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                //read first bit of data from text file eg username, data split by ";"
                string[] data = line.Split(';');
                if (data[0] == txtUsername.Text.Trim())
                {
                    break;
                }

            }

            // read second bit of data from text file eg password, data split by ";"
            string[] user = line.Split(';');
            if (user[1] == txtPassword.Text.Trim())
            {
                // checks access levels by viewing the third part of data and corresponds to which form to open
                if (user[2] == "employee")
                {
                    EmployeeForm frm = new EmployeeForm();
                    frm.Show();

                }
                else if (user[2] == "admin")
                {
                    AdminForm frm = new AdminForm();
                    frm.Show();

                }
            }
            else
            {
                MessageBox.Show("Login not successful, try again", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
    }
}

Body:
First you do this:

check_user(txtUsername.Text.Trim())

Indicating that txtUsername is some kind of control which has Text property. Two lines below you do:

string filePath = txtUsername + ".txt";

This is equivalent of

string filePath = txtUsername.ToString() + ".txt";

And because txtUsername is not string but some control that has Text property - you end up with invalid path. Change that to:

string filePath = txtUsername.Text.Trim() + ".txt";


问:
Is there a way to get what is clicked in any windows?
I managed to get the position (x,y) of mousse clicked event in windows with C# and Win32 API from the code at http://www.codeproject.com/KB/cs/globalhook.aspx (using Version 1 because I have a problem with version 2)
But I want to know what is clicked not the position on the screen.
For example, click the "Bold Button" in MS Word.
Is there a way to archive this?

Thanks in advance.

答: You can fetch a window handle from WindowFromPoint or ChildWindowFromPointEx, then query the window handle with GetWindowInfo etc. I don't think there's a trivial way to identify a button from Word, though.</p>


问:
How to kill process inside container? Docker top command
I have simple example from official guide at docker website.

I run the following:

```<code>sudo docker run -d ubuntu:latest /bin/sh -c "while true; do echo hello world; sleep 1; done"
a66asdasdhqie123...
</code>```

Then take some output from created container:

```<code>sudo docker logs a66
hello
hello
hello
...
</code>```

Then I lookup the running processes of a container:

```<code>sudo docker top a66
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                25055               15152               0                   20:07               ?                   00:00:00            /bin/sh -c while true; do echo hello world; sleep 1; done
root                25295               25055               0                   20:10               ?                   00:00:00            sleep 1
</code>```

Next I try to kill the first process of container:

```<code>sudo docker exec a66 kill -9 25055
</code>```

However after I make it nothing changes. Process still works and output "hello" every second. What do I wrong?

答:
i was looking for something like this, but i couldn't find and then i did this:

[root@notebook ~]# docker exec -it tadeu_debian ps aux | grep ping |
  awk '{ print $2 }' | xargs -I{} docker exec -i tadeu_debian kill -9

It was two "execs" from Docker e one xargs.

Well, i hope this helps someone!

Body:
I have simple example from official guide at docker website.

I run the following:

sudo docker run -d ubuntu:latest /bin/sh -c "while true; do echo hello world; sleep 1; done"
a66asdasdhqie123...

Then take some output from created container:

sudo docker logs a66
hello
hello
hello
...

Then I lookup the running processes of a container:

sudo docker top a66
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                25055               15152               0                   20:07               ?                   00:00:00            /bin/sh -c while true; do echo hello world; sleep 1; done
root                25295               25055               0                   20:10               ?                   00:00:00            sleep 1

Next I try to kill the first process of container:

sudo docker exec a66 kill -9 25055

However after I make it nothing changes. Process still works and output "hello" every second. What do I wrong?


问:
Dagger 2 multibindings with Kotlin
I have the following snippet in my dagger 2 module

```<code>@Singleton
@Provides
@ElementsIntoSet
fun providesQueries(foo: Foo): Set<Foo>{
    val queries = LinkedHashSet<Foo>()
    queries.add(foo)
    return queries
}
</code>```

I try to inject into in this way

```<code>@Inject lateinit var foo: Set<Foo>
</code>```

But dagger shows an error which says that Dagger cannot provides java.util.Set without @Provides or @Produces method.

I did the same in java and it worked. Does somebody know why is it failing?

答:
As it described in the Kotlin reference

To make Kotlin APIs work in Java we generate Box<Super> as
  Box<? extends Super> for covariantly defined Box (or Foo<? super Bar> for
  contravariantly defined Foo) when it appears as a parameter.

You can use @JvmSuppressWildcards for avoiding it, just as following:

```<code>@Inject lateinit var foo: Set<@JvmSuppressWildcards Foo>
</code>```

Title: Dagger 2 multibindings with Kotlin

Body:
I have the following snippet in my dagger 2 module

@Singleton
@Provides
@ElementsIntoSet
fun providesQueries(foo: Foo): Set<Foo>{
    val queries = LinkedHashSet<Foo>()
    queries.add(foo)
    return queries
}

I try to inject into in this way

@Inject lateinit var foo: Set<Foo>

But dagger shows an error which says that Dagger cannot provides java.util.Set without @Provides or @Produces method.

I did the same in java and it worked. Does somebody know why is it failing?

Body:
As it described in the Kotlin reference

To make Kotlin APIs work in Java we generate Box<Super> as
  Box<? extends Super> for covariantly defined Box (or Foo<? super Bar> for
  contravariantly defined Foo) when it appears as a parameter.

You can use @JvmSuppressWildcards for avoiding it, just as following:

@Inject lateinit var foo: Set<@JvmSuppressWildcards Foo>


问:
Substitute everything but letters
I am trying to write a single line bash command that will replace every single not letter into a newline. (I am using bash)

Right now, I have this: tr ^[a-zA-Z]g '\n'

I have also tried tr [^a-zA-Z]g '\n' Both don't work.

I thought that the ^ character would have the regular expression match everything but a-z and A-Z, and thus turn all other characters into newlines, but instead it still jus turns a-z and A-Z into newlines, and keeps the other characters.

How can I make sure that I am using the ^ to reverse the regex, instead of anchor it to the beginning of the line?

Does anyone know the correct syntax? Or should I try using a different command? Thanks.

答:
tr does not support regex.

You can use:

```<code>tr -c 'a-zA-Z' '\n'
</code>```

Title: Substitute everything but letters

Body:
tr does not support regex.

You can use:

tr -c 'a-zA-Z' '\n'


问:
Adding Totals to a Table According to Parameters in PHP
I have this code to show a table in PHP:

```<code><?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }

      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

    //  exit;

      $body = '';
      $body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
      $body .= '<thead style="background-color:#f3f4f5;">';
      $body .= '<tr>';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }else{
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }
        }
      }
      $body .= '</tr>';
      $body .= '</thead>';
      $body .= '<tbody>';

      for ($k=0; $k < count($harvest); $k++) {
        for ($a=0; $a < count($harvest[$k]) ; $a++) {
          $body .= '<tr>';
          for ($i=0; $i < count($arrayThead) ; $i++) {
            for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
              if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
                $body .= '<td style="border: 1px solid black;font-size:12px;">'.$harvest[$k][$a][$arrayThead[$i][$j]].'</td>';
              }else{
                $body .= '<td style="border: 1px solid black; text-align:right;font-size:12px;">'.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'</td>';
              }
            }
          }
          $body .= '</tr>';
          foreach ($totalByProduct as $key => $value) {
            if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
              $body .= '<tr>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;">TOTAL '.$value["PRODUCT"].'</th>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;"></th>';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $body .= '<th style="border: 1px solid black;text-align:right;font-size:12px;">'.number_format($value[$th]).'</th>';
                  }
                }
              }
              $body .= '</tr>';
            }
          }
        }
      }

      $body .= '</tbody>';
      $body .= '<tfoot>';
      $body .= '<tr>';
      $body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
      $body .= '<th style="border: 1px solid black;"></th>';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= '<th style="border: 1px solid black;text-align:right;">'.number_format($arrayFinal[$i]).'</th>';
      }

      $body .= '</tr>';
      $body .= '</tfoot>';
      $body .= '</table>';

      echo $body;
</code>```

I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.

If you want to see how the code works you can copy the code and past in this page: PHPTESTER

I need to show the table something like this:

```<code>-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GOLD    |  NORMAL |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ADELE     |  160     |  0      |     160        |
-------------------------------------------------------------------
   ROSE       |   ALESSO    |  1320    |  550    |    1870        |
-------------------------------------------------------------------
   ROSE       |  ANASTACIA  |  440     |    150  |  590           |
-------------------------------------------------------------------
   TOTAL ROSE |             |  1920    |  700    |  2620          |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  420     |  120    |  540           |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  440     |    100  |  540           |
-------------------------------------------------------------------
 TOTAL ROSE1  |             |  860     |  220    |  1080          |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  640     |    0    |  640           |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  440     |    440  |  880           |
-------------------------------------------------------------------
  TOTAL ROSE2 |             |  1080    |  440    |  1520          |
-------------------------------------------------------------------
 TOTAL GENERAL|             |  3860    |  1360   |  5220          |
-------------------------------------------------------------------
</code>```

I hope that someone can help me thanks!

答:
```<code><?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$prods = array();
$prevprod = "";
$total_gold = 0;
$total_normal = 0;
$total_prod = 0;
$total = 0;

foreach($harvest[0] as $key => $val){

    $pos = $key;
    $obj = $val;

    $total_prod = $obj["GOLD"]+$obj["NORMAL"];
    if($obj["PRODUCT"]==$prevprod || $prevprod==""){
        $prods[] = array($obj["PRODUCT"],$obj["VARIETY"],$obj["GOLD"],$obj["NORMAL"],$obj["TOTAL"]);
        $total_gold = $total_gold + $obj["GOLD"];
        $total_normal = $total_normal + $obj["NORMAL"];
        $total_prod = $total_prod + $obj["TOTAL"];
        $total = $total + $total_prod;
    }else{
        $prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);
        $total_gold = 0;
        $total_normal = 0;
        $total_prod = 0;
    }

    $prevprod = $obj["PRODUCT"];
}
$prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);

    //  exit;

      $body = '';
      $body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
      $body .= '<thead style="background-color:#f3f4f5;">';
      $body .= '<tr>';

      $body .= '<th>PRODUCT</th><th>VARIETY</th><th>GOLD</th><th>NORMAL</th><th>TOTAL</th>';
      $body .= '</tr>';
      $body .= '</thead>';
      $body .= '<tbody>';

      foreach($prods as $p){
        $body .= '<tr><td>'.$p[0].'</td><td>'.$p[1].'</td><td>'.$p[2].'</td><td>'.$p[3].'</td><td>'.$p[4].'</td><tr>';
      }

      $body .= '</tbody>';
      $body .= '<tfoot>';
      $body .= '<tr>';
      $body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
      $body .= '<th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th>';

      $body .= '<th>'.$total.'</th>';
      $body .= '</tr>';
      $body .= '</tfoot>';
      $body .= '</table>';

      echo $body;
</code>```

Body:
I have this code to show a table in PHP:

<?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }

      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

    //  exit;

      $body = '';
      $body .= '
';
      $body .= '
';
      $body .= '
';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= ''.$arrayThead[$i][$j].'	';
          }else{
            $body .= ''.$arrayThead[$i][$j].'	';
          }
        }
      }
      $body .= '
';
      $body .= '
';
      $body .= '
';

      for ($k=0; $k < count($harvest); $k++) {
        for ($a=0; $a < count($harvest[$k]) ; $a++) {
          $body .= '
';
          for ($i=0; $i < count($arrayThead) ; $i++) {
            for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
              if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
                $body .= ''.$harvest[$k][$a][$arrayThead[$i][$j]].'	';
              }else{
                $body .= ''.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'	';
              }
            }
          }
          $body .= '
';
          foreach ($totalByProduct as $key => $value) {
            if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
              $body .= '
';
              $body .= 'TOTAL '.$value["PRODUCT"].'	';
              $body .= '	';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $body .= ''.number_format($value[$th]).'	';
                  }
                }
              }
              $body .= '
';
            }
          }
        }
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';
      $body .= 'TOTAL GENERAL	';
      $body .= '	';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= ''.number_format($arrayFinal[$i]).'	';
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';

      echo $body;

I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.

If you want to see how the code works you can copy the code and past in this page: PHPTESTER

I need to show the table something like this:

-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GOLD    |  NORMAL |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ADELE     |  160     |  0      |     160        |
-------------------------------------------------------------------
   ROSE       |   ALESSO    |  1320    |  550    |    1870        |
-------------------------------------------------------------------
   ROSE       |  ANASTACIA  |  440     |    150  |  590           |
-------------------------------------------------------------------
   TOTAL ROSE |             |  1920    |  700    |  2620          |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  420     |  120    |  540           |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  440     |    100  |  540           |
-------------------------------------------------------------------
 TOTAL ROSE1  |             |  860     |  220    |  1080          |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  640     |    0    |  640           |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  440     |    440  |  880           |
-------------------------------------------------------------------
  TOTAL ROSE2 |             |  1080    |  440    |  1520          |
-------------------------------------------------------------------
 TOTAL GENERAL|             |  3860    |  1360   |  5220          |
-------------------------------------------------------------------

I hope that someone can help me thanks!


问:
sorting and load balancing
I read about parallel quicksort ( but no load balancing ).
who can give good algorithm for using on 2, 4, 8 cores?</p>

答: This will give insight http://sortbenchmark.org/</p>

Title: sorting and load balancing


问:
Error during SonarQube Scanner execution from Jenkins plugin
I get the following error when I try to execute SonarQube Scanner as a part of Jenkins build:

```<code>ERROR: SonarQube server [http://<hostname>:9000] can not be reached

INFO: ------------------------------------------------------------------------

INFO: EXECUTION FAILURE

INFO: ------------------------------------------------------------------------

INFO: Total time: 0.242s

INFO: Final Memory: 5M/483M

INFO: ------------------------------------------------------------------------

ERROR: Error during SonarQube Scanner execution

org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarQube

at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:84)

at
... 8 more

Caused by: java.lang.IllegalStateException: Status returned by
 url [http://<hostname>:9000/batch/index] is not valid: [404]

at org.sonarsource.scanner.api.internal.ServerConnection.callUrl(ServerConnection.java:115)

at org.sonarsource.scanner.api.internal.Jars.getBootstrapIndex(Jars.java:96)

... 12 more

ERROR:
</code>```

I can access the following URL from my Jenkins host: http://:9000/sonar/ . When I try to execute this:

```<code>wget http://<hostname>:9000/batch/index
</code>```

I get the same 404 http error in response. I have no idea from where this URL postfix /batch/index comes from. Web search did not give any clues for this.

My Sonar version is 6.0. My Jenkins Sonar Scanner plugin version is 2.6.1.

Used JVM:

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

答:
What is your the setting for sonar's web context (sonar.web.context) on your sonar server? It would be inside of sonar.properties. By default both the Jenkins plugin and the sonar server configuration set it to root:

```<code>'http://<hostname>:9000/'
</code>```

The first thing I would do is to make sure those are matching in the sonar configuration and the jenkins plugin configuration.

I've seen tutorials that tell you to use /sonar or something similar. In that case, the jenkins plugin would need to be set to /sonar as well, like:

```<code>'http://<hostname>:9000/sonar'
</code>```

Body:
I get the following error when I try to execute SonarQube Scanner as a part of Jenkins build:

ERROR: SonarQube server [http://<hostname>:9000] can not be reached

INFO: ------------------------------------------------------------------------

INFO: EXECUTION FAILURE

INFO: ------------------------------------------------------------------------

INFO: Total time: 0.242s

INFO: Final Memory: 5M/483M

INFO: ------------------------------------------------------------------------

ERROR: Error during SonarQube Scanner execution

org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarQube

at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory$1.run(IsolatedLauncherFactory.java:84)

at
... 8 more

Caused by: java.lang.IllegalStateException: Status returned by
 url [http://<hostname>:9000/batch/index] is not valid: [404]

at org.sonarsource.scanner.api.internal.ServerConnection.callUrl(ServerConnection.java:115)

at org.sonarsource.scanner.api.internal.Jars.getBootstrapIndex(Jars.java:96)

... 12 more

ERROR:

I can access the following URL from my Jenkins host: http://:9000/sonar/ . When I try to execute this:

wget http://<hostname>:9000/batch/index

I get the same 404 http error in response. I have no idea from where this URL postfix /batch/index comes from. Web search did not give any clues for this.

My Sonar version is 6.0. My Jenkins Sonar Scanner plugin version is 2.6.1.

Used JVM:

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Body:
What is your the setting for sonar's web context (sonar.web.context) on your sonar server? It would be inside of sonar.properties. By default both the Jenkins plugin and the sonar server configuration set it to root:

'http://<hostname>:9000/'

The first thing I would do is to make sure those are matching in the sonar configuration and the jenkins plugin configuration.

I've seen tutorials that tell you to use /sonar or something similar. In that case, the jenkins plugin would need to be set to /sonar as well, like:

'http://<hostname>:9000/sonar'


问:
using beginBackgroundTaskWithExpirationHandler for upload
From the doc it looks like uploading a file is a good use case for using beginBackgroundTaskWithExpirationHandler. I've found that using

```<code>let uploadTask = session.uploadTask(with: request as URLRequest, fromFile: file)
uploadTask.resume()
</code>```

will already run while the app is backgrounded (I'm getting upload progress pings for a while). Additionally I can set the URLSession to be backgrounded:

```<code>let config = URLSessionConfiguration.background(withIdentifier: "uploads")
session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
</code>```

So what is the advantage of using beginBackgroundTaskWithExpirationHandler ? Will it extend the time I've to finish my upload? If so can I know by how much (didn't see anything about this in the doc)? Or is it just that I'll get pinged before the app stops? Should I use it in combination with a background URLSession?

Additionally the docs says that the handler will be called shortly before the app’s remaining background time reaches 0 Does it mean that the app will be terminated after that? ie can I assume that the next call will be application:didFinishLaunchingWithOptions or can it be applicationDidBecomeActive ?

答:
So what is the advantage of using beginBackgroundTaskWithExpirationHandler ?

If you are going to use URLSessionConfiguration.background, there is no such advantage and you should not use beginBackgroundTask(expirationHandler:) at all. Your entire premise (your very first sentence) was wrong. Uploading a file is not a good use case for beginBackgroundTask(expirationHandler:). It's a good use case for URLSessionConfiguration.background. The two things have nothing to do with each other.

Body:
From the doc it looks like uploading a file is a good use case for using beginBackgroundTaskWithExpirationHandler. I've found that using

let uploadTask = session.uploadTask(with: request as URLRequest, fromFile: file)
uploadTask.resume()

will already run while the app is backgrounded (I'm getting upload progress pings for a while). Additionally I can set the URLSession to be backgrounded:

let config = URLSessionConfiguration.background(withIdentifier: "uploads")
session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

So what is the advantage of using beginBackgroundTaskWithExpirationHandler ? Will it extend the time I've to finish my upload? If so can I know by how much (didn't see anything about this in the doc)? Or is it just that I'll get pinged before the app stops? Should I use it in combination with a background URLSession?

Additionally the docs says that the handler will be called shortly before the app’s remaining background time reaches 0 Does it mean that the app will be terminated after that? ie can I assume that the next call will be application:didFinishLaunchingWithOptions or can it be applicationDidBecomeActive ?


问:
StoreKit Sandbox Purchase Fails with "Confirm your IAP" Dialog ("Cannot connect to iTunes Store" code 0)
UPDATE: The issue resolved itself. It looks like it was a problem on Apple's end.

I am trying to test my implementation of In-App Purchases with StoreKit:

Using an actual device,

With multiple sandbox accounts created on iTunes Connect, after having signed out of my actual account on the App Store on my iOS device,

With a non-consumable product.

However, I am getting a bizarre error; the transaction fails right after though the App Store "Confirm your IAP" alert shows up. Here is a synopsis after hours of debugging:

In viewDidLoad, I add the view controller instance (self) as an observer to the SKPaymentQueue, and start a SKProductsRequest, again setting its delegate to self.

In productsRequest(_:didReceive:), I store the SKProduct object in the view controller. UI updates as necessary.

The user taps a button which purchases the product, by instantiating an SKPayment object and adding it to the SKPaymentQueue.

paymentQueue(_:updatedTransactions:) receives a transaction object with transactionState as .purchasing. All good so far.

The App Store dialog pops up and asks the user to sign in to iTunes, and then to "Confirm your IAP [Environment: Sandbox]".

Immediately after the latter dialog pops up, with no user input, paymentQueue(_:updatedTransactions:) receives a transaction object with transactionState as .failed. The error property indicates that the device "Cannot connect to iTunes Store" with an error code of 0.

I have tried doing the same with fresh iTunes Connect Sandbox accounts and on multiple devices, but the results are always the same. What should I do?

The IAP on iTunes Connect is marked "Ready To Submit", so I don't think it's because I didn't configure it correctly on ITC.

Simplified Gist

Edit: To elaborate, IAPs worked before. I tried running previous versions of my code, when it used to work, but the same error occurs.

答:
It's not you. There are dozens of other developers who are having the same issue right now. Largest list active list of issues is here.

The timing of the problem coincides with the release of iOS 10.3 and XCode 8.3. Along with Apple Pay being rolled out in Taiwan. It's an issue with Apple's back end servers. The best we can do is file a bug report and wait.


问:
Reverting a specific old commit
Hi I have a repository on Bitbucket. I am working with a partner on a project and he pushed some updates few commits ago, working on a file, I realized that he did wrong code. I want to revert that commit, particularly that file only so I can get back code of that file only. cartitems.blade.php

Is this possible?

Attached is the image of SourceTree tool. Uncommited changes are my new changes. I want to keep these and recover that specific file only.

答:
Like get rid of the last commit "for good" so that it's like it didn't happen?

Suppose the change is already on your master branch:

git checkout master
git reset --hard HEAD~1
git push origin master

That should be enough.

Title: Reverting a specific old commit


问:
why can i not use break on this code and what can i use instead? python
The task that I am doing is to develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.

```<code>sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")

question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
    sentencetext=sentence.isalpha or sentence.isspace()
    while sentencetext==False: #if letters have not been entered
        print("Only letters are allowed") #error message
        sentence=input("Please enter a sentence").upper() #asks the question again
        sentencetext=sentence.isalpha #checks if letters have been entered this time

    word = sentence.split(' ')
    for (i, check) in enumerate(word): #orders the words
        print(sentence)

        word = input("What word are you looking for?").upper() #asks what word they want
        if (check == word):
            positionofword=print("your word is in this position:", i+1)
            positionofword=str(positionofword)
        else:
            print("this didn't work") #print error message

elif question=="N":
    print("The program will now close")
else:
print("you did not enter one of the prescribed letters")

words.write(word + " ")
position.write(positionofword + " ")
</code>```

The problem for me is that I am stuck in the loop of:

```<code>   word = input("What word are you looking for?").upper() #asks what word they want
    if (check == word):
        positionofword=print("your word is in this position:", i+1)
        positionofword=str(positionofword)
    else:
        print("this didn't work") #print error message
</code>```

Which therefore means that I cannot get the words into the file. I have tried to use break, but that did not work out for me because I could not get the words into the file.

I'm new to this site, but I've been stalking for quite a while. Hopefully this is right, I'm open to hearing criticism if I've worded this wrong.

答:
Your logic in the for loop is incorrect - rather than asking once what the word the user wants to find, you ask that for each word in the sentence, and only match if they enter the word they want when that is the current word being checked. You are also printing the sentence once for each word in the sentence. Restructure it like so:</p>

```<code>print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
    if (check == word):
        print("your word is in this position:", i+1)
        positionofword=i+1
        break
else:
    print("This didn't work")
</code>```

Body:
The task that I am doing is to develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.

sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")

question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
    sentencetext=sentence.isalpha or sentence.isspace()
    while sentencetext==False: #if letters have not been entered
        print("Only letters are allowed") #error message
        sentence=input("Please enter a sentence").upper() #asks the question again
        sentencetext=sentence.isalpha #checks if letters have been entered this time

    word = sentence.split(' ')
    for (i, check) in enumerate(word): #orders the words
        print(sentence)

        word = input("What word are you looking for?").upper() #asks what word they want
        if (check == word):
            positionofword=print("your word is in this position:", i+1)
            positionofword=str(positionofword)
        else:
            print("this didn't work") #print error message

elif question=="N":
    print("The program will now close")
else:
print("you did not enter one of the prescribed letters")

words.write(word + " ")
position.write(positionofword + " ")

The problem for me is that I am stuck in the loop of:

   word = input("What word are you looking for?").upper() #asks what word they want
    if (check == word):
        positionofword=print("your word is in this position:", i+1)
        positionofword=str(positionofword)
    else:
        print("this didn't work") #print error message

Which therefore means that I cannot get the words into the file. I have tried to use break, but that did not work out for me because I could not get the words into the file.

I'm new to this site, but I've been stalking for quite a while. Hopefully this is right, I'm open to hearing criticism if I've worded this wrong.

Body:
Your logic in the for loop is incorrect - rather than asking once what the word the user wants to find, you ask that for each word in the sentence, and only match if they enter the word they want when that is the current word being checked. You are also printing the sentence once for each word in the sentence. Restructure it like so:

print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
    if (check == word):
        print("your word is in this position:", i+1)
        positionofword=i+1
        break
else:
    print("This didn't work")


问:
How to load images with glide dynamically (Android)?
In my android app I pull data from http requests.

In my layout I want to show images dynamically with Glide library.

I get the image urls but I can not find a way to show them in my layout.

In my layout file I have:

```<code>   <LinearLayout
    android:id="@+id/social_media_layout"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="60dp"
    android:gravity="center_vertical">

  </LinearLayout>
</code>```

Somehow I want to add imageviews(dynamically) in my LinearLayout.

For example: If I get 2 image urls from the request I need two imageviews in my linearlayout.

Note: I want to load images with Glide library.

Any idea would be helful.

Thanks.

答:
You should better use ListView or RecycleView . But if you insist on adding them into LinearLayout dynamically, then:

```<code>LinearLayout layout = (LinearLayout)findViewById(R.id.social_media_layout);

// assuming that image_urls_list contains the images urls
for(int i=0;i<image_urls_list.size();i++)
{
    ImageView image = new ImageView(this);

    // set whatever width and height you want to give
    image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100,100));

    // load image using Glide
     Glide.with(context).load(image_urls_list.get(i)).into(image);

    // Adds the view to the layout
    layout.addView(image);
}
</code>```

You might want to add a HorizontalScrollView tag as a parent tag to your LinearLayout so that you can scroll horizontally.

Body:
In my android app I pull data from http requests.

In my layout I want to show images dynamically with Glide library.

I get the image urls but I can not find a way to show them in my layout.

In my layout file I have:

   <LinearLayout
    android:id="@+id/social_media_layout"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="60dp"
    android:gravity="center_vertical">

  </LinearLayout>

Somehow I want to add imageviews(dynamically) in my LinearLayout.

For example: If I get 2 image urls from the request I need two imageviews in my linearlayout.

Note: I want to load images with Glide library.

Any idea would be helful.

Thanks.

Body:
You should better use ListView or RecycleView . But if you insist on adding them into LinearLayout dynamically, then:

LinearLayout layout = (LinearLayout)findViewById(R.id.social_media_layout);

// assuming that image_urls_list contains the images urls
for(int i=0;i<image_urls_list.size();i++)
{
    ImageView image = new ImageView(this);

    // set whatever width and height you want to give
    image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100,100));

    // load image using Glide
     Glide.with(context).load(image_urls_list.get(i)).into(image);

    // Adds the view to the layout
    layout.addView(image);
}

You might want to add a HorizontalScrollView tag as a parent tag to your LinearLayout so that you can scroll horizontally.


问:
Double quote single quote not working in PHP/JavaScript
I can't get my required result when i use this code

```<code><?php
session_start();
$returnMessage = "Hey";
$test = fopen('check.txt', a+);
fwrite($test, '
   if (empty($_SESSION["nabeel"])) {
     echo "<script>alert($returnMessage)</script>";
   };
    ?>    ')
</code>```

I also tried doing this but does work...

```<code><?php
session_start();
$returnMessage = "Hey";
?>
$test = fopen('check.txt', a+);
fwrite($test, '
   if (empty($_SESSION["nabeel"])) {
     echo "<script>alert(<?php $returnMessage ?>)</script>";
   }
    ?>    ')
</code>```

I think I have some problem with quotes.

答:
use this:</p>

```<code><?php
session_start();
$returnMessage = "Hey";
$test = fopen('check.txt', a+);
if (empty($_SESSION["nabeel"]))
    fwrite($test,'<script>alert('. $returnMessage .');</script>');
?>
</code>```

Body:
I can't get my required result when i use this code

<?php
session_start();
$returnMessage = "Hey";
$test = fopen('check.txt', a+);
fwrite($test, '
   if (empty($_SESSION["nabeel"])) {
     echo "";
   };
    ?>    ')

I also tried doing this but does work...

<?php
session_start();
$returnMessage = "Hey";
?>
$test = fopen('check.txt', a+);
fwrite($test, '
   if (empty($_SESSION["nabeel"])) {
     echo "";
   }
    ?>    ')

I think I have some problem with quotes.

Body:
use this:

<?php
session_start();
$returnMessage = "Hey";
$test = fopen('check.txt', a+);
if (empty($_SESSION["nabeel"]))
    fwrite($test,'<script>alert('. $returnMessage .');</script>');
?>


问:
Angular 2 Sibling Component Communication
I have a ListComponent.  When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent.  Both are on the screen at the same time, so there's no routing involved.

How do I tell DetailComponent what item in ListComponent was clicked?

I've considered emitting an event up to the parent (AppComponent), and have the parent set the selectedItem.id on DetailComponent with an @Input.  Or I could use a shared service with observable subscriptions.

EDIT: Setting the selected item via event + @Input doesn't trigger the DetailComponent, though, in case I were to need to execute additional code.  So I'm not sure this is an acceptable solution.

But both of these methods seem far more complex than the Angular 1 way of doing things which was either through $rootScope.$broadcast or $scope.$parent.$broadcast.

With everything in Angular 2 being a component, I'm surprised there's not more information out there about component communication.

Is there another/more straightforward way to accomplish this?

答:
I have been passing down setter methods from the parent to one of its children through a binding, calling that method with the data from the child component, meaning that the parent component is updated and can then update its second child component with the new data. It does require binding 'this' or using an arrow function though.

This has the benefit that the children aren't so coupled to each other as they don't need a specific shared service.

I am not entirely sure that this is best practice, would be interesting to hear others views on this.


问:
Determining BCNF violations
So I have a relation schema with FD's that look like this:

```<code>R(A,B,C,D): AB -> C, B -> D, CD -> A, AD -> B
</code>```

Now I'm trying to find all the BCNF violations and then decompose the tables. I computed the left hand side of all the FD's and found this:

```<code>AB+ = {A, B, C, D}
B+ = {B, D} <- violation
CD+ = {C, D, A, B}
AD+ = {A, D, B, C}
</code>```

So I decompose the table to look like this:

```<code>R1 (B, D)
R2 (A, B, C)
</code>```

The only problem is that I'm not sure if this is all I have to do when it comes to decomposing the tables or if I have to do more. I'm mainly confused about the AB, CD, and AD parts.

答:
In your example, B → D is in effect the only dependency that violates the BCNF, since in all the other depedencies the left hand side is a key (actually all the keys of the relation are  (A D), (A B), (B C) and  (C D)).

So, you can decompose by splitting the original relation R in R1, containing B+, that is BD, and R2, containing R - B+ + B, that is ABC, as you have correctly found.

Then one should apply again this process if in any of the decomposed relation there is some dependency that violates the BCNF. But this is not the case, since the only dependency in R1 is B → D, with B the only key, and with the dependencies AB → C and BC → A in R2, that has keys AB and BC.

At this point can terminate the process since R1 and R2 are both in BCNF. But we should note also that this decomposition does not preserve the dependencies, since CD → A and AD → B have been lost.

Title: Determining BCNF violations

Body:
So I have a relation schema with FD's that look like this:

R(A,B,C,D): AB -> C, B -> D, CD -> A, AD -> B

Now I'm trying to find all the BCNF violations and then decompose the tables. I computed the left hand side of all the FD's and found this:

AB+ = {A, B, C, D}
B+ = {B, D} <- violation
CD+ = {C, D, A, B}
AD+ = {A, D, B, C}

So I decompose the table to look like this:

R1 (B, D)
R2 (A, B, C)

The only problem is that I'm not sure if this is all I have to do when it comes to decomposing the tables or if I have to do more. I'm mainly confused about the AB, CD, and AD parts.