问:
Unix Script Convert CSV into XLSX
I am trying to convert CSV file into XLSX.

I have done successfully in XLS before but when trying to do in XLSX , I keep getting errors.

This is sample script I am trying to execute.

https://github.com/jmcnamara/excel-writer-xlsx/blob/master/examples/a_simple.pl

I have included all these Lib in my script :-
!/usr/bin/perl -w

use lib qw(/Scripts/perl/excel-writer-xlsx-master/lib);

use lib qw(/Scripts/perl/File-Temp-0.19/lib);

use lib qw(/Scripts/perl/Archive-Zip-1.30/lib);

use lib qw(/Scripts/perl/IO-1.25/lib);

use lib qw(/Scripts/perl/Compress-Raw-Zlib-2.069/lib);

Error :-
Can't locate loadable object for module Compress::Raw::Zlib in @INC
Compilation failed in require  /Archive-Zip-1.30/lib/Archive/Zip.pm line 12

XLS working successfully with this package: Spreadsheet-WriteExcel-2.40

Perl XLSX Module downloaded from

http://search.cpan.org/dist/Excel-Writer-XLSX/lib/Excel/Writer/XLSX.pm

答:
You can try with a python script which convert any ff - flat file to required file format. csv2xls.py
Ref link: https://pypi.python.org/pypi/csv2xls/0.4</p>

Title: Unix Script Convert CSV into XLSX


来源: stackexchange

问:
How to use passcode lock scene in my app?
Actually, I building an app which contains local authentication.

My code so far:

```<code>func authenticateUser() {
        let authenticationContext = LAContext()
        var error: NSError?
        let reasonString = "Touch the Touch ID sensor to unlock."

        // Check if the device can evaluate the policy.
        if authenticationContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) {

            authenticationContext.evaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, evalPolicyError) in

                if success {
                    print("success")
                } else {
                    if let evaluateError = error as NSError? {
                        // enter password using system UI
                    }

                }
            })

        } else {
            print("toch id not available")
           // enter password using system UI
        }
    }
</code>```

My problem is I want to use the passcode lock scene when the app doesn't has touch ID or invalid finger print.

Like below Image:

How can I do it?

答: At this point, I am afraid that you cannot access this passcode lock screen into your app, it is related to the iOS itself. You might need to build your own custom view controller to look/behave as the passcode lock scene (with Touch ID). I would suggest to use a library for achieving this, personally, I've tried PasscodeLock and it works fine for me.

ContentLicense: CC BY-SA 3.0

Body:
Actually, I building an app which contains local authentication.

My code so far:

func authenticateUser() {
        let authenticationContext = LAContext()
        var error: NSError?
        let reasonString = "Touch the Touch ID sensor to unlock."

        // Check if the device can evaluate the policy.
        if authenticationContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) {

            authenticationContext.evaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, evalPolicyError) in

                if success {
                    print("success")
                } else {
                    if let evaluateError = error as NSError? {
                        // enter password using system UI
                    }

                }
            })

        } else {
            print("toch id not available")
           // enter password using system UI
        }
    }

My problem is I want to use the passcode lock scene when the app doesn't has touch ID or invalid finger print.

Like below Image:

How can I do it?


问:
artifactory gradle plugin overwrite snapshot versions
I would like to publish artefacts on my local Artifactory instance, with annotated Artifactory metatada, and with a version number based on a time-stamp for SNAPSHOT artefacts versions.

I tried to use the artifactory gradle plugin and the maven-publish plugin for this purpose.

However, it is (as far as I know) not possible to annotate Artifactory metadata while using the maven-publish plugin.

And if I use the artifactory gradle plugin, I get an error "Not enough permissions to overwrite artifact ..." while publishing two different SNAPSHOT versions of a given artefact.

In fact, the artifactoryPublish task tries to overwrite the existent artefact, instead of using a time-stamp.

To be noticed that my Artifactory repository is correctly set-up (Version number is based on a time-stamp). Thus, no errors are raised if I use the maven-publish plugin (the artefacts are published with a time-stamp, and no overwritting is done).

Is someone familiar with these issues?

I used a project example available here:
https://github.com/JFrogDev/project-examples/tree/master/gradle-examples/4/gradle-example-minimal

Which I modified a bit to adapt it to my local configuration.

I am using the following artifactory plugin:
org.jfrog.buildinfo:build-info-extractor-gradle-uber:4.4.14

答: If anyone is facing the same issues, the problem was the repository layout definition. I have to use the maven-2-default layout definition to publish SNAPSHOT artefacts versions with timestamps and artifactory properties.


问:
Updating individual sql databases inside Joomla
My work website is running on Joomla 2.5 (yes, I know it needs to be updated) and recently somehow the virtuemart module was updated, resulting in a slight glitch. Now, when hovering over the Virtuemart button in the back end menu, the dropdown menu is not there, and when I click on the VM button it takes me where I need to go, but there is about 200 lines of text now that needs to be scrolled past before I can access the actual VM menu.

I have a full sql database backup from prior to the update, but I just want to know if I can just roll back the update of the module without affecting the listings within VM? I have a feeling the answer is no, so I have pinpointed anything that has been added since the issue and exported the sql table, but can I execute the full backup and then drop the individual tables in afterwards?

Attached is a pic of the text that has appeared...

Please help.image

答:
Login to your Joomla backend as super administrator.

In the main menu select Site -> Global Configuration, then click on the “Server” tab and look for the Error Reporting parameters (these options should appear in the “Server Settings” group).
Set the Error Reporting setting to “None” and click on “Save” to store the changes.

These steps will no longer see that kind of error


问:
Match substring in string divided by a dot
I have following strings:

```<code>'sample1.sample2'
'sample1.sample2.samaple3'
</code>```

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

```<code>$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
</code>```

works fine only for first case.

答:
Use preg_split() if it has to be a Regex:</p>

```<code>$array = preg_split('/\./', $string);
</code>```

Body:
I have following strings:

'sample1.sample2'
'sample1.sample2.samaple3'

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);

works fine only for first case.

Body:
Use preg_split() if it has to be a Regex:

$array = preg_split('/\./', $string);


问:
Linq Query C# ( Multiple Occurrences in String array)
Guys I know this might be a naive Question but i got to ask.
I have array of string
List<string> lstPets = new List<string> { "dog", "cat","horse","parrot" };

And a string

string paragraph = "This is a test script to test whether a dog exists or not";

Now I have to write a linq query to find whether any occurrence of "lstPets" in "paragrah".

Thanks in advance. :)

答:
Try Code </p>

```<code>var countres = lstPets.Where(c => paragraph.Contains(c)).ToList().Count() > 0 ? true : false;
</code>```

Body:
Try Code

var countres = lstPets.Where(c => paragraph.Contains(c)).ToList().Count() > 0 ? true : false;


问:
docker build - exactly 1 argument
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

```<code>docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min
</code>```

I get the error message:

```<code>"docker build" requires exactly 1 argument(s).
</code>```

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

```<code>ln -s docker-devel/Dockerfile.min link1
</code>```

Then I just went through with the command:

```<code>docker build -t dragnn-oss:latest-minimal -f link1 .
</code>```

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

答:
You need to add a dot at the end, either

docker build -t mytag .

or

docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min .

see also

docker: "build" requires 1 argument. See 'docker build --help'

Title: docker build - exactly 1 argument

Body:
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min

I get the error message:

"docker build" requires exactly 1 argument(s).

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

ln -s docker-devel/Dockerfile.min link1

Then I just went through with the command:

docker build -t dragnn-oss:latest-minimal -f link1 .

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.


问:
Android Firebase - version number of Firebase UI & Android design support libraries for Android SDK 24
I'm making a Chat Android app, and require the version number of Firebase UI & Android design support libraries for Android SDK 24.

I have got the below given version numbers from a link, but they are not compatible with sdk 24 but are only compatible with sdk 23.

```<code>compile 'com.android.support:design:23.4.0'
compile 'com.firebaseui:firebase-ui:0.6.0'
</code>```

I have searched Firebase website, but couldn't locate the new version no of these libraries.

Where can I find the updated version number for these library files?

答:
Android Support Library revisions

FirebaseUI versions

As of now 25.3.1 is the stable version for the support library and 2.0.1 for FirebaseUI.

ContentLicense: CC BY-SA 4.0

Body:
I'm making a Chat Android app, and require the version number of Firebase UI & Android design support libraries for Android SDK 24.

I have got the below given version numbers from a link, but they are not compatible with sdk 24 but are only compatible with sdk 23.

compile 'com.android.support:design:23.4.0'
compile 'com.firebaseui:firebase-ui:0.6.0'

I have searched Firebase website, but couldn't locate the new version no of these libraries.

Where can I find the updated version number for these library files?


问:
WPF Image.Source does nothing
I've been trying to set the Image.Source in the code behind to a relative path like this:

```<code>IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));
</code>```

If I use a non existing path, the program crashes.

But this path exists and works just like that as a .Fill in a Rectangle.
Whats wrong here ?

答:
I see nothing wrong here. Try using the full path instead. The .Last() is Linq so if you don't want to use this, just do the same thing with count - 1.

```<code>string exe = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Split('\\').Last();
IMG_3.Source = new BitmapImage(new Uri(System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.Length - exe.Length) + "/Sprites/Layout/image1.png"));
</code>```

Title: WPF Image.Source does nothing

