问:
Knockoutjs google maps binding with Ajax call
I have scratched my head on this code with extensive reading and tinkering but can't seem to get myself to apply knockout js on google maps. Let me know if am on the right track. I am rendering a map with some default markers (which is working as intended) then want to update them with points derived from making an ajax call triggered by on change event on the select form. It is possible I am missing on something very basic as this is the first time am using google maps with KO and not quite sure where to separate the  V and the VM

```<code>my HTML

    // html form with select option in jinja2
    <form action="">
    <select name="categories" onchange="showCategory(this.value)">
    <option value="">Select Category</option>
    {% for c in cat %}
    <option value={{c.id}}>{{c.name}}</option>
    {% endfor %}
    </select>
    </form>

//a div to display XMLHttpRequest response to make sure am getting that part right
        <div id="demo">
    <h1>The XMLHttpRequest Object</h1>
    </div>
 //the map div
    <div id="map"></div>
        <script>
</code>```

my variables with plus XMLHttpRequest

```<code>//Declare Map variable and markers array
      var map;
      var marker;
      var markers = [];
      var lat = -1.2886009200028272;
      var lng = 36.822824478149414;

      var features = [
          {
            name: name,
            position: {lat:lat, lng: lng},
            type: 'parking'
          },
          {
            name: name,
            position: {lat:-1.287785734541792, lng: 36.82161211967468},
            type: 'info'
          }
        ];

      // make XMLHttpRequest and update the above variables
      function showCategory(cat_id) {
      var xhttp;
      if (cat_id == "") {
      document.getElementById("demo").innerHTML = "Please select a Category";
      return;
      }
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      var my_text = this.responseText;
      obj = JSON.parse(my_text);
      raw_lat = obj.Addresses[0].lat
      lat = parseFloat(raw_lat)
      raw_lng = obj.Addresses[0].lng
      lng = parseFloat(raw_lng)
      features = [
          {
            position: {lat:lat, lng: lng},
            type: 'info'
          },
          {
            name: name,
            position: {lat:-1.287785734541792, lng: 36.82161211967468},
            type: 'parking'
          }
        ];

      //check to confirm am getting a response
      document.getElementById("demo").innerHTML =
      this.responseText;

    }
    };

    xhttp.open("GET", "/loc/"+cat_id, true);
    xhttp.send();
    };

    //Fetch relevant map icons from Google

      var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
        var icons = {
          parking: {
            icon: iconBase + 'parking_lot_maps.png'
          },
          library: {
            icon: iconBase + 'library_maps.png'
          },
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };
</code>```

The map code

```<code>//create the map and the view model
      function initMap() {
        var ViewModel = function() {
          var self = this
          self.lat = ko.observable(lat)
          self.lng = ko.observable(lng)
        self.map = new google.maps.Map(document.getElementById("map"), {
          zoom: 16,
          center: new google.maps.LatLng(self.lat(), self.lng()),
          mapTypeId: 'roadmap'
        });

       self.updatedfeatures = ko.observableArray(features.slice());
        // Create markers.
        self.updatedfeatures().forEach(function(feature) {
            marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: self.map
          });
          markers.push(marker);
        });
      };
      ko.applyBindings(new ViewModel());
      };
</code>```

答:
For this purpose, this turned out to be an overkill. The gist is that the XMLHttpRequest is asynchronous, and the ajax call would set lat and lng values but after the rest of the javascript has run. Of course there is promise in js and deferred updates in KO but i realised there was a much easier way to get the same thing done. I simply moved the XMLHttpRequest function into the map function and used document.getElementById("myId").addEventListener("change", myFunction); to make a the ajax request when select value changes, then update the markers. I will not need KO for that, but of course it will come in handy as I do further sorting of the makers after the call

So this is the section of code that I changed

```<code>//create the map and the view model
      function initMap() {
        var ViewModel = function() {
          var self = this
          self.lat = ko.observable(lat)
          self.lng = ko.observable(lng)

        self.lng.subscribe(function(newValue) {
        alert("new values are " + newValue);
        });

        self.map = new google.maps.Map(document.getElementById("map"), {
          zoom: 16,
          center: new google.maps.LatLng(self.lat(), self.lng()),
          mapTypeId: 'roadmap'
        });

       self.updatedfeatures = ko.observableArray(features);
        // Create markers.
        self.updatedfeatures().forEach(function(feature) {
            self.marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: self.map
          });
          markers.push(self.marker);
        });

        document.getElementById("my_cats").addEventListener("change", myFunction);
        function myFunction() {
      var cat_id = document.getElementById("my_cats").value;
      var xhttp;
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      var my_text = this.responseText;
      obj = JSON.parse(my_text);
      var raw_lat = obj.Addresses[0].lat;
      lat = parseFloat(raw_lat);
      var raw_lng = obj.Addresses[0].lng;
      lng = parseFloat(raw_lng);
      features = [
          {
            position: {lat:lat, lng: lng},
            type: 'parking'
          },
          {
            name: name,
            position: {lat:-1.287785734541792, lng: 36.82161211967468},
            type: 'parking'
          }
        ];
      features.forEach(function(feature) {
            marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: self.map
          });
          markers.push(marker);
        });

    }
    };

    xhttp.open("GET", "/loc/1", true);
    xhttp.send();
      }

      };
      ko.applyBindings(new ViewModel());

      };
</code>```

Body:
I have scratched my head on this code with extensive reading and tinkering but can't seem to get myself to apply knockout js on google maps. Let me know if am on the right track. I am rendering a map with some default markers (which is working as intended) then want to update them with points derived from making an ajax call triggered by on change event on the select form. It is possible I am missing on something very basic as this is the first time am using google maps with KO and not quite sure where to separate the  V and the VM

my HTML

    // html form with select option in jinja2
    <form action="">
    <select name="categories" onchange="showCategory(this.value)">
    <option value="">Select Category</option>
    {% for c in cat %}
    <option value={{c.id}}>{{c.name}}</option>
    {% endfor %}
    </select>
    </form>

//a div to display XMLHttpRequest response to make sure am getting that part right

The XMLHttpRequest Object

 //the map div

Body:
For this purpose, this turned out to be an overkill. The gist is that the XMLHttpRequest is asynchronous, and the ajax call would set lat and lng values but after the rest of the javascript has run. Of course there is promise in js and deferred updates in KO but i realised there was a much easier way to get the same thing done. I simply moved the XMLHttpRequest function into the map function and used document.getElementById("myId").addEventListener("change", myFunction); to make a the ajax request when select value changes, then update the markers. I will not need KO for that, but of course it will come in handy as I do further sorting of the makers after the call

So this is the section of code that I changed

//create the map and the view model
      function initMap() {
        var ViewModel = function() {
          var self = this
          self.lat = ko.observable(lat)
          self.lng = ko.observable(lng)

        self.lng.subscribe(function(newValue) {
        alert("new values are " + newValue);
        });

        self.map = new google.maps.Map(document.getElementById("map"), {
          zoom: 16,
          center: new google.maps.LatLng(self.lat(), self.lng()),
          mapTypeId: 'roadmap'
        });

       self.updatedfeatures = ko.observableArray(features);
        // Create markers.
        self.updatedfeatures().forEach(function(feature) {
            self.marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: self.map
          });
          markers.push(self.marker);
        });

        document.getElementById("my_cats").addEventListener("change", myFunction);
        function myFunction() {
      var cat_id = document.getElementById("my_cats").value;
      var xhttp;
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      var my_text = this.responseText;
      obj = JSON.parse(my_text);
      var raw_lat = obj.Addresses[0].lat;
      lat = parseFloat(raw_lat);
      var raw_lng = obj.Addresses[0].lng;
      lng = parseFloat(raw_lng);
      features = [
          {
            position: {lat:lat, lng: lng},
            type: 'parking'
          },
          {
            name: name,
            position: {lat:-1.287785734541792, lng: 36.82161211967468},
            type: 'parking'
          }
        ];
      features.forEach(function(feature) {
            marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: self.map
          });
          markers.push(marker);
        });

    }
    };

    xhttp.open("GET", "/loc/1", true);
    xhttp.send();
      }

      };
      ko.applyBindings(new ViewModel());

      };


来源: stackexchange

问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e an initialization (of the pointer itself):

```<code>int *         q                      = 8;
~~~~~         ~                      ~~~
type is int*; name of variable is q; initialized with 8
</code>```

The 2nd one is assignment (of the object pointed by the pointer):

```<code>*q                              = 6;
~~                              ~~~
dereference on q via operator*; assign the resulting lvalue pointed by q to 6
</code>```

And, int *p = 6; means define a variable named p with type int* and initialize it with 6, which fails because 6 can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").