Body:
I've been trying to set the Image.Source in the code behind to a relative path like this:

IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));

If I use a non existing path, the program crashes.

But this path exists and works just like that as a .Fill in a Rectangle.
Whats wrong here ?

Body:
I see nothing wrong here. Try using the full path instead. The .Last() is Linq so if you don't want to use this, just do the same thing with count - 1.

string exe = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Split('\\').Last();
IMG_3.Source = new BitmapImage(new Uri(System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.Length - exe.Length) + "/Sprites/Layout/image1.png"));


问:
what is the exception being thrown in this code:
```<code>public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}
</code>```

im not sure what exception is being thrown here, any help please

答: double[5] is not the last element in the array, double[4] is (arrays are zero-based in java)</p>

ContentLicense: CC BY-SA 2.5

Body:
public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}

im not sure what exception is being thrown here, any help please


问:
Dynamically ADDING and REMOVING Components in Angular
The current official docs only shows how to dynamically change components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader

What I want to achieve is, let's say I have 3 components: header, section, and footer with the following selectors:

```<code><app-header>
<app-section>
<app-footer>
</code>```

And then there are 6 buttons that will add or remove each component: Add Header, Add Section, and Add Footer

and when I click Add Header, the page will add <app-header> to the page that renders it, so the page will contain:

```<code><app-header>
</code>```

And then if I click Add Section twice, the page will now contain:

```<code><app-header>
<app-section>
<app-section>
</code>```

And if I click Add Footer, the page will now contain all these components:

```<code><app-header>
<app-section>
<app-section>
<app-footer>
</code>```

Is it possible to achieve this in Angular? Note that ngFor is not the solution I'm looking for, as it only allows to add the same components, not different components to a page.

EDIT: ngIf and ngFor is not the solution I'm looking for as the templates are already predetermined. What I am looking for is something like a stack of components or an array of components where we can add, remove, and change any index of the array easily.

EDIT 2: To make it more clear, let's have another example of why ngFor does not work. Let's say we have the following components:

```<code><app-header>
<app-introduction>
<app-camera>
<app-editor>
<app-footer>
</code>```

Now here comes a new component, <app-description>, which the user wants to insert in between  and <app-editor>. ngFor works only if there is one same component that I want to loop over and over. But for different components, ngFor fails here.

答:
What you're trying to achieve can be done by creating components dynamically using the ComponentFactoryResolver and then injecting them into a ViewContainerRef. One way to do this dynamically is by passing the class of the component as an argument of your function that will create and inject the component.

See example below:

```<code>import {
  Component,
  ComponentFactoryResolver, Type,
  ViewChild,
  ViewContainerRef
} from '@angular/core';

// Example component (can be any component e.g. app-header app-section)
import { DraggableComponent } from './components/draggable/draggable.component';

@Component({
  selector: 'app-root',
  template: `
    <!-- Pass the component class as an argument to add and remove based on the component class -->
    <button (click)="addComponent(draggableComponentClass)">Add</button>
    <button (click)="removeComponent(draggableComponentClass)">Remove</button>

    <div>
      <!-- Use ng-template to ensure that the generated components end up in the right place -->
      <ng-template #container>

      </ng-template>
    </div>

  `
})
export class AppComponent {
  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

  // Keep track of list of generated components for removal purposes
  components = [];

  // Expose class so that it can be used in the template
  draggableComponentClass = DraggableComponent;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  }

  addComponent(componentClass: Type<any>) {
    // Create component dynamically inside the ng-template
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
    const component = this.container.createComponent(componentFactory);

    // Push the component so that we can keep track of which components are created
    this.components.push(component);
  }

  removeComponent(componentClass: Type<any>) {
    // Find the component
    const component = this.components.find((component) => component.instance instanceof componentClass);
    const componentIndex = this.components.indexOf(component);

    if (componentIndex !== -1) {
      // Remove component from both view and array
      this.container.remove(this.container.indexOf(component));
      this.components.splice(componentIndex, 1);
    }
  }
}
</code>```

Notes:

If you want to make it easier to remove the components later on, you can keep track of them in a local variable, see this.components. Alternatively you can loop over all the elements inside the ViewContainerRef.

You have to register your component as an entry component. In your module definition register your component as an entryComponent (entryComponents: [DraggableComponent]).

Running example:
https://plnkr.co/edit/mrXtE1ICw5yeIUke7wl5

For more information:
https://angular.io/guide/dynamic-component-loader

Body:
The current official docs only shows how to dynamically change components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader

What I want to achieve is, let's say I have 3 components: header, section, and footer with the following selectors:

<app-header>
<app-section>
<app-footer>

And then there are 6 buttons that will add or remove each component: Add Header, Add Section, and Add Footer

and when I click Add Header, the page will add <app-header> to the page that renders it, so the page will contain:

<app-header>

And then if I click Add Section twice, the page will now contain:

<app-header>
<app-section>
<app-section>

And if I click Add Footer, the page will now contain all these components:

<app-header>
<app-section>
<app-section>
<app-footer>

Is it possible to achieve this in Angular? Note that ngFor is not the solution I'm looking for, as it only allows to add the same components, not different components to a page.

EDIT: ngIf and ngFor is not the solution I'm looking for as the templates are already predetermined. What I am looking for is something like a stack of components or an array of components where we can add, remove, and change any index of the array easily.

EDIT 2: To make it more clear, let's have another example of why ngFor does not work. Let's say we have the following components:

<app-header>
<app-introduction>
<app-camera>
<app-editor>
<app-footer>

Now here comes a new component, <app-description>, which the user wants to insert in between  and <app-editor>. ngFor works only if there is one same component that I want to loop over and over. But for different components, ngFor fails here.

Body:
What you're trying to achieve can be done by creating components dynamically using the ComponentFactoryResolver and then injecting them into a ViewContainerRef. One way to do this dynamically is by passing the class of the component as an argument of your function that will create and inject the component.

See example below:

import {
  Component,
  ComponentFactoryResolver, Type,
  ViewChild,
  ViewContainerRef
} from '@angular/core';

// Example component (can be any component e.g. app-header app-section)
import { DraggableComponent } from './components/draggable/draggable.component';

@Component({
  selector: 'app-root',
  template: `
    <!-- Pass the component class as an argument to add and remove based on the component class -->
    <button (click)="addComponent(draggableComponentClass)">Add</button>
    <button (click)="removeComponent(draggableComponentClass)">Remove</button>

    <div>
      <!-- Use ng-template to ensure that the generated components end up in the right place -->
      <ng-template #container>

      </ng-template>
    </div>

  `
})
export class AppComponent {
  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

  // Keep track of list of generated components for removal purposes
  components = [];

  // Expose class so that it can be used in the template
  draggableComponentClass = DraggableComponent;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  }

  addComponent(componentClass: Type<any>) {
    // Create component dynamically inside the ng-template
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
    const component = this.container.createComponent(componentFactory);

    // Push the component so that we can keep track of which components are created
    this.components.push(component);
  }

  removeComponent(componentClass: Type<any>) {
    // Find the component
    const component = this.components.find((component) => component.instance instanceof componentClass);
    const componentIndex = this.components.indexOf(component);

    if (componentIndex !== -1) {
      // Remove component from both view and array
      this.container.remove(this.container.indexOf(component));
      this.components.splice(componentIndex, 1);
    }
  }
}

Notes:

If you want to make it easier to remove the components later on, you can keep track of them in a local variable, see this.components. Alternatively you can loop over all the elements inside the ViewContainerRef.

You have to register your component as an entry component. In your module definition register your component as an entryComponent (entryComponents: [DraggableComponent]).

Running example:
https://plnkr.co/edit/mrXtE1ICw5yeIUke7wl5

For more information:
https://angular.io/guide/dynamic-component-loader


问:
How do I change NavBar Color in CSS
Hello I have view some of responsive multi level menu.
I Copy exactly the css and javascript. Here is my NavBar. The problem is, Im having trouble to change the default color(green) to other color. Here is the CSS file.

```<code> @import url(http://fonts.googleapis.com/css?
 family=Open+Sans:400italic,400,300,600);

@font-face {
font-family: 'icomoon';
src:url('../fonts/icomoon.eot');
src:url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'),
    url('../fonts/icomoon.woff') format('woff'),
    url('../fonts/icomoon.ttf') format('truetype'),
    url('../fonts/icomoon.svg#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}

/* minimal styles for that navi */
.rmm {margin: 0 auto;}
.rmm ul {margin: 0; padding:0; list-style: none; position: relative;
background: #000;}
.rmm ul:after {content: ""; clear: both; display: block;}
.rmm ul li {float: left;}
.rmm ul li:hover {background: #202020;}
.rmm ul li:hover > ul {display: block;}
.rmm ul li:hover a{color: #fff;}
.rmm ul li a {color: #fff; display: block; text-decoration: none;}
.rmm ul ul {display: none; margin:0; padding: 0; position: absolute; top:
100%;}
.rmm ul ul li {float: none; position: relative;}
.rmm ul ul li a{color: #fff;}
.rmm ul ul li a:hover {background: #202020;}
.rmm ul ul ul {position: absolute; left: 100%; top:0; width: 100%;}

/* mobile menu header button */
.rmm-toggled {width: 100%; background-color: #555555; min-height: 50px;
margin: 0 auto; display: none;}
.rmm-closed ~ .rmm-mobile {display: none!important;}
.rmm-toggled-controls{width: 100%;}
.rmm-toggled-title{width: 60%; float: left; font-size: 27px; color: #fff;
font-weight:600; display: block; padding: 8px 0; text-decoration: none;
text-transform: uppercase; text-align: left; padding-left: 35px;}
.rmm-toggled-button{width: 20%; float: left; margin-top: 3px;
display:block;
width: 32px;
padding:0 !important;
margin:10px 10px 0 0;
border:1px solid #fff;
border-radius:3px;
float: right;
}
.rmm-toggled-button span{float: left; display:block; margin: 3px 6px;
height: 3px; background:white; width:20px;}

/* normalny back button visible only on mobiles  */
.rmm .rmm-back{display: none; font-size: 12px;}
.rmm .rmm-back:after {display: none;}
.rmm .rmm-back a:after {
font-family: 'icomoon';
speak: none;
-webkit-font-smoothing: antialiased;
content: "\e000";
position: relative;
display: inline-block;
-webkit-transform: rotate(-60deg);
transform: rotate(-60deg);
top: 1px;
right: -2px ;
float: left;
font-size: 10px;
 }
.rmm-mobile .rmm-back{display: block;}

   /* mobile menu list */
  .rmm-mobile{width: 100%;}
  .rmm-mobile .rmm-dropdown:hover ~ ul, .rmm-mobile .rmm-dropdown:hover > ul
  ,.rmm-mobile .rmm-dropdown:hover + ul {display: none!important;}
   .rmm-mobile ul{width: 100%; position: inherit!important;}
   .rmm-mobile li{width: 100%; }

   /* mobile menu js action */
  .rmm-dropdown{display: block!important;}
  .rmm-mobile .rmm-subview{display: block!important; width: 100%;}
  .rmm-mobile .rmm-subover-hidden{display: none!important;}
  .rmm-mobile .rmm-subover-visible{display: block;}
  .rmm-mobile .rmm-subover-header{display: none!important; padding: 0;
   margin:0;}

  /* mobile menu content */
  .rmm-mobile .rmm-submenu{position: relative; left: 0px;}

  .rmm .rmm-mobile li:hover > ul {display: none;}

  /* arrow down for wide screen */
  .rmm.style {text-align: left; font-family: Tahoma;}
  .rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
   background:#990;
   text-transform: uppercase; display: inline-table; text-align:left;}
  .rmm.style ul li {text-align:left;}
  .rmm.style ul li:hover {background: #4b545f;}
  .rmm.style ul ul {display: none; margin:0; background: #5f6975; border-
   radius: 0px; padding: 0; position: absolute;}
  .rmm.style ul li a {color: #fff; font-weight:600; display: block; padding:
   15px 35px; text-decoration: none; font-weight:600; }
  .rmm.style ul ul li {border-bottom: 1px solid #575F6A; border-top: 1px
  solid #6B727C;}
  .rmm.style ul ul li a {padding: 12px 35px; color: #fff; }
  .rmm.style ul ul li a:hover {background: #4b545f;}

    /* arrow down for wide screen */
   .rmm.style ul li > a:not(:only-child):after {
   font-family: 'icomoon';
    speak: none;
   -webkit-font-smoothing: antialiased;
   content: "\e000";
   position: relative;
   display: inline-block;
   -webkit-transform: rotate(210deg);
    transform: rotate(210deg);
    top: -4px;
    left: 1px;
     font-size: 10px;
    }

   /* arrow left for wide screen submenus  */
   .rmm.style ul ul li > a:not(:only-child):after {-webkit-transform:
   rotate(120deg)!important; transform: rotate(120deg)!important; top: 2px;
   font-size: 14px; float: right; margin-right: -20px;}

   /* mobile style */
   .rmm.style .rmm-mobile li > a:not(:only-child):after {-webkit-transform:
     rotate(120deg)!important; transform: rotate(120deg)!important; top:
    4px!important; font-size: 14px!important; float: right; margin-right:
   -20px;}
   .rmm.style .rmm-mobile li{background: #3ab4a6; border-bottom: 1px solid
    #575f6a!important; border-top: 0!important; }
</code>```

I have tried to change the color or add something for background-color. But the default color still Green. The javascript is to executed to function of the mobile version. Nothing to do with the color. Please Help. Im still newbie :)
Here is My HTML

```<code><!DOCTYPE html>
<html>
<head>
<title></title>

<!-- Include scripts -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js">
</script>
<script type="text/javascript" src="js/responsivemultimenu.js"></script>

<!-- Include styles -->
<link rel="stylesheet" href="css/responsivemultimenu.css" type="text/css"/>

<!-- Include media queries -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-
scale=1, user-scalable=no"/>
</head>
<body >

<div >

    <div class="rmm style">
        <ul>
        <li>

                <a href="KPIhome.php" title="KPI">eKPI</a>

        </li>

        <?php if(isset($_SESSION['admin']) || $_SESSION['user_level'] == 5
|| $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1 ){ ?>

            <li>

                <a href="#">Value Graph</a>
                <ul>
                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="sales_form.php">Sales Achievement against
Target</a>
                    </li>
                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="promo_form.php">Promotion Sales Achievement
against Target </a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="manhour_form.php">Sales per Manhour</a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="trans_form.php">Transaction per Manhour</a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="salmonform.php">Salmon Usage Per 1K</a>
                    </li>

                </ul>
            </li>

            <?php } ?>

             <?php if(isset($_SESSION['admin']) || $_SESSION['user_level']
  == 5 || $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1){ ?>

            <li>

                <a href="#">Percentage Graph</a>
                <ul>
                    <li <?php if($page == 'home.php'){echo '
 class="active"';};?>>
                        <a href="sales_form2.php">Sales Achievement against
Target (%)</a>
                    </li>
                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="promo_form2.php">Promotion Sales
Achievement against Target (%)</a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="wastage_form.php">Wastage against Target
(%)</a>
                    </li>

                </ul>
            </li>

            <?php } ?>

             <?php if(isset($_SESSION['admin']) || $_SESSION['user_level']
== 5 || $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1){ ?>

            <li>

                <a href="#">Over Budget</a>
                <ul>
                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="obtargetform.php">Sales Achievement</a>
                    </li>
                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="obmtdform.php">Sales Month to Date
 Achievement</a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="obtargetform2.php">Promotion Sales
Achievement</a>
                    </li>
                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        <a href="obmtdform2.php">Promotion Month to Date
Sales Achivement</a>
                    </li>

                </ul>
            </li>

            <?php } ?>

             <?php if(isset($_SESSION['admin'])&& $_SESSION['user_level'] == 0 || $_SESSION['user_level']==7 ){ ?>
            <li>

                <a href="#">Report</a>
                <ul>
                    <li <?php if($page == 'home.php'){echo ' class="active"';};?>>
                        <a href="typereport.php">Add Report</a>
                    </li>

                </ul>
            </li>

            <?php } ?>

        <li>

                <a href="KPIhome.php" title="KPI">Website</a>

        </li>

        <li>

                <a href="KPIhome.php" title="KPI">Admin</a>

        </li>

        </ul>
    </div>
</div>
</code>```