ContentLicense: CC BY-SA 3.0

Body:
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e an initialization (of the pointer itself):

int *         q                      = 8;
~~~~~         ~                      ~~~
type is int*; name of variable is q; initialized with 8

The 2nd one is assignment (of the object pointed by the pointer):

*q                              = 6;
~~                              ~~~
dereference on q via operator*; assign the resulting lvalue pointed by q to 6

And, int *p = 6; means define a variable named p with type int* and initialize it with 6, which fails because 6 can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").


问:
iPhone Best practices for large number of animations using UIImageView
Just requesting a little advice animating images on the iphone. I'm building an app that consists of a character with 5 animations.

Each animation consists of roughly 50 images with an average duration of 3 seconds.

I was going to create an array of images for each animation, have these as the source for an UIImageView and switch these as needed. But as you can guess this approach kills my iphone's memory and thus the app. (250 images @ 130K each!)

So this got me wondering how other people get around this? Maybe change the animations to movies?

Thanks for any advice.

答:
I'd recommend the movie route, if you can get away with it. It'll be cleaner and likely much more performant.

However, if you're stuck with images for some reason, here's performance from loading 5000 full-frame images in succession:

```<code>[UIImage imageWithData:...] // 44.8 seconds

[UIImage imageWithContentsOfFile:...] // 52.3 seconds

[[UIImage alloc] initWithContentsOfFile:…] // 351.8 seconds

[UIImage imageNamed:...] // hung due to caching
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd recommend the movie route, if you can get away with it. It'll be cleaner and likely much more performant.

However, if you're stuck with images for some reason, here's performance from loading 5000 full-frame images in succession:

[UIImage imageWithData:...] // 44.8 seconds

[UIImage imageWithContentsOfFile:...] // 52.3 seconds

[[UIImage alloc] initWithContentsOfFile:…] // 351.8 seconds

[UIImage imageNamed:...] // hung due to caching


问:
How to set client side timestamp in spring data cassandra?
In datastax driver we have api like

withTimestampGenerator(new AtomicMonotonicTimestampGenerator())

to enable the feature to setting timestamp per query at client side. How can we achieve same with spring data canssandra.

I am aware that i can use "USING TIMESTAMP value" in cql but is there something which spring data cassandra provide ? I dont find such api in CassandraClusterFactoryBean .

答:
The timestamp capability is available in SD 1.5.x,
  public void setTimestampGenerator(TimestampGenerator timestampGenerator) {
        this.timestampGenerator = timestampGenerator;
    }

https://github.com/spring-projects/spring-data-cassandra/blob/cc4625f492c256e5fa3cb6640d19b4e048b9542b/spring-data-cassandra/src/main/java/org/springframework/data/cql/config/CassandraCqlClusterFactoryBean.java.


问:
How do I programmatically add a view right under the navigation bar?
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

```<code>override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}
</code>```

With this being the result:

And I tried by setting the frame of my subview:

```<code>override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}
</code>```

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?

答:
Height of status bar is 20.You should consider status bar also while assigning y of your label. Your viewDidAppear should be

```<code>override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height+20, width: navigationBar.frame.width, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
 }
</code>```

Body:
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}

With this being the result:

And I tried by setting the frame of my subview:

override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?

Body:
Height of status bar is 20.You should consider status bar also while assigning y of your label. Your viewDidAppear should be

override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height+20, width: navigationBar.frame.width, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
 }

ContentLicense: CC BY-SA 4.0


问:
Android Studio 3 unable to build kotlin fragment
Im trying to use Kotlin with Android Studio 3.0 with my existing project.
I have created a fragment using kotlin. Im trying to use the kotlin fragment in my Java Activity. But everytime i try to run it I get

```<code>Error:(209, 5) error: cannot find symbol class BlankFragment
</code>```

BlankFragment.kt

```<code>import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class BlankFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null

    private var mListener: OnFragmentInteractionListener? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1)
            mParam2 = getArguments().getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
            = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))

}

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            textView {
                text = R.string.app_name

            }
        }
    }
}
</code>```

project - build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.1'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
You seem to be missing all Kotlin dependencies other than having the version declared (you should probably update that to 1.1.3 as well, which is the latest available as of now).

You can configure your project in two ways:

Remove the Kotlin version you have declared, and then go to Tools -> Kotlin -> Configure Kotlin in Project, and follow the steps presented there.

Alternatively, you can do it in a more manual way by following the steps described here to set up the Kotlin Gradle plugin, including following the link that's there and setting up the standard library dependency as well.

Body:
Im trying to use Kotlin with Android Studio 3.0 with my existing project.
I have created a fragment using kotlin. Im trying to use the kotlin fragment in my Java Activity. But everytime i try to run it I get

Error:(209, 5) error: cannot find symbol class BlankFragment

BlankFragment.kt

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class BlankFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null

    private var mListener: OnFragmentInteractionListener? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1)
            mParam2 = getArguments().getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
            = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))

}

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            textView {
                text = R.string.app_name

            }
        }
    }
}

project - build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.1'
    ext.anko_version = '0.10.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app build.gradle

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        splits {
            abi {
                enable true //enables the ABIs split mechanism
                reset() //reset the list of ABIs to be included to an empty string
                include 'x86', 'armeabi', 'armeabi-v7a', 'mips', 'x86_64', 'arm64-v8a'
                universalApk true
            }
        }
    project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.versionCodeOverride =
                    project.ext.versionCodes.get(output.getFilter(
                            com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
        }
    }
}
compileSdkVersion 25
buildToolsVersion '26'
defaultConfig {
    applicationId "com.example"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 20
    versionName "v.32"
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
}
packagingOptions {
    exclude 'LICENSE.txt'
}
repositories {
    maven { url "https://jitpack.io" }
}
lintOptions {
    disable "ResourceType"
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    //    compile 'io.realm:realm-android:0.87.5'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.github.jkwiecien:EasyImage:1.3.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.yarolegovich:lovely-dialog:1.0.4'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.github.ParkSangGwon:TedPermission:v1.0.12'
    compile 'com.github.lovetuzitong:MultiImageSelector:1.2'
    compile 'com.github.piotrek1543:CustomSpinner:0.1'
    compile 'com.github.ganfra:material-spinner:1.1.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.appyvet:materialrangebar:1.3'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.mixpanel.android:mixpanel-android:4.+'
    compile 'com.github.ericwlange:AndroidJSCore:3.0.1'
    compile 'com.android.support:multidex:1.0.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile "org.jetbrains.anko:anko-sdk25:$anko_version"
    compile "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
    compile files('libs/bcpkix-jdk15on-1.56.0.0.jar')
    compile files('libs/core-1.56.0.0.jar')
    compile files('libs/prov-1.56.0.0.jar')
}
apply plugin: 'com.google.gms.google-services'


问:
How to slice Excel data using win32com in Python (3.6)
I have data in Excel that I want to split.

Here is my code

```<code>import win32com.client

excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Open('C:\\Users\\a\\Desktop\\bin256.xlsx')
ws = wb.ActiveSheet
input_number = ws.Range('U4:U15363')
number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
</code>```

But I get this error:

```<code>Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
  File "<pyshell#13>", line 1, in <listcomp>
    number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
  File "C:\Users\a\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
    return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
TypeError: Objects of type 'slice' can not be converted to a COM VARIANT
</code>```

How can I fix that? Thanks in advance.

答:
Did you just want to open excel?

Maybe you can try pandas

```<code>import pandas as pd
file_path=r'E:\download\tmp\test.xlsx'
file_path='./tmp/test.xlsx'
df_name.to_excel(file_path,sheet_name='Sheet1',index=False)
</code>```

Body:
I have data in Excel that I want to split.

Here is my code

import win32com.client

excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Open('C:\\Users\\a\\Desktop\\bin256.xlsx')
ws = wb.ActiveSheet
input_number = ws.Range('U4:U15363')
number = [input_number[i:i+60] for i in range(0,len(input_number),60)]

But I get this error:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
  File "<pyshell#13>", line 1, in <listcomp>
    number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
  File "C:\Users\a\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
    return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
TypeError: Objects of type 'slice' can not be converted to a COM VARIANT

How can I fix that? Thanks in advance.

Body:
Did you just want to open excel?

Maybe you can try pandas

import pandas as pd
file_path=r'E:\download\tmp\test.xlsx'
file_path='./tmp/test.xlsx'
df_name.to_excel(file_path,sheet_name='Sheet1',index=False)


问:
Proper way to populate dropdownlist based off another value?
I'm running into a minor issue with some ASP.Net code I'm working on. For simplicity sake lets say I have two dropdownlists, one that is full of various items and another that is full of other items, but based off the selected item of the first dropdownlist. I currently set variables into hidden inputs to check to see if the item in the first dropdownlist has changed and if it has to change the second dropdownlist, but I'm also having to check to make sure that if something else causes a postback to NOT repopulate the second dropdownlist as to not lose what is currently selected by the user. This check also allows me to make sure that when I navigate away from the page, the correct values are selected and not something replaced by a postback repopulation.

I'm new to ASP.Net/HTML/CSS/Javascript and the like. I know while what I have works, it isn't even close to being the correct way to do things. Please help me correct my ways and figure out the BEST way to solve this current problem. Some good ASP.Net tutorial websites would be nice too as I need to keep improving my skills with it.

答:
You probably want to have a look at

DropDownList

ListControl.AutoPostBack Property

ListControl.SelectedIndexChanged
Event

and some examples in DropDownList Class


问:
Need to duplicate the same element in the DOM 4 times using Jquery
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

```<code>function Pin(caixaPin){
 var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('<div></div>');
</code>```

Thanks !!

答: Just execute your function pin in loop</p>

Body:
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

function Pin(caixaPin){
 var $temp;
  $temp = $("

");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('

');

Thanks !!

Body: Just execute your function pin in loop


答: In your first statement you are declaring and initializing the pointer to some value of type int (on the same line). In your second statement you are changing the value pointed to by a pointer. Two different things. What you have there is initialization followed by an assignment. Don't let the * confuse you.

Title: Why can't I directly assign an int to an int pointer like this: int *p = 6;?

Body:
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?


问:
Unable to send AWS email using my sender id
I am sending AWS email using SNS. It's working fine but the only thing i am unable to find anywhere is how to replace the no-reply@sns.amazonaws.com via amazonses.com  id with my own email id..

I had used:

```<code>$result = $client->publish(array(
    'TopicArn' => $topicArn,
    'Message' => 'testing...',
    'Subject' => 'Test Msg',
    'DisplayName'=>'abc@gmail.com'
));
</code>```

I have used many other options also but every time it sends email through no-reply@sns.amazonaws.com

答:
can i remove the email id hat comes like no-reply@sns.amazonaws.com.

No, you can't.

if I have 5 persons subscribed to topic, can All the recipients of the email should be visible to every one.

SNS doesn't consider this as as 1 email sent to 5 recipients.  It sends 5 separate emails, 1 to each recipient.

For these capabilities, you'll need to use Simple Email Service (SES), not SNS.

Body:
I am sending AWS email using SNS. It's working fine but the only thing i am unable to find anywhere is how to replace the no-reply@sns.amazonaws.com via amazonses.com  id with my own email id..

I had used:

$result = $client->publish(array(
    'TopicArn' => $topicArn,
    'Message' => 'testing...',
    'Subject' => 'Test Msg',
    'DisplayName'=>'abc@gmail.com'
));

I have used many other options also but every time it sends email through no-reply@sns.amazonaws.com


问:
@Umbraco.TypedMedia(MyProperty) is null in Umbraco 7.6.1
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

```<code>@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}
</code>```

But bannerMediaItem is always null even though I know it exists. If I do this..

```<code>@Model.Content.Image
</code>```

It returns the id of the image e.g. 1086

答:
Ok so I was nearly right and with help from @Harsheet this worked...</p>

```<code>@{
   var media = Umbraco.TypedMedia(Model.Content.GetPropertyValue<int>("image"));
   var thumbUrl = media.Url;
}
</code>```

Body:
I'm using Umbraco 7.6.1 and I'm trying to get the url for a media image using the code below in razor.

@{
   var bannerMediaItem = Umbraco.TypedMedia(Model.Content.Image);
   var bannerUrl = bannerMediaItem.Url;
}

But bannerMediaItem is always null even though I know it exists. If I do this..

@Model.Content.Image

It returns the id of the image e.g. 1086

Body:
Ok so I was nearly right and with help from @Harsheet this worked...

@{
   var media = Umbraco.TypedMedia(Model.Content.GetPropertyValue<int>("image"));
   var thumbUrl = media.Url;
}


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答: Because the actual type of a var is inferred from the context in which it is used. For fields (class member variables), there is no such context.</p>

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.


问:
Add an attribute with a value in its td tag with jQuery
I need help with adding an attribute to  tag in table.

I have a loop which output an image an checkbox. (see picture below). when user click the first, it enables should enable the next checkbox to be enabled.

I would like user to click first image, than second than third and so on. I do not want user to click any image random.

It works if i get rid of  tags. SO my problem is  tags

HTML

```<code> <table class="table table-bordered">
   <?php
     $count = 1;
     for($x=0; $x < 5; $x++){
   ?>

   <td>
     <div class="thumb">
       <label for="image <?php echo $count;?>"><img class="img" src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
       <input type="checkbox" class="chk " id="image <?php echo $count;?>" name="tick" value="0" />
     </div>
   </td>

    <?php
      $count++; }
    ?>

 </table>
</code>```

JavaScript

```<code><script>
 $(function() {

 var imageSelector = 'input[type="checkbox"][name="tick"]';
 $(imageSelector)
.on('click', function() {
  var $this = $(this);

  if($this.is(':checked')) {
    $this
      .nextAll(imageSelector)
      .first()
      .removeAttr('disabled')
      .removeAttr('checked');
    return;
  }

  $this
    .nextAll(imageSelector)
    .attr('disabled', 'disabled')
    .removeAttr('checked');
})
.attr('disabled', 'disabled')
.removeAttr('checked')
.first().removeAttr('disabled');

});
</script>
</code>```

How I can add attribue to  tags

答:
Here is my version if I understood you correctly.

PS: I suggest you do not have spaces in the ID

$(function() {

  var imageSelector = 'input[type="checkbox"][name="tick"]';
  $(imageSelector).on('click', function() {
      var $this = $(this);
      if (this.checked) {
        $this.closest("td").next("td")
          .find(imageSelector)
          .prop('disabled', false)
          .prop('checked', false);
      } else { // uncheck and disable the following checkboxes
        $this.closest("td").nextAll("td").each(function() {
          $(this).find(imageSelector)
            .prop('disabled', true)
            .prop('checked', false);
        });
      }
    })
    .prop('disabled', 'disabled')
    .prop("checked", false)
    .first().prop('disabled', false);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table table-bordered">
  <tr>
    <td>
      <div class="thumb">
        <label for="image1"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image1" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image2"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image2" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image3"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image3" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image4"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image4" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image5"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image5" name="tick" value="0" />
      </div>
    </td>
  </tr>
</table></code>```

Body:
I need help with adding an attribute to  tag in table.

I have a loop which output an image an checkbox. (see picture below). when user click the first, it enables should enable the next checkbox to be enabled.

I would like user to click first image, than second than third and so on. I do not want user to click any image random.

It works if i get rid of  tags. SO my problem is  tags

HTML

   <?php
     $count = 1;
     for($x=0; $x < 5; $x++){
   ?>

       <label for="image <?php echo $count;?>">
       <input type="checkbox" class="chk " id="image <?php echo $count;?>" name="tick" value="0" />

    <?php
      $count++; }
    ?>

JavaScript

How I can add attribue to  tags

Body:
Here is my version if I understood you correctly.

PS: I suggest you do not have spaces in the ID