答:
.new class{
background-color:red;
}```

you can also make new class and add along with rmm style for desired background

Title: How do I change NavBar Color in CSS

Body:
Hello I have view some of responsive multi level menu.
I Copy exactly the css and javascript. Here is my NavBar. The problem is, Im having trouble to change the default color(green) to other color. Here is the CSS file.

 @import url(http://fonts.googleapis.com/css?
 family=Open+Sans:400italic,400,300,600);

@font-face {
font-family: 'icomoon';
src:url('../fonts/icomoon.eot');
src:url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'),
    url('../fonts/icomoon.woff') format('woff'),
    url('../fonts/icomoon.ttf') format('truetype'),
    url('../fonts/icomoon.svg#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}

/* minimal styles for that navi */
.rmm {margin: 0 auto;}
.rmm ul {margin: 0; padding:0; list-style: none; position: relative;
background: #000;}
.rmm ul:after {content: ""; clear: both; display: block;}
.rmm ul li {float: left;}
.rmm ul li:hover {background: #202020;}
.rmm ul li:hover > ul {display: block;}
.rmm ul li:hover a{color: #fff;}
.rmm ul li a {color: #fff; display: block; text-decoration: none;}
.rmm ul ul {display: none; margin:0; padding: 0; position: absolute; top:
100%;}
.rmm ul ul li {float: none; position: relative;}
.rmm ul ul li a{color: #fff;}
.rmm ul ul li a:hover {background: #202020;}
.rmm ul ul ul {position: absolute; left: 100%; top:0; width: 100%;}

/* mobile menu header button */
.rmm-toggled {width: 100%; background-color: #555555; min-height: 50px;
margin: 0 auto; display: none;}
.rmm-closed ~ .rmm-mobile {display: none!important;}
.rmm-toggled-controls{width: 100%;}
.rmm-toggled-title{width: 60%; float: left; font-size: 27px; color: #fff;
font-weight:600; display: block; padding: 8px 0; text-decoration: none;
text-transform: uppercase; text-align: left; padding-left: 35px;}
.rmm-toggled-button{width: 20%; float: left; margin-top: 3px;
display:block;
width: 32px;
padding:0 !important;
margin:10px 10px 0 0;
border:1px solid #fff;
border-radius:3px;
float: right;
}
.rmm-toggled-button span{float: left; display:block; margin: 3px 6px;
height: 3px; background:white; width:20px;}

/* normalny back button visible only on mobiles  */
.rmm .rmm-back{display: none; font-size: 12px;}
.rmm .rmm-back:after {display: none;}
.rmm .rmm-back a:after {
font-family: 'icomoon';
speak: none;
-webkit-font-smoothing: antialiased;
content: "\e000";
position: relative;
display: inline-block;
-webkit-transform: rotate(-60deg);
transform: rotate(-60deg);
top: 1px;
right: -2px ;
float: left;
font-size: 10px;
 }
.rmm-mobile .rmm-back{display: block;}

   /* mobile menu list */
  .rmm-mobile{width: 100%;}
  .rmm-mobile .rmm-dropdown:hover ~ ul, .rmm-mobile .rmm-dropdown:hover > ul
  ,.rmm-mobile .rmm-dropdown:hover + ul {display: none!important;}
   .rmm-mobile ul{width: 100%; position: inherit!important;}
   .rmm-mobile li{width: 100%; }

   /* mobile menu js action */
  .rmm-dropdown{display: block!important;}
  .rmm-mobile .rmm-subview{display: block!important; width: 100%;}
  .rmm-mobile .rmm-subover-hidden{display: none!important;}
  .rmm-mobile .rmm-subover-visible{display: block;}
  .rmm-mobile .rmm-subover-header{display: none!important; padding: 0;
   margin:0;}

  /* mobile menu content */
  .rmm-mobile .rmm-submenu{position: relative; left: 0px;}

  .rmm .rmm-mobile li:hover > ul {display: none;}

  /* arrow down for wide screen */
  .rmm.style {text-align: left; font-family: Tahoma;}
  .rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
   background:#990;
   text-transform: uppercase; display: inline-table; text-align:left;}
  .rmm.style ul li {text-align:left;}
  .rmm.style ul li:hover {background: #4b545f;}
  .rmm.style ul ul {display: none; margin:0; background: #5f6975; border-
   radius: 0px; padding: 0; position: absolute;}
  .rmm.style ul li a {color: #fff; font-weight:600; display: block; padding:
   15px 35px; text-decoration: none; font-weight:600; }
  .rmm.style ul ul li {border-bottom: 1px solid #575F6A; border-top: 1px
  solid #6B727C;}
  .rmm.style ul ul li a {padding: 12px 35px; color: #fff; }
  .rmm.style ul ul li a:hover {background: #4b545f;}

    /* arrow down for wide screen */
   .rmm.style ul li > a:not(:only-child):after {
   font-family: 'icomoon';
    speak: none;
   -webkit-font-smoothing: antialiased;
   content: "\e000";
   position: relative;
   display: inline-block;
   -webkit-transform: rotate(210deg);
    transform: rotate(210deg);
    top: -4px;
    left: 1px;
     font-size: 10px;
    }

   /* arrow left for wide screen submenus  */
   .rmm.style ul ul li > a:not(:only-child):after {-webkit-transform:
   rotate(120deg)!important; transform: rotate(120deg)!important; top: 2px;
   font-size: 14px; float: right; margin-right: -20px;}

   /* mobile style */
   .rmm.style .rmm-mobile li > a:not(:only-child):after {-webkit-transform:
     rotate(120deg)!important; transform: rotate(120deg)!important; top:
    4px!important; font-size: 14px!important; float: right; margin-right:
   -20px;}
   .rmm.style .rmm-mobile li{background: #3ab4a6; border-bottom: 1px solid
    #575f6a!important; border-top: 0!important; }

I have tried to change the color or add something for background-color. But the default color still Green. The javascript is to executed to function of the mobile version. Nothing to do with the color. Please Help. Im still newbie :)
Here is My HTML

<!DOCTYPE html>

<title></title>

<link rel="stylesheet" href="css/responsivemultimenu.css" type="text/css"/>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-
scale=1, user-scalable=no"/>

                eKPI

        <?php if(isset($_SESSION['admin']) || $_SESSION['user_level'] == 5
|| $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1 ){ ?>

                Value Graph

                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Sales Achievement against
Target

                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Promotion Sales Achievement
against Target

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Sales per Manhour

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Transaction per Manhour

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Salmon Usage Per 1K

            <?php } ?>

             <?php if(isset($_SESSION['admin']) || $_SESSION['user_level']
  == 5 || $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1){ ?>

                Percentage Graph

                    <li <?php if($page == 'home.php'){echo '
 class="active"';};?>>
                        Sales Achievement against
Target (%)

                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Promotion Sales
Achievement against Target (%)

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Wastage against Target
(%)

            <?php } ?>

             <?php if(isset($_SESSION['admin']) || $_SESSION['user_level']
== 5 || $_SESSION['user_level']==7 || $_SESSION['user_level'] ==1){ ?>

                Over Budget

                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Sales Achievement

                    <li <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Sales Month to Date
 Achievement

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Promotion Sales
Achievement

                    <li  <?php if($page == 'home.php'){echo '
class="active"';};?>>
                        Promotion Month to Date
Sales Achivement

            <?php } ?>

             <?php if(isset($_SESSION['admin'])&& $_SESSION['user_level'] == 0 || $_SESSION['user_level']==7 ){ ?>

                Report

                    <li <?php if($page == 'home.php'){echo ' class="active"';};?>>
                        Add Report

            <?php } ?>

                Website

                Admin

Body:
.new class{
background-color:red;
}

you can also make new class and add along with rmm style for desired background


问:
Javascript function remove from position in array
I have an array:

```<code>var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
</code>```

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

```<code>var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];
</code>```

How can i do that?

答:
I do not like example with splicing source array, because splicing is a long operation and in large arrays / multiple operations it will be not so effective. I think you should create new arrays and don't mind.</p>

```<code>const arraysList = myArray.reduce((acc, item, index) => {
    if ((index + 1) % 3 === 0) {
        acc.second.push(item);
    } else {
        acc.first.push(item);
    }
    return acc;
}, { first: [], second: [] })

console.log(arraysList.first); // [12, 11 18, 30, 21, 18]
console.log(arraysList.second); // [13, 51, 20]
</code>```

Body:
I have an array:

var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];

How can i do that?

Body:
I do not like example with splicing source array, because splicing is a long operation and in large arrays / multiple operations it will be not so effective. I think you should create new arrays and don't mind.

const arraysList = myArray.reduce((acc, item, index) => {
    if ((index + 1) % 3 === 0) {
        acc.second.push(item);
    } else {
        acc.first.push(item);
    }
    return acc;
}, { first: [], second: [] })

console.log(arraysList.first); // [12, 11 18, 30, 21, 18]
console.log(arraysList.second); // [13, 51, 20]


答:
if the array is of size five, the allowed indexes are 0-4.

So you are probably getting an out of bounds exception.

Title: what is the exception being thrown in this code:


问:
How do I make changes in base.css for WordPress
I need to change an image background for some blog posts on a website using WordPress. I've tracked the element source to be located in the base.css. As far as I can tell I don't have direct access to edit the file, but I'm assuming that there is somewhere that I can modify it. I want to change the background style of the Testimonial posts on the Testimonials page. The element that I need to modify is testi-container's url image. Here is the website address. www.avantirecruiters.com

How can I change the style using CSS?

答:
You do have class called body class called 'category-testimonials'
.category-testimonials .testi-container
for image you  can always use
.category-testimonials .testi-container{background:url('');} </p>


问:
my inapp browser path is not closing when i click on Close button on app given location.href = 'mobile/close'
here is my client side code iam opening browser .

```<code>ref = cordova.InAppBrowser.open(path, '_self', 'location=no,toolbar=yes,closebuttoncaption=Close');
ref.addEventListener('loadstop', function (event) {
    if (event.url.match("mobile/close")) {
        ref.close();
    }
});
</code>```

in server by clicking close button iam writting to close inappbrowser is
 location.href = 'mobile/close';

答:
in config file i have added

so the inappbrowser is not closing .
 i have removed this configuration file

i have solved issue .</p>

Body:
here is my client side code iam opening browser .

ref = cordova.InAppBrowser.open(path, '_self', 'location=no,toolbar=yes,closebuttoncaption=Close');
ref.addEventListener('loadstop', function (event) {
    if (event.url.match("mobile/close")) {
        ref.close();
    }
});

in server by clicking close button iam writting to close inappbrowser is
 location.href = 'mobile/close';


答:
That would be an Index Out Of Range Exception (arrays are 0 based, not 1 based):</p>

```<code> scores[5] = 95.75; // references the sixth element of a five element array
</code>```

Body:
That would be an Index Out Of Range Exception (arrays are 0 based, not 1 based):

 scores[5] = 95.75; // references the sixth element of a five element array


问:
Session lost after redirect in Codeigniter
I'm using codeigniter as a framework.

Firstly, I use localhost but when I change to my IP address the login function doesn't work anymore. I found that the session is lost after redirect to another controller.

Here is the result of print_r($this->session->all_userdata());

```<code>[session_id] => 7b00fa0f8790f48d24446f9eb4e6aab2
[ip_address] => 10.42.68.71
[user_agent] => Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
[last_activity] => 1285962398
[user_data] =>
</code>```

As you can see it doesn't have any data passed to user_data but it was set before redirect when I test.

I separate the controller to two which the first one is users -> handler of login function and another is planner which handler of the link that I redirect from users controller.

users.php (first controller):

```<code>$this->load->model('users_model');
$this->load->model('mymodel');
$this->load->database();

$email = $this->input->post('email');

$pass = $this->input->post('password');

$type = $this->input->post('type');

// Authenticate the user
$userdata = $this->users_model->auth_user($email,$pass,$type);

if($userdata)
{
    $data = array('FIRSTNAME' => $userdata->FIRSTNAME,
                  'LASTNAME' => $userdata->LASTNAME,
                  'EMAIL' => $userdata->EMAIL,
                  'LOGIN' =>TRUE, 'TYPE' => $type);
    $this->session->set_userdata($data);
    redirect('planner/view_system','refresh');
}
</code>```

planner.php (second controller):

```<code>function __construct() {
    parent::__construct();

    if ( ! ($this->session->userdata('LOGIN')))
    {
        print_r (var_dump($this->session->userdata('FIRSTNAME')));
        print_r($this->session->all_userdata());
    }
    $this->load->helper(array('form','html','url'));
</code>```

And here is my config

```<code>$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = TRUE;
$config['sess_match_useragent'] = FALSE;
$config['sess_time_to_update']  = 300;
</code>```

答:
I was shocked at first when I encountered this problem. It happened to me because my session data had an @ sign.

The solution is to simply encode the data using base64_encode.

Eg:

```<code>$Data = urlencode(  base64_encode($Email) );
$this->session->set_userdata('Data', $Data);
</code>```

And to reuse it, simply do this:

```<code>$Data = base64_decode( urldecode( $this->session->userdata('Data') ) );
</code>```

Hope this helps.

NEW FINDING: This problem still persists on some browsers and devices. So this is not really a solution anymore. For example, it works on Samsung Android, MicroMAX Android but not on Huawei Android.

Body:
I'm using codeigniter as a framework.

Firstly, I use localhost but when I change to my IP address the login function doesn't work anymore. I found that the session is lost after redirect to another controller.

Here is the result of print_r($this->session->all_userdata());

[session_id] => 7b00fa0f8790f48d24446f9eb4e6aab2
[ip_address] => 10.42.68.71
[user_agent] => Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
[last_activity] => 1285962398
[user_data] =>

As you can see it doesn't have any data passed to user_data but it was set before redirect when I test.

I separate the controller to two which the first one is users -> handler of login function and another is planner which handler of the link that I redirect from users controller.

users.php (first controller):

$this->load->model('users_model');
$this->load->model('mymodel');
$this->load->database();

$email = $this->input->post('email');

$pass = $this->input->post('password');

$type = $this->input->post('type');

// Authenticate the user
$userdata = $this->users_model->auth_user($email,$pass,$type);

if($userdata)
{
    $data = array('FIRSTNAME' => $userdata->FIRSTNAME,
                  'LASTNAME' => $userdata->LASTNAME,
                  'EMAIL' => $userdata->EMAIL,
                  'LOGIN' =>TRUE, 'TYPE' => $type);
    $this->session->set_userdata($data);
    redirect('planner/view_system','refresh');
}

planner.php (second controller):

function __construct() {
    parent::__construct();

    if ( ! ($this->session->userdata('LOGIN')))
    {
        print_r (var_dump($this->session->userdata('FIRSTNAME')));
        print_r($this->session->all_userdata());
    }
    $this->load->helper(array('form','html','url'));

And here is my config

$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = TRUE;
$config['sess_match_useragent'] = FALSE;
$config['sess_time_to_update']  = 300;

Body:
I was shocked at first when I encountered this problem. It happened to me because my session data had an @ sign.

The solution is to simply encode the data using base64_encode.

Eg:

$Data = urlencode(  base64_encode($Email) );
$this->session->set_userdata('Data', $Data);

And to reuse it, simply do this:

$Data = base64_decode( urldecode( $this->session->userdata('Data') ) );

Hope this helps.

NEW FINDING: This problem still persists on some browsers and devices. So this is not really a solution anymore. For example, it works on Samsung Android, MicroMAX Android but not on Huawei Android.


问:
assign variables before or in loops statement performance
In many programming languages, assignments are legal in loops statement like this.

```<code>while(variable1 = someFunction()){
...
}
</code>```

although it would be more clear code to assign variables like this I am wondering if someFunction function has a computational process in it's, it would be a better way to assign variable before loops like this

```<code>variable1 = someFunction()
while(variable1){
...
}
</code>```

or no matter and compilers can detect this to do not compute it again

答:
I tested this in Java,JavaScript and Python that are popular languages.
in every language first I have a function that sums from number 1 to 1000.
first I assign this value before the loop and see how many second take-ups to finish, then I assign this sum in a loop condition and see the result again

Java

```<code>public class Main {
    public static void main(String args[]){

        //assign variable before loop
        long startTime= System.currentTimeMillis();
        int counter = sum();
        for (int i = 0; i < counter; i++) {
            //some code
        }
        long finishTime = System.currentTimeMillis();
        System.out.println("duration for assign before loop : "+(finishTime-startTime));

        //assign variable in  loop
        startTime = System.currentTimeMillis();
        for (int i = 0; i < sum(); i++) {
            //some code
        }
        finishTime = System.currentTimeMillis();
        System.out.println("duration for assign in loop : "+(finishTime-startTime));

    }
    public static int sum(){
        int sum = 0;
        for (int i = 1; i < 1000; i++) {
            sum+=i;
        }
        return sum;
    }
}
</code>```

Then write this code in javascript:

```<code>function sum(){
        let sum = 0;
        for (let i = 1; i < 1000; i++) {
            sum+=i;
        }
        return sum;
}
(function(){
        //assign variable before loop
        let startTime= Date.now();
        let counter = sum();
        for (let i = 0; i < counter; i++) {
            //some code
        }
        let finishTime = Date.now();
        console.log("duration for assign before loop : "+(finishTime-startTime))

        //assign variable in  loop
        startTime = Date.now();
        for (let i = 0; i < sum(); i++) {
            //some code
        }
        finishTime = Date.now()
        console.log("duration for assign in loop : "+(finishTime-startTime));
})()
</code>```

and finally, I write this code in python

```<code>import time

def current_milli_time():
    return int(round(time.time() * 1000))

def sum():
    sum = 0
    for i in xrange(1,1000):
        sum += i
    return sum

if __name__=="__main__":
    #assign before loop
    startTime = current_milli_time()
    counter = sum()
    for i in xrange(1,counter):
        pass
    finishTime = current_milli_time()
    print("duration for assign before loop : "+str(finishTime-startTime))

    #assign in loop
    startTime = current_milli_time()
    for i in xrange(1,sum()):
        pass
    finishTime = current_milli_time()
    print("duration for assign in loop : "+str(finishTime-startTime))
</code>```

the result was interesting.I got this result in every language

Java :

duration for assign before loop : 2

duration for assign in loop : 326

JavaScript :

duration for assign before loop : 4

duration for assign in loop : 1846

but in python I got

duration for assign before the loop : 66

duration for assign in a loop : 67

as we can see in Java and JavaScript we absolutely should not use assign variable in loops if it results is the same during loop but in python, we got almost very close duration.

Conclusion

as a conclusion, I think it's no matter what programming language we use but it's better to don't assign variables in loops if it results remain the same during the loop

Body:
In many programming languages, assignments are legal in loops statement like this.

while(variable1 = someFunction()){
...
}

although it would be more clear code to assign variables like this I am wondering if someFunction function has a computational process in it's, it would be a better way to assign variable before loops like this

variable1 = someFunction()
while(variable1){
...
}

or no matter and compilers can detect this to do not compute it again

Body:
I tested this in Java,JavaScript and Python that are popular languages.
in every language first I have a function that sums from number 1 to 1000.
first I assign this value before the loop and see how many second take-ups to finish, then I assign this sum in a loop condition and see the result again

Java

public class Main {
    public static void main(String args[]){

        //assign variable before loop
        long startTime= System.currentTimeMillis();
        int counter = sum();
        for (int i = 0; i < counter; i++) {
            //some code
        }
        long finishTime = System.currentTimeMillis();
        System.out.println("duration for assign before loop : "+(finishTime-startTime));

        //assign variable in  loop
        startTime = System.currentTimeMillis();
        for (int i = 0; i < sum(); i++) {
            //some code
        }
        finishTime = System.currentTimeMillis();
        System.out.println("duration for assign in loop : "+(finishTime-startTime));

    }
    public static int sum(){
        int sum = 0;
        for (int i = 1; i < 1000; i++) {
            sum+=i;
        }
        return sum;
    }
}

Then write this code in javascript:

function sum(){
        let sum = 0;
        for (let i = 1; i < 1000; i++) {
            sum+=i;
        }
        return sum;
}
(function(){
        //assign variable before loop
        let startTime= Date.now();
        let counter = sum();
        for (let i = 0; i < counter; i++) {
            //some code
        }
        let finishTime = Date.now();
        console.log("duration for assign before loop : "+(finishTime-startTime))

        //assign variable in  loop
        startTime = Date.now();
        for (let i = 0; i < sum(); i++) {
            //some code
        }
        finishTime = Date.now()
        console.log("duration for assign in loop : "+(finishTime-startTime));
})()

and finally, I write this code in python

import time

def current_milli_time():
    return int(round(time.time() * 1000))

def sum():
    sum = 0
    for i in xrange(1,1000):
        sum += i
    return sum

if __name__=="__main__":
    #assign before loop
    startTime = current_milli_time()
    counter = sum()
    for i in xrange(1,counter):
        pass
    finishTime = current_milli_time()
    print("duration for assign before loop : "+str(finishTime-startTime))

    #assign in loop
    startTime = current_milli_time()
    for i in xrange(1,sum()):
        pass
    finishTime = current_milli_time()
    print("duration for assign in loop : "+str(finishTime-startTime))

the result was interesting.I got this result in every language

Java :

duration for assign before loop : 2

duration for assign in loop : 326

JavaScript :

duration for assign before loop : 4

duration for assign in loop : 1846

but in python I got

duration for assign before the loop : 66

duration for assign in a loop : 67

as we can see in Java and JavaScript we absolutely should not use assign variable in loops if it results is the same during loop but in python, we got almost very close duration.

Conclusion

as a conclusion, I think it's no matter what programming language we use but it's better to don't assign variables in loops if it results remain the same during the loop


答:
You need to add an argument to the end with just the path.

If it's the current directory then . (simple dot) will suffice.

The -f param is just for the filename (Dockerfile being the default)

```<code>docker build -t dragnn-oss:latest-minimal -f Dockerile.min docker-devel
</code>```

Title: docker build - exactly 1 argument

Body:
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min

I get the error message:

"docker build" requires exactly 1 argument(s).

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

ln -s docker-devel/Dockerfile.min link1

Then I just went through with the command:

docker build -t dragnn-oss:latest-minimal -f link1 .

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

Body:
You need to add an argument to the end with just the path.

If it's the current directory then . (simple dot) will suffice.

The -f param is just for the filename (Dockerfile being the default)

docker build -t dragnn-oss:latest-minimal -f Dockerile.min docker-devel


问:
AWS Cpanel & Phpmyadmin
Can any please help me in below issue.
I am planning to host more than one site on single AWS ec-2 Instance, now I want every site have its own cpanel and phpmyadmin.

Confusion
should I need to install Cpanel and PHPMyAdmin for every site or what?

Maybe it a silly question but currently, I am stuck.

答:
If you plan on using cPanel/WHM first you need to install the software on your server. You will be provided with a 15 days trial license and then you need to pay a monthly or yearly fee (around $15/month). Then from the WHM interface you can add cpanel accounts for your different domains. Each added cPanel account will have it's own login credentials (username/password) and a bunch of stuff to play with from editing files, creating emails, mysql database administration, phpmyadmin included etc.

If you do not plan to use cPanel at all then you need to configure your server the way you need or use any other hosting panels (some of them paid as Plesk for example) or free ones: ISPConfig, CWP, Virtualmin/Usermin, VestaCP etc.

Title: AWS Cpanel & Phpmyadmin


答:
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

var newArray1 = [];
var newArray2 = [];
myArray.forEach(function(value,index){
  if((index + 1) % 3 === 0){
    newArray1.push(value);
  }
  else {
    newArray2.push(value);
  }
});

console.log(newArray1); // Stores element at index 3 in the original array
console.log(newArray2); // Stores element at index other than 3 in the original array```

Title: Javascript function remove from position in array


问:
C# MVC IIS long running requests
I have an C# MVC app. And one of the calls I know will take like 12 hours, I'm generating some reports.

I want to know if the IIS will keep the process running this long.
If I'll do it async will it run and somehow put it away and let him run for this long?

答: I'm assuming the report must be using something like SSRS. Why don't you create a batch job at the backend to run the reports at a specified time. Update a table with the status of the report and just poll the status at the front end. when Ready just download it. Imagine if your report had been running for 6 hours and it's reliant on the website being up. If someone re-starts the website that's 6 hours of processing gone.</p>

Title: C# MVC IIS long running requests


问:
Temporarily Storing Decrypted Data in Memory
Background

I am working on a simple application in native C++11 which uses Microsoft's Cassablanca REST framework to communicate with various remote endpoints.  To do this, I have to cryptographically sign the various requests with some secret provided by whichever API is being targeted.  By linking Cassablanca I already have OpenSSL so the actual crypto is reasonably straight-forward.

Now, the tricky part is how to store the secrets themselves.  My plan is to AES encrypt a JSON file with all of the goodies using a symmetric key from the user's brain (read: password) so that it does not have to be stored on disk.

The Question

What is a secure way to store the decrypted secrets in memory during the execution of the application?  This is not another "how do I store secrets on disk so the user doesn't have to do anything" question.

My big concern is that someone will be able to examine my application's memory externally and find the appropriate regions containing the goodies.  I know Windows provides credstores and protected memory however I am on Linux and would prefer a platform-agnostic solution if possible.  There is also a significant chance that this will be deployed to a VM cluster so protected memory may only buy limited assurances (though, still better than nothing).

Finally, I know that any cryptographic system can be overcome with sufficiently large amount of money+time or a large enough rubber hose.  That being said, I would still like to be as secure as possible as an exercise in Good™ coding practice.

My constraints are:

Must be able to access secrets for signing the various requests quickly.  Milliseconds count here but I am willing to accept a slowdown if security is truly improved.

I would prefer a minimum of external libraries and to use native C++11 where possible.  I feel like this should be doable with what I already have (Cassablanca which requires OpenSSL, Boost, libcrypt).

Finally, it should be able to accommodate a reasonably large number of secrets / requests.  My application domain is basically a giant parallelization problem and scalability is key.

What I already know to do:

Never ever store sensitive material on disk unencrypted.  This includes usage of disk-backed containers and whatnot.

An old but useful trick: attach a debugger instance to prevent remote debugging from external process.

Build without debug symbols and strip final executable.

Minimize in-application access to data to only the parts which truly need it.

Destroy sensitive information as soon as it is no longer needed (Ex. NULL out user password as soon as decryption is finished, etc).

Do not trust anybody to sanitize memory for me.  Manually overwrite areas with NULL / garbage.

Similar Questions

Storing sensitive data in memory

PHP specific and advises writing something not in PHP to store the credentials...which is exactly the problem I am trying to solve.

Store password temporarily in memory

Android application lifecycle specific.  I already know the storage duration for my secrets will be the lifetime of the application.

答:
I would have an area of static memory (largish buffer in your application which holds a per application launch encryption key.

Encrypt all your live secrets with the encryption key

Any memory which uses unencrypted secrets is cleared with a secure memset.

Keep memory used for encryption separate from normal memory (special new/delete to a mmap area).

This would result in....

Plain view of your secrets would not be possible.  This prevents leaking of your information by heartbleed type of bugs.  Although un- reset areas of the heap may be published, they are no use as they are encrypted.

Plain view secrets have a short life.

Encrypted memory would not be adjacent to un-encypted data.

The scheme keeps three areas of memory, the encryption secret which is static, and part of the image memory.

The general application side data - using normal new / delete.

Encrypted data, using a custom new/delete, which is a mmap, and won't share addresses with normal new/delete


问:
XPath For Elements With Tag Name ID
I'm having trouble retrieving elements values with tag name "Id"
All other elements and even the Parent Node (//Product) XPath works perfectly, but for some reason I can't get the Id elements by XPath

I've tried several path queries including:

```<code>//Product/Id[1]/text()
//Product/Id[1]
//Product[1]/Id[1]/text()
//Product[1]/Id/text()
</code>```

I suspect "Id" is reserved or is that I'm doing something wrong here?

```<code>...<Product>
              <Id>401057</Id>
              <ProductOrderKey>439138</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>420004</Id>
              <ProductOrderKey>439139</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>401061</Id>
              <ProductOrderKey>439140</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>401008</Id>
              <ProductOrderKey>439141</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>420000</Id>
              <ProductOrderKey>439142</ProductOrderKey>
              <EffectiveDate>20101102145023</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Service>...
</code>```

答:
```<code>import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class Test {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        File inputFile = new File("C:/product.txt");
        DocumentBuilderFactory dbFactory
                = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();

        XPath xPath = XPathFactory.newInstance().newXPath();

        String expression = "/Products/Product";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node nNode = nodeList.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Student roll no : "
                        + eElement.getElementsByTagName("Id").item(0)
                        .getTextContent());
            }
        }
    }
}
</code>```

You can parse a xml file and get the Id tag value.I hope this will be useful for you.

Title: XPath For Elements With Tag Name ID

Body:
I'm having trouble retrieving elements values with tag name "Id"
All other elements and even the Parent Node (//Product) XPath works perfectly, but for some reason I can't get the Id elements by XPath

I've tried several path queries including:

//Product/Id[1]/text()
//Product/Id[1]
//Product[1]/Id[1]/text()
//Product[1]/Id/text()

I suspect "Id" is reserved or is that I'm doing something wrong here?

...<Product>
              <Id>401057</Id>
              <ProductOrderKey>439138</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>420004</Id>
              <ProductOrderKey>439139</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>401061</Id>
              <ProductOrderKey>439140</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>401008</Id>
              <ProductOrderKey>439141</ProductOrderKey>
              <EffectiveDate>20101102145002</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Product>
              <Id>420000</Id>
              <ProductOrderKey>439142</ProductOrderKey>
              <EffectiveDate>20101102145023</EffectiveDate>
              <ExpiredDate>20370101000000</ExpiredDate>
              <Status>0</Status>
           </Product>
           <Service>...

Body:
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class Test {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        File inputFile = new File("C:/product.txt");
        DocumentBuilderFactory dbFactory
                = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();

        XPath xPath = XPathFactory.newInstance().newXPath();

        String expression = "/Products/Product";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node nNode = nodeList.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Student roll no : "
                        + eElement.getElementsByTagName("Id").item(0)
                        .getTextContent());
            }
        }
    }
}