$(function() {

  var imageSelector = 'input[type="checkbox"][name="tick"]';
  $(imageSelector).on('click', function() {
      var $this = $(this);
      if (this.checked) {
        $this.closest("td").next("td")
          .find(imageSelector)
          .prop('disabled', false)
          .prop('checked', false);
      } else { // uncheck and disable the following checkboxes
        $this.closest("td").nextAll("td").each(function() {
          $(this).find(imageSelector)
            .prop('disabled', true)
            .prop('checked', false);
        });
      }
    })
    .prop('disabled', 'disabled')
    .prop("checked", false)
    .first().prop('disabled', false);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table table-bordered">
  <tr>
    <td>
      <div class="thumb">
        <label for="image1"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image1" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image2"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image2" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image3"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image3" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image4"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image4" name="tick" value="0" />
      </div>
    </td>
    <td>
      <div class="thumb">
        <label for="image5"><img class="img"
   src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
        <input type="checkbox" class="chk " id="image5" name="tick" value="0" />
      </div>
    </td>
  </tr>
</table>


问:
Extract details from dir output in Windows XP using for loop (batch script)
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)
</code>```

In Windows 7 the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config
</code>```

In Windows XP the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config
</code>```

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

答:
Time formats provided in windows listings depend on user-settings. Unfortunately, you've posted doctored listings, not actual data (evidence - exactly the same time and date for each of the data elements listed, bar the PM flag, despite their being allegedly on different systems)

fix : Easy way is to align the systems' UI settings - use the same format on both machines.

code to cope:

@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "required_format=12"

for /f "tokens=1-5 delims= " %%a in (
 'type q44964366.txt^|FINDSTR /L /E /c:" ."') do (
 set "dt=%%a"
 set dirdate=%%a
 set dirtime=%%b
 IF "%%e"=="." (
  REM reading 12-hr format - convert to 24-hr
  IF "!dirtime:~0,2!"=="12" (
   IF /i "%%c"=="PM" (
    SET "dirtime=12!dirtime:~2!"
   ) else (
    SET "dirtime=00!dirtime:~2!"
   )
  ) ELSE (
   IF /i "%%c"=="PM" (
    SET /a $=2!dirtime:~0,2!-88
    SET "dirtime=!$:~-2!!dirtime:~2!"
   )
  )
 )
 REM else is in 24-hr format already
 IF %required_format%==12 (
  SET /a $=1!dirtime:~0,2!
  IF !$!==100 SET "dirtime=12!dirtime:~2! AM"
  IF !$! gtr 100 IF !$! leq 111 SET "dirtime=!dirtime! AM"
  IF !$!==112 SET "dirtime=12!dirtime:~2! PM"
  IF !$! gtr 112 SET /a $=$-12&SET "dirtime=!$:~-2!!dirtime:~2! PM"
 )
 echo !dirdate!, !dirtime!
 set dirday=!dirdate:~0,2!
 echo !dirday!
)

GOTO :EOF
```

For testing, I used a file containing typical dir lines. You would need to substitute the dir command from the original for the type q44964366.txt

The caret (^) before the pipe (|) tells cmd that the pipe is part of the command to be executed. The pipe outputs the data (from the dir command) and filds all those lines which /L Literally /E end /c:"string" with the constant string - note that this is Space. which neatly filters out all but the . directoryname, so proceeding with the analysis of the processing on the . name - which is the only name the findstr will allow through...

Since we now are using tokens=1-5 then %%e can only be set to . if the line is in 12-hr format, else it's in 24-hr format. To convert to 24-hr format, we need to see whether %%c is PM (else it's AM) and if so, add 12 to the hours digits except for 12 in the hours digits, when we need to set the hours digits to 00 for AM and 12 for PM.

The last of these conversions is obvious, but for non-12:xx PM, we take the two hours digits and append them to 2 making a string 2hh. cmd mathematics treats any numeric starting 0 as octal, so 09:xx would create an error. 209 it can cope with as it's decimal. From that, subtract 88, which is 100-12. This produces a 3-digit number which batch treats as a string, and we need the last 2 of the characters.

You don't specify your preferred format, so we may need to conver to 12-hr (in the code, if that has been chosen in required_format)

In 12-hr mode, we need to subtract 12 hours if the time is PM, and take care of the special values 12:xx and 00:xx. This is again done by stringing the first 2 digits of the time with a constant to form a nice 3-digit decimal value. 100 means 12:xx AM 112 means 12:xx PM 101-111 means we simply need to add AM and if it's greater than 112 (eg 15:xx in 24-hour format) then we need to subtract 12 and take the last 2 characters of the result as the hours digits; then add PM.

And done.

type q44964366.txt replaced by the dir command from the original

'dir /ad /tc "%path_of_folder%."^|FINDSTR /L /E /c:" ."') do (

Body:
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)

In Windows 7 the dir command in the command prompt outputs something similar to:

   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config

In Windows XP the dir command in the command prompt outputs something similar to:

   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

Body:
Time formats provided in windows listings depend on user-settings. Unfortunately, you've posted doctored listings, not actual data (evidence - exactly the same time and date for each of the data elements listed, bar the PM flag, despite their being allegedly on different systems)

fix : Easy way is to align the systems' UI settings - use the same format on both machines.

code to cope:

@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "required_format=12"

for /f "tokens=1-5 delims= " %%a in (
 'type q44964366.txt^|FINDSTR /L /E /c:" ."') do (
 set "dt=%%a"
 set dirdate=%%a
 set dirtime=%%b
 IF "%%e"=="." (
  REM reading 12-hr format - convert to 24-hr
  IF "!dirtime:~0,2!"=="12" (
   IF /i "%%c"=="PM" (
    SET "dirtime=12!dirtime:~2!"
   ) else (
    SET "dirtime=00!dirtime:~2!"
   )
  ) ELSE (
   IF /i "%%c"=="PM" (
    SET /a $=2!dirtime:~0,2!-88
    SET "dirtime=!$:~-2!!dirtime:~2!"
   )
  )
 )
 REM else is in 24-hr format already
 IF %required_format%==12 (
  SET /a $=1!dirtime:~0,2!
  IF !$!==100 SET "dirtime=12!dirtime:~2! AM"
  IF !$! gtr 100 IF !$! leq 111 SET "dirtime=!dirtime! AM"
  IF !$!==112 SET "dirtime=12!dirtime:~2! PM"
  IF !$! gtr 112 SET /a $=$-12&SET "dirtime=!$:~-2!!dirtime:~2! PM"
 )
 echo !dirdate!, !dirtime!
 set dirday=!dirdate:~0,2!
 echo !dirday!
)

GOTO :EOF

For testing, I used a file containing typical dir lines. You would need to substitute the dir command from the original for the type q44964366.txt

The caret (^) before the pipe (|) tells cmd that the pipe is part of the command to be executed. The pipe outputs the data (from the dir command) and filds all those lines which /L Literally /E end /c:"string" with the constant string - note that this is Space. which neatly filters out all but the . directoryname, so proceeding with the analysis of the processing on the . name - which is the only name the findstr will allow through...

Since we now are using tokens=1-5 then %%e can only be set to . if the line is in 12-hr format, else it's in 24-hr format. To convert to 24-hr format, we need to see whether %%c is PM (else it's AM) and if so, add 12 to the hours digits except for 12 in the hours digits, when we need to set the hours digits to 00 for AM and 12 for PM.

The last of these conversions is obvious, but for non-12:xx PM, we take the two hours digits and append them to 2 making a string 2hh. cmd mathematics treats any numeric starting 0 as octal, so 09:xx would create an error. 209 it can cope with as it's decimal. From that, subtract 88, which is 100-12. This produces a 3-digit number which batch treats as a string, and we need the last 2 of the characters.

You don't specify your preferred format, so we may need to conver to 12-hr (in the code, if that has been chosen in required_format)

In 12-hr mode, we need to subtract 12 hours if the time is PM, and take care of the special values 12:xx and 00:xx. This is again done by stringing the first 2 digits of the time with a constant to form a nice 3-digit decimal value. 100 means 12:xx AM 112 means 12:xx PM 101-111 means we simply need to add AM and if it's greater than 112 (eg 15:xx in 24-hour format) then we need to subtract 12 and take the last 2 characters of the result as the hours digits; then add PM.

And done.

type q44964366.txt replaced by the dir command from the original