You can parse a xml file and get the Id tag value.I hope this will be useful for you.


答:
Array#reduce the original array into 2 new arrays:

const myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

const [without3rdItems, with3rdItems] = myArray.reduce((arrs, n, i) => {
  const arr = (i + 1) % 3 ? 0 : 1;

  arrs[arr].push(n);

  return arrs;
}, [[], []]);

console.log(without3rdItems.join());
console.log(with3rdItems.join());```


问:
Case Sensitive filter in Realm
I want a list of items in which I want to perform a search. I want items to be filtered based upon the query in case sensitive order.
For Example if user searches for milk
the order should be like
milk
Milk
butter milk
Butter MILK
Below is my current query but since I have added Case.Insesitive it gives me any random order based on the position of item in table.</p>

```<code>  mRealm.where(Product.class).contains("productTags.name", tag,Case.INSENSITIVE).findAll();
</code>```

答:
You need to use findAllSorted, like:

```<code>    realm.where(Product.class)
            .contains("productTags.name", tag, Case.INSENSITIVE)
            .findAllSorted("productTags.name", Sort.ASCENDING);
</code>```

But the sorting will be based on the ASCII value of the String, which by the looks of it isn't enough for you. In that case you need to do the sorting yourself by using a Comparator

Title: Case Sensitive filter in Realm

Body:
I want a list of items in which I want to perform a search. I want items to be filtered based upon the query in case sensitive order.
For Example if user searches for milk
the order should be like
milk
Milk
butter milk
Butter MILK
Below is my current query but since I have added Case.Insesitive it gives me any random order based on the position of item in table.

  mRealm.where(Product.class).contains("productTags.name", tag,Case.INSENSITIVE).findAll();

Body:
You need to use findAllSorted, like:

    realm.where(Product.class)
            .contains("productTags.name", tag, Case.INSENSITIVE)
            .findAllSorted("productTags.name", Sort.ASCENDING);

But the sorting will be based on the ASCII value of the String, which by the looks of it isn't enough for you. In that case you need to do the sorting yourself by using a Comparator


问:
A problem connecting to a MySQL DB using JDBC
Here's how I'm trying to connect:

```<code>try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }
</code>```

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...

答: Check that you can connect to the database from the mysql admin tool, that will drive out whether your mysql is running and that the port is open.</p>

Body:
Here's how I'm trying to connect:

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...


问:
Getting error while using custom activities in an Azure Data Factory pipeline
I am getting an error when running a custom activity in Azure Data Factory.
 The error is:

Job encountered scheduling error. Code: BlobDownloadMiscError
  Category: ServerError Message: Miscellaneous error encountered while
  downloading one of the specified Azure Blob(s).

I have been trying to follow the steps in this document  https://azure.microsoft.com/en-in/documentation/articles/data-factory-use-custom-activities/

答:
The problem is that you deployed a custom pipeline in a zipped file and in the meantime the container name containing that pipeline was renamed.
The specified Azure Blob is the pipeline you deployed.</p>


问:
reference to DOM element in Vue,js component computed property
Inside a Vue component computed property. How can I get a reference to the DOM element this method initiated by?

for instance:

<template>

</template>

```

NOTE:
I was printing the 'this' inside the method and couldn't find nothing that can help me over here....

thanks :)

答:
You should use method instead of computed property.</p>

```<code>methods : {
  getUrl(className){
    switch(className) {
      case 'image1':
        //code..
        break
      case 'image2':
        //code...
        break
    }
  }
}

<template>
  <img :src="getUrl('image1')" class="image1"/>
  <img :src="getUrl('image2')" class="image2"/>
</template>
</code>```

Body:
Inside a Vue component computed property. How can I get a reference to the DOM element this method initiated by?

for instance:

<template>

</template>

NOTE:
I was printing the 'this' inside the method and couldn't find nothing that can help me over here....

thanks :)

Body:
You should use method instead of computed property.

methods : {
  getUrl(className){
    switch(className) {
      case 'image1':
        //code..
        break
      case 'image2':
        //code...
        break
    }
  }
}

<template>
  <img :src="getUrl('image1')" class="image1"/>
  <img :src="getUrl('image2')" class="image2"/>
</template>


问:
Video stop when play music (spotify for example)
In my HTML code the video stops if I play a music at the same time. My code is like the following:

```<code><video autoplay id="video-bg" webkit-playsinline loop>
    <source src="videos/login_bg2.mp4" type="video/mp4">
    <source src="videos/login_bg2.webm" type="video/webm">
</video>
</code>```

How can I solve this?

Thanks in advance

答:
Set the AVAudioSession category works for me:

Find your AppDelegate.m from Xcode Proj.

import the header file: AVFoundation/AVFoundation.h

Add below code within the launchOptions {}

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];

My entire code like this:

#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];

    self.viewController = [[MainViewController alloc] init];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end```

NOTE: withOptions:AVAudioSessionCategoryOptionDuckOthers important.

Body:
In my HTML code the video stops if I play a music at the same time. My code is like the following:

<video autoplay id="video-bg" webkit-playsinline loop>
    <source src="videos/login_bg2.mp4" type="video/mp4">
    <source src="videos/login_bg2.webm" type="video/webm">
</video>

How can I solve this?

Thanks in advance

Body:
Set the AVAudioSession category works for me:

Find your AppDelegate.m from Xcode Proj.

import the header file: AVFoundation/AVFoundation.h

Add below code within the launchOptions {}

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];

My entire code like this:

#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];

    self.viewController = [[MainViewController alloc] init];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

NOTE: withOptions:AVAudioSessionCategoryOptionDuckOthers important.


问:
Can we integrate Paypal Payment Gateway with IONIC 1 or 2 app if yes then how...?
I have developed a mobile application for Android & iOS using IONIC framework. Now I want to integrate Payment Gateway with the same app.

I have gone through multiple links, but didn't get a final answer it is it possible to integrate Paypal with IONIC or not.

答:
It's not possible to implement PayPal to ionic IOS app, You can use inApp purchase plugin from Cordova to use for payment.

You can find it in below mentioned link.
https://github.com/AlexDisler/cordova-plugin-inapppurchase


问:
how to change one array into another while canceling the recurring variables?
I'm new to programing and was given a task of making a function that puts one array into the other with the following criteria: a variable in the destination array will repeat only once and the source and destination array will be of the same size.
the function i came up with is:

```<code>int RemoveDup (int src[],int dst[])
//recive two array compare them and copy the src array to dst,and only the none reacuring
//numbers,the arrays must be from the same size