'dir /ad /tc "%path_of_folder%."^|FINDSTR /L /E /c:" ."') do (


问:
PhpStorm file watchers to minify and merge JS files from multiple folders
I am trying to accomplish the following.

I have raw assets such as JavaScript source files in folder assets/js in application root. I also have folder public where should go minified files that will be loaded in application.

What I want is when I change my js files I want to IDE create minified versions of it, and then to merge those minified files into one in public folder.

I need two file watchers but don't know how to configure them.

I tried default options for YUI Compressor and those build minified files in the same folder where source files are. But I can't manage to merge those files with File Watcher.

I also created two scopes, one for source JS files, and one for minified JS files.

I am not even sure if File Watchers can do this. I am talking about multiple folders, and recursive scopes.

I would appreciate any help.

答:
What I would do is let the YUI compressor create on save the .min.js files and then use as an external tool (Settings->Tools->External Tools) this tool compressJS for linux OS (if you have windows you could try to adapt the script or run this in a linux env like a docker,vm etc - eventually use Remote SSH external Tool from settings).

In the end you can set a keymap for the tool to run it whenever you want.
You can set it also as a file watcher, but this will be too much processing imho.


答: Frame of navigationBar is (0 20; 375 44), you can set label y position to 64.</p>

Title: How do I programmatically add a view right under the navigation bar?


问:
How perform entire model validation in loopback?
Consider the following example:
Suppose there is a object with enum property. If enum property has 5 value, the field value should be equal to 5, if enum is super object must have properties up and down. So the js code can be like that:

```<code>if (obj.enum === 5) {
    if (obj.value != 5) {
        //error here
    }
}

if (obj.enum === 'super') {
    if (obj.up === undefined || obj.down === undefined ) {
        //error here
    }
}
</code>```

How to integrate this code into loopbackjs???

E.g. this is not a fields validation (custom or not), this it model validation. So isValid funciton (see below) and validate method can not be used. The validate validates only one property.

Here is very similar question but it ended up with custiom property validation.

Here is example with isValid funciton in validatable.js. Please note that this only invoking validation, there is no way to add additional errors or add additional validation

答: Use this answer as workaround. Pass one of always present fields to validate method and add custom error code and messages inside customValidator funciton.

Body:
Consider the following example:
Suppose there is a object with enum property. If enum property has 5 value, the field value should be equal to 5, if enum is super object must have properties up and down. So the js code can be like that:

if (obj.enum === 5) {
    if (obj.value != 5) {
        //error here
    }
}

if (obj.enum === 'super') {
    if (obj.up === undefined || obj.down === undefined ) {
        //error here
    }
}

How to integrate this code into loopbackjs???

E.g. this is not a fields validation (custom or not), this it model validation. So isValid funciton (see below) and validate method can not be used. The validate validates only one property.

Here is very similar question but it ended up with custiom property validation.

Here is example with isValid funciton in validatable.js. Please note that this only invoking validation, there is no way to add additional errors or add additional validation


问:
Error while trying to shift row entries of POSIXct time format in R?
I have a data set of time (PSIXct format ) with 'newtime' & 'endtime'

```<code>datatest <-
  newtime           endtime
7/7/2017 2:12:00    7/7/2017 2:13:00
7/7/2017 2:59:00    7/7/2017 2:59:00
7/7/2017 18:23:00   7/7/2017 18:23:00
7/7/2017 18:23:00   7/7/2017 18:23:00
7/7/2017 20:40:00   7/7/2017 22:25:00
7/7/2017 20:40:00   7/7/2017 22:33:00
7/7/2017 21:59:00   7/7/2017 22:00:00
7/7/2017 22:35:00   7/7/2017 22:39:00
</code>```

Now I need to shift 'end time' down by one row, so that I can compute difference between newtime and endtime

EXPECTED OUTPUT BELOW

```<code>datatest1 <-
 newtime             endtime                 timeDifference (newtimeendtime)
7/7/2017 2:12:00           NA
7/7/2017 2:59:00    7/7/2017 2:13:00              To Be calculated
7/7/2017 18:23:00   7/7/2017 2:59:00             To Be calculated
7/7/2017 18:23:00   7/7/2017 18:23:00             To Be calculated
7/7/2017 20:40:00   7/7/2017 18:23:00             To Be calculated
7/7/2017 20:40:00   7/7/2017 22:25:00             To Be calculated
7/7/2017 21:59:00   7/7/2017 22:33:00             To Be calculated
7/7/2017 22:35:00   7/7/2017 22:00:00             To Be calculated
</code>```

The str output is as below

```<code>str(datatest) <-
    $ newtime   : POSIXct, format: "2017-07-07 02:12:00" "2017-07-07 02:59:00" "2017-07-07 18:23:00" ...
     $ endtime   : POSIXct, format: "2017-07-07 02:13:24" "2017-07-07 02:59:28" "2017-07-07 18:23:06"
</code>```

Now am trying to shift 'endtime' by one of the solutions for my earlier query and store it a new data frame 'datatest1' along with 'newtime',

```<code> newtime <- c(datatest$newtime)
testtime <- c(datatest$endtime)
time_shift2 <- c(NA,time[1:length(testtime)-1])
time_shift2 <- strptime(time_shift2, format='%H:%M:%S')
datatest1 <- data.frame(newtime,time_shift2)
</code>```

And am getting the following error once I execute the last command from the sequence above

```<code>Error in data.frame(newtime, time_shift2) :
  arguments imply differing number of rows: 15005, 12
</code>```

I can also observe on my R console that when i execute the below , from the earlier mentioned sequence

```<code>time_shift2 <- strptime(time_shift2, format='%H:%M:%S')
</code>```

its showing NA values

```<code>POSIXlt[1:12], format : NA NA NA NA..
</code>```

Is there any better way to get the expected output , help needed please. Is there any problem with POSIXct format?

TIA

答:
Generate test data:

```<code>datatest1 <- data.frame(newtime = Sys.time() + 1:10, endtime = Sys.time() + 20:29)
</code>```

Do the shift:

```<code>datatest1$endtime <- c(.POSIXct(NA), head(datatest1$endtime, -1))
</code>```

Is that what you are looking for?

Body:
I have a data set of time (PSIXct format ) with 'newtime' & 'endtime'

datatest <-
  newtime           endtime
7/7/2017 2:12:00    7/7/2017 2:13:00
7/7/2017 2:59:00    7/7/2017 2:59:00
7/7/2017 18:23:00   7/7/2017 18:23:00
7/7/2017 18:23:00   7/7/2017 18:23:00
7/7/2017 20:40:00   7/7/2017 22:25:00
7/7/2017 20:40:00   7/7/2017 22:33:00
7/7/2017 21:59:00   7/7/2017 22:00:00
7/7/2017 22:35:00   7/7/2017 22:39:00

Now I need to shift 'end time' down by one row, so that I can compute difference between newtime and endtime

EXPECTED OUTPUT BELOW

datatest1 <-
 newtime             endtime                 timeDifference (newtimeendtime)
7/7/2017 2:12:00           NA
7/7/2017 2:59:00    7/7/2017 2:13:00              To Be calculated
7/7/2017 18:23:00   7/7/2017 2:59:00             To Be calculated
7/7/2017 18:23:00   7/7/2017 18:23:00             To Be calculated
7/7/2017 20:40:00   7/7/2017 18:23:00             To Be calculated
7/7/2017 20:40:00   7/7/2017 22:25:00             To Be calculated
7/7/2017 21:59:00   7/7/2017 22:33:00             To Be calculated
7/7/2017 22:35:00   7/7/2017 22:00:00             To Be calculated

The str output is as below

str(datatest) <-
    $ newtime   : POSIXct, format: "2017-07-07 02:12:00" "2017-07-07 02:59:00" "2017-07-07 18:23:00" ...
     $ endtime   : POSIXct, format: "2017-07-07 02:13:24" "2017-07-07 02:59:28" "2017-07-07 18:23:06"

Now am trying to shift 'endtime' by one of the solutions for my earlier query and store it a new data frame 'datatest1' along with 'newtime',

 newtime <- c(datatest$newtime)
testtime <- c(datatest$endtime)
time_shift2 <- c(NA,time[1:length(testtime)-1])
time_shift2 <- strptime(time_shift2, format='%H:%M:%S')
datatest1 <- data.frame(newtime,time_shift2)

And am getting the following error once I execute the last command from the sequence above

Error in data.frame(newtime, time_shift2) :
  arguments imply differing number of rows: 15005, 12

I can also observe on my R console that when i execute the below , from the earlier mentioned sequence

time_shift2 <- strptime(time_shift2, format='%H:%M:%S')

its showing NA values

POSIXlt[1:12], format : NA NA NA NA..

Is there any better way to get the expected output , help needed please. Is there any problem with POSIXct format?

TIA

Body:
Generate test data:

datatest1 <- data.frame(newtime = Sys.time() + 1:10, endtime = Sys.time() + 20:29)

Do the shift:

datatest1$endtime <- c(.POSIXct(NA), head(datatest1$endtime, -1))

Is that what you are looking for?


问:
Create custom blur UIView
I have to develop an app that uses a a blur view.

I've tried to use UIVisualEffectView with UIBlueEffect but then I realised that there are just 3 types of blur that you can choose from, without an option to customise the blur.

I need to make a blur that is something between the Light and Dark modes, but I don't know how can I create a custom blur view.

Any idea on how can I do that?

Thank you!

答:
User below code for the blur effect

```<code>let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)
</code>```

Also you can use below library

https://github.com/ide/UIVisualEffects

Title: Create custom blur UIView

Body:
User below code for the blur effect

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

Also you can use below library

https://github.com/ide/UIVisualEffects


答:
```<code>for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}
</code>```

There you go. Basic for loop from 0 to 3 (4 times). And calling Pin inside it.

Title: Need to duplicate the same element in the DOM 4 times using Jquery

Body:
for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}

There you go. Basic for loop from 0 to 3 (4 times). And calling Pin inside it.


问:
Regular Expression - Accept 15 to 17 Digits
I want a regular expression that accepts numeric only between 15 to 17 digits.</p>

答:
^\d{15,17}$ - For any digit (use [0-9] instead of \d to avoid Unicode characters, if applicable).

^[1-9]\d{14,16}$ - If you don't want the number to start with all zeros.

Of course, it might be easier to parse the number and check it, it fits nicely in a long value.


问:
Static Initialization in Java?
I was trying to execute the following code:

```<code>public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}
</code>```

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

答:
Your code:

```<code>{
    dat1 = new ArrayList<>();
}
</code>```

Is a non-static initializer. This is called, when you are calling the constructor with: new StaticTest(). After that dat1 will be initialized.

You can change your code to static initializing by preceding it with the static keyword:

```<code>static
{
    dat1 = new ArrayList<>();
}
</code>```

Then it will work for both cases.

Title: Static Initialization in Java?

Body:
I was trying to execute the following code:

public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

Body:
Your code:

{
    dat1 = new ArrayList<>();
}

Is a non-static initializer. This is called, when you are calling the constructor with: new StaticTest(). After that dat1 will be initialized.

You can change your code to static initializing by preceding it with the static keyword:

static
{
    dat1 = new ArrayList<>();
}

Then it will work for both cases.


问:
React component not recognizing .filter as a function
So I am making a react app for food recipes and am pulling data from a JSON file. For some reason the .filter and .map of the recipes is not showing as a function. Any help greatly appreciated.

It most examples it looks like you can add this info under render. I am a noob with both coding and react so I am sure it is user error.

```<code>import React from 'react';
import ReadInput from'./readInput';
import '../Styles/Home.css';

 class Input extends React.Component{
     constructor(props) {
         super(props);
     this.state = {
         value:''
     }
     this.handleName = this.handleName.bind(this);
 };
handleName(e){
    console.log('handleName')
    if(e === 'chicken'){
            this.setState({value: 1})
        } else if (e === 'beef') {
            this.setState({value: 2})
        } else if (e === 'rice'){
            this.setState({value: 3})
        }

}

render(){
    const menu = this.props.data.filter((recipe) => {
            if(recipe.id === this.state.value){
            return recipe.dish;
        }
    })
    .map(recipe => {
        return(
            <div>
            <li key={recipe.id}>{recipe.dish}</li>
            <li >{recipe.ingredients}</li>
            </div>
        )
    })

    return(
        <div>
            <ReadInput
                onChange={this.handleName} />
            <button className="homeButton" onClick={this.menu}>Click</button>
            <ul className='listStyle'>
                {menu}
            </ul>
        </div>
    )
}
</code>```

}

```<code>export default Input;
</code>```

app file

```<code>import React from 'react';
import Input from'./Input';
import recipes from'../data.json';

class App extends React.Component{
    constructor(props) {
        super();

}
render(){
    return(
        <div>
            <Input data={recipes} />
        </div>
    )
}
</code>```

}

export default App;

答:
If this.props.data is an object, you cannot directly map or filter on it. I think this should work:

```<code>const recipes = this.props.data;
const menu = Object.keys(recipes).filter((recipeKey) => recipes[recipeKey].id === this.state.value)
.map(recipeKey =>
  return (
    <div key={recipes[recipeKey].id}>
      <li>{recipes[recipeKey].dish}</li>
      <li>{recipes[recipeKey].ingredients}</li>
    </div>
  );
});
</code>```

First you filter the keys of your this.props.data, you only get the keys for the recipes that match the id in the state.
Then you map (still mapping with the keys of the object, not the values) and create the list.

Notice that I moved the key attribute to the
 tag, that's because you need this attribute in the component returned by the map, not in it's children.

Also, in the <button className="homeButton" onClick={this.menu}>Click</button>, the onClick attribute receives the menu, but it should receive a function to execute when the button is clicked.

Body:
So I am making a react app for food recipes and am pulling data from a JSON file. For some reason the .filter and .map of the recipes is not showing as a function. Any help greatly appreciated.

It most examples it looks like you can add this info under render. I am a noob with both coding and react so I am sure it is user error.

import React from 'react';
import ReadInput from'./readInput';
import '../Styles/Home.css';

 class Input extends React.Component{
     constructor(props) {
         super(props);
     this.state = {
         value:''
     }
     this.handleName = this.handleName.bind(this);
 };
handleName(e){
    console.log('handleName')
    if(e === 'chicken'){
            this.setState({value: 1})
        } else if (e === 'beef') {
            this.setState({value: 2})
        } else if (e === 'rice'){
            this.setState({value: 3})
        }

}

render(){
    const menu = this.props.data.filter((recipe) => {
            if(recipe.id === this.state.value){
            return recipe.dish;
        }
    })
    .map(recipe => {
        return(

{recipe.dish}

{recipe.ingredients}

        )
    })

    return(

            <ReadInput
                onChange={this.handleName} />
            <button className="homeButton" onClick={this.menu}>Click</button>

                {menu}

    )
}

}

export default Input;

app file

import React from 'react';
import Input from'./Input';
import recipes from'../data.json';

class App extends React.Component{
    constructor(props) {
        super();

}
render(){
    return(

            <Input data={recipes} />

    )
}

}

export default App;

Body:
If this.props.data is an object, you cannot directly map or filter on it. I think this should work:

const recipes = this.props.data;
const menu = Object.keys(recipes).filter((recipeKey) => recipes[recipeKey].id === this.state.value)
.map(recipeKey =>
  return (
    <div key={recipes[recipeKey].id}>
      <li>{recipes[recipeKey].dish}</li>
      <li>{recipes[recipeKey].ingredients}</li>
    </div>
  );
});

First you filter the keys of your this.props.data, you only get the keys for the recipes that match the id in the state.
Then you map (still mapping with the keys of the object, not the values) and create the list.

Notice that I moved the key attribute to the <div> tag, that's because you need this attribute in the component returned by the map, not in it's children.

Also, in the <button className="homeButton" onClick={this.menu}>Click</button>, the onClick attribute receives the menu, but it should receive a function to execute when the button is clicked.


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
This:

```<code>int *q = 8;
</code>```

is an initialization. It initializes q (the pointer), not *q (what it points to). Writing this equivalently with an assignment instead of initialization would look like:

```<code>int *q;
q = 8;
</code>```

So you see it doesn't make sense. (and, isn't allowed of course -- an int is not a pointer)

Just to be sure, if you write:

```<code>int *q;
*q = 8;
</code>```

this is syntactically correct, but undefined behavior. Your pointer doesn't point to an object of type int, it is uninitialized and probably pointing to some invalid location. Writing there, anything could happen.

Body:
This:

int *q = 8;

is an initialization. It initializes q (the pointer), not *q (what it points to). Writing this equivalently with an assignment instead of initialization would look like:

int *q;
q = 8;

So you see it doesn't make sense. (and, isn't allowed of course -- an int is not a pointer)

Just to be sure, if you write:

int *q;
*q = 8;

this is syntactically correct, but undefined behavior. Your pointer doesn't point to an object of type int, it is uninitialized and probably pointing to some invalid location. Writing there, anything could happen.


问:
Convert pandas time series with monthly returns into a df with col cumulative yearly return
My df containing monthly returns looks like this:

```<code>df=pd.DataFrame((x*x).dropna(),columns=['mthly rtrn'])

             mthly rtrn
2016-09-30    0.002488
2016-10-31   -0.004692
2016-11-30    0.003157
2016-12-30   -0.000503
2017-01-31    0.008019
2017-02-28    0.010055
2017-03-31    0.003435
2017-04-28    0.002577
2017-05-31    0.012107
2017-06-30    0.001089
</code>```

How can I convert this into a df with columns Jan to Dec plus column for the cumulative yearly return. Lines should be the years 2016, 2017 etc. And the numbers should ideally be shown in %.

Desired output:

```<code>      Jan   Feb  Mar  Apr  May  Jun  Jul  Aug  Sep   Oct  Nov  Dec ANNUAL
2016 -5.0  -0.1  6.7  0.4  1.7  0.3  3.6  0.1  0.0  -1.7  3.7  2.0   12.0
2017  1.8   3.9  0.1  1.0  1.4  0.6  0.1   NA   NA    NA   NA   NA    9.3
</code>```

where ANNUAL is the cumprod of the monthly returns.

What is the best pythonic way to achieve this?

答:
I would first add additional columns Year and Month to your df using this, then use a pivot table to create a new df to get the index as Year and columns as Month, around the monthly return values.

Once you have the pivot table, you can use apply along axis=1 to get whatever aggregation you need for each year.

I can't really comment on the aggregation because I'm not sure if by 'cumulative' do you mean additive or multiplicative. You might want to consider cumsum or gmean from scipy, or if you prefer not to get scipy this function works too.

Body:
My df containing monthly returns looks like this:

df=pd.DataFrame((x*x).dropna(),columns=['mthly rtrn'])

             mthly rtrn
2016-09-30    0.002488
2016-10-31   -0.004692
2016-11-30    0.003157
2016-12-30   -0.000503
2017-01-31    0.008019
2017-02-28    0.010055
2017-03-31    0.003435
2017-04-28    0.002577
2017-05-31    0.012107
2017-06-30    0.001089