{
int size_src;
int size_dst;
int i,n=0;
size_src = sizeof(src)/sizeof(int);//determine the size of source array
size_dst = sizeof(dst)/sizeof(int);//determine the size of destination array
if (size_src = size_dst);//checks that the array are in the same size
{
for(i = 0;i < size_src;i++)//the loop for advancing the copying process
{
dst[i] = src[i];
}
while (i<size_dst)
{
dst[i] = dst[i++];

if (dst[i] = dst[i++])//relay on the fact that if the function will find a similar varibale, the tested varibale will be set to 0 and the other one will come out clean in the check
dst[i] = 0;//eliminating the varibale in that specific address
}
}

return dst [i];
</code>```

but it doesn't seems to work and have no idea where it is going wrong.
any help or clue will be appreciated .

答:
well in fact it is possible to make a function recieve an array and not a pointer (given of course the size of the array is pre-defined).

so you can use:

```<code>int RemoveDup(int src[M],int dst[N]){
     .
     .
     .
return whatever;
</code>```

I will agree though that using pointers is better.
In my opinion you should write a recursive function to do that using of course pointers.
so that the next call is (*src+1) so you look at the next cell.
the exit condition is then:

```<code>if (sizeof(src) == 0) {
 //exit recursion statement.
}
</code>```

Body:
I'm new to programing and was given a task of making a function that puts one array into the other with the following criteria: a variable in the destination array will repeat only once and the source and destination array will be of the same size.
the function i came up with is:

int RemoveDup (int src[],int dst[])
//recive two array compare them and copy the src array to dst,and only the none reacuring
//numbers,the arrays must be from the same size

{
int size_src;
int size_dst;
int i,n=0;
size_src = sizeof(src)/sizeof(int);//determine the size of source array
size_dst = sizeof(dst)/sizeof(int);//determine the size of destination array
if (size_src = size_dst);//checks that the array are in the same size
{
for(i = 0;i < size_src;i++)//the loop for advancing the copying process
{
dst[i] = src[i];
}
while (i<size_dst)
{
dst[i] = dst[i++];

if (dst[i] = dst[i++])//relay on the fact that if the function will find a similar varibale, the tested varibale will be set to 0 and the other one will come out clean in the check
dst[i] = 0;//eliminating the varibale in that specific address
}
}

return dst [i];

but it doesn't seems to work and have no idea where it is going wrong.
any help or clue will be appreciated .

Body:
well in fact it is possible to make a function recieve an array and not a pointer (given of course the size of the array is pre-defined).

so you can use:

int RemoveDup(int src[M],int dst[N]){
     .
     .
     .
return whatever;

I will agree though that using pointers is better.
In my opinion you should write a recursive function to do that using of course pointers.
so that the next call is (*src+1) so you look at the next cell.
the exit condition is then:

if (sizeof(src) == 0) {
 //exit recursion statement.
}


问:
Why matplotlib is also printing data while doing a subplot?
Hi I can t figure out how to properly use pyplot for multiple plots, in addition to the plot it also print me the full array of data </p>

```<code># import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50) # kinda work, the problem is it print the array and then do the plot

plt.hist(x, 50, ax=axes[0,0]) # not wokring inner() got multiple values for keyword argument 'ax'
</code>```

答:
The important information you missed in the question is that you are using a Jupyter Notebook.
In order to show a plot in a jupyter notebook you may call plt.show() at the end of the cell, or you may use %matplotlib inline backend.

If using several subplots it's best to use the oo interface, i.e. not using plt.hist(...) but axes[0,2].hist(...). This way you directly set the axes to which to plot. (plt.hist(..., ax=...) does not exist - hence the error)

In order not to have the array printed you may suppress the output from the ax.hist() line by using a semicolon at the end (;).

```<code>axes[1,0].hist(x, 50);
</code>```

Complete Example (using plt.show()):

```<code>import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50);
axes[3,1].hist(x, 50);

plt.show()
</code>```

Complete example (using inline backend):

```<code>import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
%matplotlib inline

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50);
axes[3,1].hist(x, 50);
</code>```

Body:
Hi I can t figure out how to properly use pyplot for multiple plots, in addition to the plot it also print me the full array of data

# import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50) # kinda work, the problem is it print the array and then do the plot

plt.hist(x, 50, ax=axes[0,0]) # not wokring inner() got multiple values for keyword argument 'ax'

Body:
The important information you missed in the question is that you are using a Jupyter Notebook.
In order to show a plot in a jupyter notebook you may call plt.show() at the end of the cell, or you may use %matplotlib inline backend.

If using several subplots it's best to use the oo interface, i.e. not using plt.hist(...) but axes[0,2].hist(...). This way you directly set the axes to which to plot. (plt.hist(..., ax=...) does not exist - hence the error)

In order not to have the array printed you may suppress the output from the ax.hist() line by using a semicolon at the end (;).

axes[1,0].hist(x, 50);

Complete Example (using plt.show()):

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50);
axes[3,1].hist(x, 50);

plt.show()

Complete example (using inline backend):

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
%matplotlib inline

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50);
axes[3,1].hist(x, 50);


问:
View with table view only works with default View Controller
I need a settings screen in my app which I intend to create with a simple static table view. Unfortunately I ran into an issue. When I assign a custom view controller to the view in my storyboard the views table goes black during runtime.

This is despite the view controller not changing the default behaviour. I only override one method at this point, to put the Settings string in the title.

```<code>import Foundation
import UIKit

class SettingsViewController: UITableViewController {

    override func loadView() {
        self.title = "Settings"
    }

}
</code>```

When I remove the custom view controller the table appears normally.

I segue into the view using the following code.

```<code>guard let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "settingsViewController") as? UITableViewController else { // or SettingsViewcontroller for the first version
                print("Could not instantiate view controller with identifier of type SettingsViewController")
                return
            }
self.navigationController?.pushViewController(vc, animated:true)
</code>```

What could cause this issue?

答:
You have to call super.loadView(), You are overriding the UITableViewController's loadView() and not calling the super class method, Due to that you are getting black screen.

```<code>import Foundation
import UIKit

    class SettingsViewController: UITableViewController {

        override func loadView() {
            self.title = "Settings"
            super.loadView()
        }

    }
</code>```

Body:
I need a settings screen in my app which I intend to create with a simple static table view. Unfortunately I ran into an issue. When I assign a custom view controller to the view in my storyboard the views table goes black during runtime.

This is despite the view controller not changing the default behaviour. I only override one method at this point, to put the Settings string in the title.

import Foundation
import UIKit

class SettingsViewController: UITableViewController {

    override func loadView() {
        self.title = "Settings"
    }

}

When I remove the custom view controller the table appears normally.

I segue into the view using the following code.

guard let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "settingsViewController") as? UITableViewController else { // or SettingsViewcontroller for the first version
                print("Could not instantiate view controller with identifier of type SettingsViewController")
                return
            }
self.navigationController?.pushViewController(vc, animated:true)

What could cause this issue?

Body:
You have to call super.loadView(), You are overriding the UITableViewController's loadView() and not calling the super class method, Due to that you are getting black screen.

import Foundation
import UIKit

    class SettingsViewController: UITableViewController {

        override func loadView() {
            self.title = "Settings"
            super.loadView()
        }

    }


问:
Horizontal XOR in AVX
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

```<code>inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}
</code>```

答:
Implementation of direct analogue of _mm256_hadd_epi32() for XOR will be look something like this:

```<code>#include <immintrin.h>

template<int imm> inline __m256i _mm256_shuffle_epi32(__m256i a, __m256i b)
{
    return _mm256_castps_si256(_mm256_shuffle_ps(_mm256_castsi256_ps(a), _mm256_castsi256_ps(b), imm));
}

inline __m256i _mm256_hxor_epi32(__m256i a, __m256i b)
{
    return _mm256_xor_si256(_mm256_shuffle_epi32<0x88>(a, b), _mm256_shuffle_epi32<0xDD>(a, b));
}

int main()
{
    __m256i a = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
    __m256i b = _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8);
    __m256i c = _mm256_hxor_epi32(a, b);
    return 0;
}
</code>```

Title: Horizontal XOR in AVX

Body:
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}

Body:
Implementation of direct analogue of _mm256_hadd_epi32() for XOR will be look something like this:

#include <immintrin.h>

template<int imm> inline __m256i _mm256_shuffle_epi32(__m256i a, __m256i b)
{
    return _mm256_castps_si256(_mm256_shuffle_ps(_mm256_castsi256_ps(a), _mm256_castsi256_ps(b), imm));
}

inline __m256i _mm256_hxor_epi32(__m256i a, __m256i b)
{
    return _mm256_xor_si256(_mm256_shuffle_epi32<0x88>(a, b), _mm256_shuffle_epi32<0xDD>(a, b));
}

int main()
{
    __m256i a = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
    __m256i b = _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8);
    __m256i c = _mm256_hxor_epi32(a, b);
    return 0;
}


问:
How to convert ASN1_TIME to std::string
I am converting ASN1_TIME to std::string in this way:

```<code>std::string timeString;
BIO *bmem = BIO_new(BIO_s_mem());

if (ASN1_TIME_print(bmem, asn1Time)) {
    BUF_MEM * bptr;

    BIO_get_mem_ptr(bmem, &bptr);
    timeString.assign(std::string(bptr->data, bptr->length));
}
else { // Log error
}
BIO_free_all(bmem);
</code>```

Whats wrong with BUF_MEM use? I am getting very large numbers in bptr->length causing exception in std::string construction.

答:
The code in question is fine. The problem was due to mismatched headers.
Earlier headers from system were being used hence everything was fine. Since (most probably) El-Capitan, OSX no longer includes headers and discourages relying on OSX for SSL, to avoid issues due to version incompatibility.

See http://lists.apple.com/archives/macnetworkprog/2015/Jun/msg00025.html

That is exactly what was happening - Code was being linked against library on OS but the headers getting used were from different version as they were downloaded from openssl latest source.

Title: How to convert ASN1_TIME to std::string

Body:
I am converting ASN1_TIME to std::string in this way:

std::string timeString;
BIO *bmem = BIO_new(BIO_s_mem());

if (ASN1_TIME_print(bmem, asn1Time)) {
    BUF_MEM * bptr;

    BIO_get_mem_ptr(bmem, &bptr);
    timeString.assign(std::string(bptr->data, bptr->length));
}
else { // Log error
}
BIO_free_all(bmem);

Whats wrong with BUF_MEM use? I am getting very large numbers in bptr->length causing exception in std::string construction.


问:
run one where clause condition on the base of parameter
i have ha query like this </p>

```<code>Select * from table1
where col1 = true or col2 = false or
case when @param <> 2 then col3 = col4 end
</code>```

<p>last condition in where is throwing an error </p>

```<code> Incorrect syntax near '<'
</code>```

答:
I assume case in question is intended to express predicate "when  @param <> 2 then col3 = col4  must hold". I also assume for simplicity no column is nullable. This quite formally translates into !(@param <> 2) OR col3 = col4 which is equivalent to  @param = 2 OR col3 = col4

```<code>Select * from table1
where col1 = 'true' or col2 = 'false' or
@param = 2 OR col3 = col4
</code>```

Body:
i have ha query like this

Select * from table1
where col1 = true or col2 = false or
case when @param <> 2 then col3 = col4 end

last condition in where is throwing an error

 Incorrect syntax near '<'

Body:
I assume case in question is intended to express predicate "when  @param <> 2 then col3 = col4  must hold". I also assume for simplicity no column is nullable. This quite formally translates into !(@param <> 2) OR col3 = col4 which is equivalent to  @param = 2 OR col3 = col4

Select * from table1
where col1 = 'true' or col2 = 'false' or
@param = 2 OR col3 = col4