How can I convert this into a df with columns Jan to Dec plus column for the cumulative yearly return. Lines should be the years 2016, 2017 etc. And the numbers should ideally be shown in %.

Desired output:

      Jan   Feb  Mar  Apr  May  Jun  Jul  Aug  Sep   Oct  Nov  Dec ANNUAL
2016 -5.0  -0.1  6.7  0.4  1.7  0.3  3.6  0.1  0.0  -1.7  3.7  2.0   12.0
2017  1.8   3.9  0.1  1.0  1.4  0.6  0.1   NA   NA    NA   NA   NA    9.3

where ANNUAL is the cumprod of the monthly returns.

What is the best pythonic way to achieve this?


问:
Pagefactory throwing null in Page Object Structure
I am implementing pagefactory in my Page object model automation framework. My existing framework works fine without pagefactory. Now I am implementing pagefactory to invoke elements. I am facing a issue where Pagefactory element throwing null values.
I have a doubt that it may be because of constructors not sure.

I have build a framework based on Page Object Model
Have packages as below :-
com.automationframework
com.configutaion
com.pageObject
com.testcases
com.testsuites

My testsuites classes invokes testcases present in testcases package and invoke driver and other framework based classes in automationframework.
I know it's hard to grab the error by simply read few stuff but may anyone faced same issue and can help me.

My Page class looks something like below :-

```<code>public class SynchronizationPage extends Page {

    ExcelLib xl = new ExcelLib();

    private WebElement element = null;

    public SynchronizationPage(WebDriver driver) {
        super(driver);
    }

    protected boolean isSecured() {
        return true;
    }

    @FindBy(how = How.XPATH, using = "//a[@class='header-font']/span[@class='icon-cog']")
    @CacheLookup
    public WebElement HoverOnSettings;
}
</code>```

My testcase class :-

```<code>public class SyncTest extends AutomationTestCaseVerification {

//  SynchronizationPage sync = new SynchronizationPage(Page.driver);
    SignOutPage signout = new SignOutPage(Page.driver);
    ExcelLib xl = new ExcelLib();
    SynchronizationPage synccc = PageFactory.initElements(Page.driver, SynchronizationPage.class);

    private WebElement element = null;
    private WebDriver driver;

    public SyncTest() {
        super();
    }

    @Override
    protected void verifyTestCases() throws Exception {
        syncFeature();
    }

    public void syncFeature() throws Exception {

        try {
         WebDriverWait waits = new WebDriverWait(Page.driver, 60);
    //   waits.until(ExpectedConditions.elementToBeClickable(synccc.clickOnOffButton)).click();
         synccc.clickOnOffButton.click();
         System.out.println("Yes I clicked");
        }
        catch(Exception ex)
        {
            System.out.println("error ="+ex.getMessage());
            }

    }
}
</code>```

I am getting error like below :-

java.lang.NullPointerException    at
  org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
    at
  org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
    at com.sun.proxy.$Proxy5.click(Unknown Source)  at
  com.cc.automation.testcases.SyncTest.syncFeature(SyncTest.java:130)
    at
  com.cc.automation.testcases.SyncTest.verifyTestCases(SyncTest.java:60)
    at
  com.cc.automation.automationframework.AutomationTestCaseVerification.Execute(AutomationTestCaseVerification.java:58)
    at
  com.cc.automation.testsuites.SynchronizationTest.testSync(SynchronizationTest.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)   at
  org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)    at
  org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)  at
  org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at
  org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)    at
  org.testng.TestRunner.run(TestRunner.java:602)    at
  org.testng.SuiteRunner.runTest(SuiteRunner.java:380)  at
  org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)  at
  org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)   at
  org.testng.SuiteRunner.run(SuiteRunner.java:289)  at
  org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)  at
  org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)   at
  org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)     at
  org.testng.TestNG.runSuitesLocally(TestNG.java:1226)  at
  org.testng.TestNG.runSuites(TestNG.java:1144)     at
  org.testng.TestNG.run(TestNG.java:1115)   at
  org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

I have also tried to apply below but still not working :-

PageFactory.initElements(this.driver, this);

答: Can you try once by calling PageFactory.initElements(driver, this); inside the constructor of your SynchronizationPage class.

Body:
I am implementing pagefactory in my Page object model automation framework. My existing framework works fine without pagefactory. Now I am implementing pagefactory to invoke elements. I am facing a issue where Pagefactory element throwing null values.
I have a doubt that it may be because of constructors not sure.

I have build a framework based on Page Object Model
Have packages as below :-
com.automationframework
com.configutaion
com.pageObject
com.testcases
com.testsuites

My testsuites classes invokes testcases present in testcases package and invoke driver and other framework based classes in automationframework.
I know it's hard to grab the error by simply read few stuff but may anyone faced same issue and can help me.

My Page class looks something like below :-

public class SynchronizationPage extends Page {

    ExcelLib xl = new ExcelLib();

    private WebElement element = null;

    public SynchronizationPage(WebDriver driver) {
        super(driver);
    }

    protected boolean isSecured() {
        return true;
    }

    @FindBy(how = How.XPATH, using = "//a[@class='header-font']/span[@class='icon-cog']")
    @CacheLookup
    public WebElement HoverOnSettings;
}

My testcase class :-

public class SyncTest extends AutomationTestCaseVerification {

//  SynchronizationPage sync = new SynchronizationPage(Page.driver);
    SignOutPage signout = new SignOutPage(Page.driver);
    ExcelLib xl = new ExcelLib();
    SynchronizationPage synccc = PageFactory.initElements(Page.driver, SynchronizationPage.class);

    private WebElement element = null;
    private WebDriver driver;

    public SyncTest() {
        super();
    }

    @Override
    protected void verifyTestCases() throws Exception {
        syncFeature();
    }

    public void syncFeature() throws Exception {

        try {
         WebDriverWait waits = new WebDriverWait(Page.driver, 60);
    //   waits.until(ExpectedConditions.elementToBeClickable(synccc.clickOnOffButton)).click();
         synccc.clickOnOffButton.click();
         System.out.println("Yes I clicked");
        }
        catch(Exception ex)
        {
            System.out.println("error ="+ex.getMessage());
            }

    }
}

I am getting error like below :-

java.lang.NullPointerException    at
  org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
    at
  org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
    at com.sun.proxy.$Proxy5.click(Unknown Source)  at
  com.cc.automation.testcases.SyncTest.syncFeature(SyncTest.java:130)
    at
  com.cc.automation.testcases.SyncTest.verifyTestCases(SyncTest.java:60)
    at
  com.cc.automation.automationframework.AutomationTestCaseVerification.Execute(AutomationTestCaseVerification.java:58)
    at
  com.cc.automation.testsuites.SynchronizationTest.testSync(SynchronizationTest.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)   at
  org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)    at
  org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)  at
  org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at
  org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)    at
  org.testng.TestRunner.run(TestRunner.java:602)    at
  org.testng.SuiteRunner.runTest(SuiteRunner.java:380)  at
  org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)  at
  org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)   at
  org.testng.SuiteRunner.run(SuiteRunner.java:289)  at
  org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)  at
  org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)   at
  org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)     at
  org.testng.TestNG.runSuitesLocally(TestNG.java:1226)  at
  org.testng.TestNG.runSuites(TestNG.java:1144)     at
  org.testng.TestNG.run(TestNG.java:1115)   at
  org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

I have also tried to apply below but still not working :-

PageFactory.initElements(this.driver, this);


问:
Javascript - Change Button function once I click it
I have a button and 3 functions.
change each funtion once I click it
Please Help me.</p>

答:
```<code>function change(that){
      that.value="Changed"
      that.innerHTML="Changed"
}

<button id="btn" type="button" onclick="change(this)">click</button

      or

<button id="btn" type="button" onclick = "this.innerHTML = 'Changed'" > click </button>
</code>```

or

```<code><button id="btn" type="button" onclick = "document.getElementById('btn').innerHTML = 'Changed' "> Try it </button>
</code>```

Body:
function change(that){
      that.value="Changed"
      that.innerHTML="Changed"
}

<button id="btn" type="button" onclick="change(this)">click</button

      or

<button id="btn" type="button" onclick = "this.innerHTML = 'Changed'" > click </button>

or

<button id="btn" type="button" onclick = "document.getElementById('btn').innerHTML = 'Changed' "> Try it </button>


问:
PHP MySQL : How to add data written into PHP into Mysql database
So ive got a little webserver going on with a phone-book.
You can click on "add a new member", but when you fill in everything from the web server and click on "save" the new row is not showing up in the show-phone-book file.
I translated it, but the files and comments and in german.

I don't think there is anything more needed than this file, adding new member.

When i execute it, i can fill everything in, click "save" , then it dies and i get to the error : Anfrage fehlgeschlagen.

```<code><?php

if ( $_GET['aktion'] == "speichern" )
{
$Nachname     = $_GET['Nachname'];
$Vorname      = $_GET['Vorname'];
$Anrede       = $_GET['Anrede'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer= $_GET['Telefonnummer'];
$Email        = $_GET['Email'];

$sql = "INSERT INTO Adressbuch SET ";
$sql .= " Nachname          = '$Nachname', ";
$sql .= " Vorname           = '$Vorname', ";
$sql .= " Anrede            = '$Anrede', ";
$sql .= " Geburtsdatum      = '$Geburtsdatum', ";
$sql .= " Telefonnummer     = '$Telefonnummer',";
$sql .= " Email             = '$Email'";

require_once ('konfiguration.php');
$db_erg = mysqli_query($db_con, $sql)
    or die(" Anfrage fehlgeschlagen");

exit;
}
?>

<form name="" action="" method="GET" enctype="text/html">
<p>Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein<br>
</p>
<p>Nachname:<br>
<input type="text" name="Nachname" value="" size="60">
</p>

<p>Vorname:<br>
<input type="text" name="Vorname" value="" size="60">
</p>

<p>Anrede:<br>
<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr
</p>

<p>Geburtsdatum (YYYY-MM-DD):<br>
<input type="date" name="Geburtsdatum" value="" size="10">
</p>

<p>Telefonnummer:<br>
<input type="text" name="Telefonnummer" value="" size="60">
</p>

<p>E-Mail:<br>
<input type="text" name="Email" value="" size="60">
</p>

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="" value="speichern">
</form>
</code>```

答:
First things don't use $_GET rather use $_POST method.

Then use prepared statements to protect against sql injections.

```<code><?php
require_once('konfiguration.php');

if (isset($_POST['submit'])) {
    $Nachname      = $_POST['Nachname'];
    $Vorname       = $_POST['Vorname'];
    $Anrede        = $_POST['Anrede'];
    $Geburtsdatum  = $_POST['Geburtsdatum'];
    $Telefonnummer = $_POST['Telefonnummer'];
    $Email         = $_POST['Email'];

    $sql  = "INSERT INTO Adressbuch (Nachname,Vorname,Anrede,Geburtsdatum,Telefonnummer,Email) VALUES(?,?,?,?,?,?) ";
    $stmt = mysqli_prepare($db_con, $sql);
    mysqli_stmt_bind_param($stmt, 'ssssss', $Nachname, $Vorname, $Anrede, $Geburtsdatum, $Telefonnummer, $Email);

    if (mysqli_stmt_execute($stmt)) {

        echo "data inserted";
    } else {

        printf("Error: %s.\n", mysqli_stmt_error($stmt));
    }

}
?>
<form name="" action="" method="POST" enctype="text/html">
<p>Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein<br>
</p>
<p>Nachname:<br>
<input type="text" name="Nachname" value="" size="60">
</p>

<p>Vorname:<br>
<input type="text" name="Vorname" value="" size="60">
</p>

<p>Anrede:<br>
<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr
</p>

<p>Geburtsdatum (YYYY-MM-DD):<br>
<input type="date" name="Geburtsdatum" value="" size="10">
</p>

<p>Telefonnummer:<br>
<input type="text" name="Telefonnummer" value="" size="60">
</p>

<p>E-Mail:<br>
<input type="text" name="Email" value="" size="60">
</p>

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="submit" value="speichern">
</form>
</code>```

Body:
So ive got a little webserver going on with a phone-book.
You can click on "add a new member", but when you fill in everything from the web server and click on "save" the new row is not showing up in the show-phone-book file.
I translated it, but the files and comments and in german.

I don't think there is anything more needed than this file, adding new member.

When i execute it, i can fill everything in, click "save" , then it dies and i get to the error : Anfrage fehlgeschlagen.

<?php

if ( $_GET['aktion'] == "speichern" )
{
$Nachname     = $_GET['Nachname'];
$Vorname      = $_GET['Vorname'];
$Anrede       = $_GET['Anrede'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer= $_GET['Telefonnummer'];
$Email        = $_GET['Email'];

$sql = "INSERT INTO Adressbuch SET ";
$sql .= " Nachname          = '$Nachname', ";
$sql .= " Vorname           = '$Vorname', ";
$sql .= " Anrede            = '$Anrede', ";
$sql .= " Geburtsdatum      = '$Geburtsdatum', ";
$sql .= " Telefonnummer     = '$Telefonnummer',";
$sql .= " Email             = '$Email'";

require_once ('konfiguration.php');
$db_erg = mysqli_query($db_con, $sql)
    or die(" Anfrage fehlgeschlagen");

exit;
}
?>

<form name="" action="" method="GET" enctype="text/html">

Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein

Nachname:

<input type="text" name="Nachname" value="" size="60">

Vorname:

<input type="text" name="Vorname" value="" size="60">

Anrede:

<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr

Geburtsdatum (YYYY-MM-DD):

<input type="date" name="Geburtsdatum" value="" size="10">

Telefonnummer:

<input type="text" name="Telefonnummer" value="" size="60">

E-Mail:

<input type="text" name="Email" value="" size="60">

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="" value="speichern">
</form>

Body:
First things don't use $_GET rather use $_POST method.

Then use prepared statements to protect against sql injections.

<?php
require_once('konfiguration.php');

if (isset($_POST['submit'])) {
    $Nachname      = $_POST['Nachname'];
    $Vorname       = $_POST['Vorname'];
    $Anrede        = $_POST['Anrede'];
    $Geburtsdatum  = $_POST['Geburtsdatum'];
    $Telefonnummer = $_POST['Telefonnummer'];
    $Email         = $_POST['Email'];

    $sql  = "INSERT INTO Adressbuch (Nachname,Vorname,Anrede,Geburtsdatum,Telefonnummer,Email) VALUES(?,?,?,?,?,?) ";
    $stmt = mysqli_prepare($db_con, $sql);
    mysqli_stmt_bind_param($stmt, 'ssssss', $Nachname, $Vorname, $Anrede, $Geburtsdatum, $Telefonnummer, $Email);

    if (mysqli_stmt_execute($stmt)) {

        echo "data inserted";
    } else {

        printf("Error: %s.\n", mysqli_stmt_error($stmt));
    }

}
?>
<form name="" action="" method="POST" enctype="text/html">
<p>Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein<br>
</p>
<p>Nachname:<br>
<input type="text" name="Nachname" value="" size="60">
</p>

<p>Vorname:<br>
<input type="text" name="Vorname" value="" size="60">
</p>

<p>Anrede:<br>
<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr
</p>

<p>Geburtsdatum (YYYY-MM-DD):<br>
<input type="date" name="Geburtsdatum" value="" size="10">
</p>

<p>Telefonnummer:<br>
<input type="text" name="Telefonnummer" value="" size="60">
</p>

<p>E-Mail:<br>
<input type="text" name="Email" value="" size="60">
</p>

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="submit" value="speichern">
</form>


问:
How do I REALLY reset the Visual Studio window layout?
I had a plugin installed in Visual Studio 2008, and it created some extra dockable windows.  I have uninstalled it, and I can't get rid of the windows it created - I close them, but they always come back.  They're just empty windows now, since the plugin is no longer present, but nothing I've tried gets rid of them.  I've tried:

Window -> Reset Window Layout

Deleting the .suo files in my project directories

Deleting the Visual Studio 9.0 folder in my Application Settings directory

Any ideas?

答:
I close them, but they always come back

When you say "they always come back" do you mean "next time you restart Visual Studio" or "immediately"?

One quirk of Visual Studio (at least VS2005) is that settings aren't saved until you exit.  That means that if VS crashes at all while you are using it, any layout changes you made will be lost.  The way around this is to always gracefully exit when you have set up everything like you want it to be.

Not sure if this will help your particular situation though.

OwnerDisplayName: TimK

LastEditorDisplayName: TimK

OwnerDisplayName: LeopardSkinPillBoxHat


答:
Because it is not valid C, simple as that. Specifically, it is a constraint violation of the assignment operator, since integer to pointer or pointer to integer is not valid forms of "simple assignment" (C11 6.5.16.1).

You can convert between integers and pointers by adding an explicit cast. The result is however not guaranteed to work: pointers and integers may have different representations and there might be alignment issues.

In case of *q = 6; you assign an int to an int, which is of course perfectly fine (given that the pointer points at allocated memory somewhere).

Body:
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?