问:
Getting "not a function"error in React Native/Redux
My code is here

I am getting the error below.

I believe its something to do with the employee create line in the code below and i cannot figure out why this might be happening. I am doing this from a tutorial

```<code>    import React, { Component } from 'react';
//import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { Picker, Text } from 'react-native';
import { employeeUpdate, employeeCreate } from '../actions';
import { Card, CardSection, Input, Button } from './common';

class EmployeeCreate extends Component {
  onButtonPress() {
    const { name, phone, shift } = this.props;

    this.props.employeeCreate({ name, phone, shift: shift || 'Monday' });
  }
  render() {
    return (
    //
    // <View>
    //  <Text>Employees</Text>
    // </View>
      <Card>
        <CardSection>
          <Input
            label="Name"
            placeholder="Jane"
            value={this.props.name}
            onChangeText={value => this.props.employeeUpdate({ prop: 'name', value })}
          />
        </CardSection>

        <CardSection>
          <Input
            label="Phone"
            placeholder="555-555-5555"
            value={this.props.phone}
            onChangeText={value => this.props.employeeUpdate({ prop: 'phone', value })}
          />
        </CardSection>
        <CardSection style={{ flexDirection: 'column' }}>
        <Text style={styles.pickerLabelStyle}>Pick a Shift: </Text>
        <Picker
            //style={{ flex: 1 }}
            selectedValue={this.props.shift}
            onValueChange={value => this.props.employeeUpdate({ prop: 'shift', value })}
        >
          <Picker.Item label="Monday" value="Monday" />
          <Picker.Item label="Tuesday" value="Tuesday" />
          <Picker.Item label="Wednesday" value="Wednesday" />
          <Picker.Item label="Thursday" value="Thursday" />
          <Picker.Item label="Friday" value="Friday" />
          <Picker.Item label="Saturday" value="Saturday" />
          <Picker.Item label="Sunday" value="Sunday" />
        </Picker>
        </CardSection>

        <CardSection>
        <Button onPress={this.onButtonPress.bind(this)}>
            Create
          </Button>
        </CardSection>
      </Card>
    );
  }
}
const styles = {
  pickerLabelStyle: {
    fontSize: 18,
    paddingLeft: 20
  }
};
const mapStateToProps = (state) => {
  const { name, phone, shift } = state.employeeForm;

    return { name, phone, shift };
};
export default connect(mapStateToProps, {
  employeeUpdate, employeeCreate
})(EmployeeCreate);
</code>```

Here is the error:

答:
Folks- this is resolved. I found my answer.

In the
https://github.com/samrao2/manager-4/blob/master/src/actions/index.js

file. I was not exporting all the actions from the Employeeactions file and so was not exporting the employeeCreate action. i should have put a * there.

Issue is resolved! Thanks!

Body:
My code is here

I am getting the error below.

I believe its something to do with the employee create line in the code below and i cannot figure out why this might be happening. I am doing this from a tutorial

    import React, { Component } from 'react';
//import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { Picker, Text } from 'react-native';
import { employeeUpdate, employeeCreate } from '../actions';
import { Card, CardSection, Input, Button } from './common';

class EmployeeCreate extends Component {
  onButtonPress() {
    const { name, phone, shift } = this.props;

    this.props.employeeCreate({ name, phone, shift: shift || 'Monday' });
  }
  render() {
    return (
    //
    // <View>
    //  <Text>Employees</Text>
    // </View>
      <Card>
        <CardSection>
          <Input
            label="Name"
            placeholder="Jane"
            value={this.props.name}
            onChangeText={value => this.props.employeeUpdate({ prop: 'name', value })}
          />
        </CardSection>

        <CardSection>
          <Input
            label="Phone"
            placeholder="555-555-5555"
            value={this.props.phone}
            onChangeText={value => this.props.employeeUpdate({ prop: 'phone', value })}
          />
        </CardSection>
        <CardSection style={{ flexDirection: 'column' }}>
        <Text style={styles.pickerLabelStyle}>Pick a Shift: </Text>
        <Picker
            //style={{ flex: 1 }}
            selectedValue={this.props.shift}
            onValueChange={value => this.props.employeeUpdate({ prop: 'shift', value })}
        >
          <Picker.Item label="Monday" value="Monday" />
          <Picker.Item label="Tuesday" value="Tuesday" />
          <Picker.Item label="Wednesday" value="Wednesday" />
          <Picker.Item label="Thursday" value="Thursday" />
          <Picker.Item label="Friday" value="Friday" />
          <Picker.Item label="Saturday" value="Saturday" />
          <Picker.Item label="Sunday" value="Sunday" />
        </Picker>
        </CardSection>

        <CardSection>
        <Button onPress={this.onButtonPress.bind(this)}>
            Create
          </Button>
        </CardSection>
      </Card>
    );
  }
}
const styles = {
  pickerLabelStyle: {
    fontSize: 18,
    paddingLeft: 20
  }
};
const mapStateToProps = (state) => {
  const { name, phone, shift } = state.employeeForm;

    return { name, phone, shift };
};
export default connect(mapStateToProps, {
  employeeUpdate, employeeCreate
})(EmployeeCreate);

Here is the error:


来源: stackexchange

问:
Tween.js rotation not working when using Three.js loader
I am working on a simulation project that was started a few years ago. They were using older versions of three.js and tween.js libs and I had to upgrade them for other reasons. I have a problem that piece of code that used to work, now doesn't and I can't figure out why...

Now, let me explain what is the problem. At the start of the app, meshes are loaded by calling this function for each mesh:

```<code>function loadMesh(objPath, objName, worldScene, initPosition) {
    if (initPosition == undefined) {
        initPosition = new THREE.Vector3();
    }
    var loader = new THREE.JSONLoader();
    loader.load(objPath, function (geometry, materials) {
        for (var material in materials) {
            materials[material].shading = THREE.FlatShading;
        }
        var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh.scale.set(1, 1, 1);
        mesh.name = objName;
        mesh.position = initPosition;
        mesh.positionO = initPosition.clone();

        worldScene.add(mesh);
        objects.push(mesh);
        objDict[objName] = mesh;
        loadCounter--;
    });
}
</code>```

NOTE: I will just show animation creation, I call "start" method on them later, of course
Now, it works when I try to move that object by changing its position with something like this:

```<code>new TWEEN.Tween(objDict["Screws"].position)
    .to({y: 5}, 1000)
    .delay(500);
</code>```

but if I try to rotate my object like this, it doesn't work:

```<code>new TWEEN.Tween(objDict["ms_LidUpper"].rotation)
    .to({x: -1.571}, 1000)
    .delay(500);
</code>```

I tried to solve this, but couldn't find anything... Note that this code worked before! I think the problem is JSONLoader because when I run the code in debug mode, mesh object was missing matrixRotationWorld atribute and had matrixWorldNeedsUpdate attribute on false, and in the previos app version matrixWorldNeedsUpdate was true and there was matrixRotationWorld atribute.

Any help will be greatly appriciated!

答:
Use tween like this way</p>

```<code>var coords = { x: 0, y: 0 };
new TWEEN.Tween(mesh.rotation).to({x: 10, y: 10}, 3000).onUpdate(function () {
    mesh.rotation.x = coords.x;
    mesh.rotation.y = coords.y;
}).start();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a simulation project that was started a few years ago. They were using older versions of three.js and tween.js libs and I had to upgrade them for other reasons. I have a problem that piece of code that used to work, now doesn't and I can't figure out why...

Now, let me explain what is the problem. At the start of the app, meshes are loaded by calling this function for each mesh:

function loadMesh(objPath, objName, worldScene, initPosition) {
    if (initPosition == undefined) {
        initPosition = new THREE.Vector3();
    }
    var loader = new THREE.JSONLoader();
    loader.load(objPath, function (geometry, materials) {
        for (var material in materials) {
            materials[material].shading = THREE.FlatShading;
        }
        var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh.scale.set(1, 1, 1);
        mesh.name = objName;
        mesh.position = initPosition;
        mesh.positionO = initPosition.clone();

        worldScene.add(mesh);
        objects.push(mesh);
        objDict[objName] = mesh;
        loadCounter--;
    });
}

NOTE: I will just show animation creation, I call "start" method on them later, of course
Now, it works when I try to move that object by changing its position with something like this:

new TWEEN.Tween(objDict["Screws"].position)
    .to({y: 5}, 1000)
    .delay(500);

but if I try to rotate my object like this, it doesn't work:

new TWEEN.Tween(objDict["ms_LidUpper"].rotation)
    .to({x: -1.571}, 1000)
    .delay(500);

I tried to solve this, but couldn't find anything... Note that this code worked before! I think the problem is JSONLoader because when I run the code in debug mode, mesh object was missing matrixRotationWorld atribute and had matrixWorldNeedsUpdate attribute on false, and in the previos app version matrixWorldNeedsUpdate was true and there was matrixRotationWorld atribute.

Any help will be greatly appriciated!

Body:
Use tween like this way

var coords = { x: 0, y: 0 };
new TWEEN.Tween(mesh.rotation).to({x: 10, y: 10}, 3000).onUpdate(function () {
    mesh.rotation.x = coords.x;
    mesh.rotation.y = coords.y;
}).start();


问:
Is there any easier way to get the key name value in the following json using newtonsoft
Let's say we have JSON as below:

```<code>{
  "Group1": ["Value1", "Value5"],
  "Group2": ["Value4", "Value11", "Value12", "Value9"],
  "Group3": ["Value2"]
}
</code>```

Given the value in the list say "Value1", I need to get the corresponding key name "Group1".

Is there any easier way to do this ?

What I tried:

```<code>var json = "{\r\n  \"Group1\": [\"Value1\", \"Value5\"],\r\n  \"Group2\": [\"Value4\", \"Value11\", \"Value12\", \"Value9\"],\r\n  \"Group3\": [\"Value2\"]\r\n}";

var jObject = JObject.Parse(json);

var group1 = jObject["Group1"].ToObject<List<string>>();
var group2 = jObject["Group2"].ToObject<List<string>>();
var group3 = jObject["Group3"].ToObject<List<string>>();

var value = group1.Contains("Value1") ? "Group1" : "Invalid";
</code>```

答:
This is what you need:

Deserialize to a Dictionary<string, List<string>>

Filter and get the key.

```<code>var data = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);

string key = data.Where(kvp => kvp.Value.Contains(searchValue))
                 .Select(kvp => kvp.Key)
                 .FirstOrDefault();
</code>```

Body:
Let's say we have JSON as below:

{
  "Group1": ["Value1", "Value5"],
  "Group2": ["Value4", "Value11", "Value12", "Value9"],
  "Group3": ["Value2"]
}

Given the value in the list say "Value1", I need to get the corresponding key name "Group1".

Is there any easier way to do this ?

What I tried:

var json = "{\r\n  \"Group1\": [\"Value1\", \"Value5\"],\r\n  \"Group2\": [\"Value4\", \"Value11\", \"Value12\", \"Value9\"],\r\n  \"Group3\": [\"Value2\"]\r\n}";

var jObject = JObject.Parse(json);

var group1 = jObject["Group1"].ToObject<List<string>>();
var group2 = jObject["Group2"].ToObject<List<string>>();
var group3 = jObject["Group3"].ToObject<List<string>>();

var value = group1.Contains("Value1") ? "Group1" : "Invalid";

Body:
This is what you need:

Deserialize to a Dictionary<string, List<string>>

Filter and get the key.

var data = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);

string key = data.Where(kvp => kvp.Value.Contains(searchValue))
                 .Select(kvp => kvp.Key)
                 .FirstOrDefault();


问:
White Backdrop appears when I click md-select
I have this problem in some parts of my website where a white backdrop appears every time I click a dropdown(md-select) in my form. At first it occurred only on forms inside a modal but lately it affected page dropdowns as well.

I observed the behavior of css every time I clicked a dropdown and this is what I noticed: Some in-line style appears on my body tag during click.

```<code><body id="#background" style="position: fixed; width: 100%; top: -718.889px;">
</code>```

No idea where did it come from. I tried to change the 'position: fixed' into 'position: inherit' on inspect element and it solved the issue. Now my problem is I don`t know where to find it in my codes.

答:
Had the same problem.
Solved it by adding top: 0px to the container of the div that holds the elements that gets white blocks during clicking of the dropdown.

Body:
I have this problem in some parts of my website where a white backdrop appears every time I click a dropdown(md-select) in my form. At first it occurred only on forms inside a modal but lately it affected page dropdowns as well.

I observed the behavior of css every time I clicked a dropdown and this is what I noticed: Some in-line style appears on my body tag during click.

No idea where did it come from. I tried to change the 'position: fixed' into 'position: inherit' on inspect element and it solved the issue. Now my problem is I don`t know where to find it in my codes.


问:
MasterDetail Hamburger Menu disappearing on back button pressed
I've created a simple Xamarin.Forms application with Prism to experiment with the navigation. I have taken the example application an changed it slightly.

When the application loads and the user logs in the application goes to the Master Detail page through
 NavigationService.NavigateAsync("/Index/Navigation/Process"). On this page there is a button that does NavigationService.NavigateAsync("SecondProcess"). At this point the back button appears as expected but when it is pressed the app goes to the Process page and the hamburger menu is lost.

Am I using the navigation process incorrectly?

Edit:
I've uploaded the project to GitHub.
https://github.com/JonathanTurnerTBA/PrismExample.git

答:
At this point the back button appears as expected but when it is pressed the app goes to the Process page and the hamburger menu is lost.

The problem is you passed the Navigation Path is incomplete. For your design requirement, the MasterDetailPage is the root navigation, if you want to display the hamburg menu in the per page, you need to modify the navigation path like the following:

```<code>"/Index/Navigation/ProcessList/FirstProcess"
</code>```

When you press back button, the NavigationService will found the previous page /Index/Navigation/ProcessList, and attach hamburg menu automatically.

Body:
At this point the back button appears as expected but when it is pressed the app goes to the Process page and the hamburger menu is lost.

The problem is you passed the Navigation Path is incomplete. For your design requirement, the MasterDetailPage is the root navigation, if you want to display the hamburg menu in the per page, you need to modify the navigation path like the following:

"/Index/Navigation/ProcessList/FirstProcess"

When you press back button, the NavigationService will found the previous page /Index/Navigation/ProcessList, and attach hamburg menu automatically.


问:
Passing 2D-array to VBA/UDF function from sheet
I am on Excel 2010.

When a VBA user-defined function, say make2DArray, outputs a variant representing a 2D-array, this 2D-array can be then used as an input to another VBA function, say someFunction. While calling the functions from within VBA code. It works fine.

However when doing the same, passing make2DArray output as argument to someFunction, from within the sheet (via a formula in a cell), then it seems to work only for 2D-array with **2 or more rows**. Generating 2D-array with 1 row would fail. It seems that the 1-row 2D-array is then transformed automatically into an equivalent 1D-array.

A small example :

```<code>Option Explicit

'returns last (top-most, right-most) element
Function someFunction(v As Variant) As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    someFunction = v(UBound(v, 1), UBound(v, 2))
End Function

Function make2DArray(h As Integer, w As Integer) As Variant
    Dim i As Integer, j  As Integer
    Dim v2d As Variant

    ReDim v2d(1 To h, 1 To w)
    For i = 1 To h
        For j = 1 To w
            v2d(i, j) = i * j
        Next j
    Next i

    make2DArray = v2d
End Function

Sub test()
    'also works when called from sheet
    Debug.Print someFunction(make2DArray(2, 3)) 'returns 6
    'doesn't work when called from sheet
    Debug.Print someFunction(make2DArray(1, 3)) 'returns 3
End Sub
</code>```

The test function will work fine from within VBA. Similarly =someFunction(make2DArray(2, 3)) or any =someFunction(make2DArray(i, j)) cell formula would work well for i>1, however =someFunction(make2DArray(1, 3)) or any =someFunction(make2DArray(1, j)) will only produce a #VALUE! result in the sheet.

My question : Is this behavior documented somewhere? Is there a way to avoid the "casting" from 2D-array to 1D-array for 1-row 2D-arrays?

答:
From my comments:

I've never seen that before. It is like it is using transpose to convert a 2-D (one row) array into a 1-D array. I consider this a bug in that the VBA overhead is looking at a 2-D variant array with one 'row' (e.g. 1 as ubound first rank) and converting it to a 1-D array with the original ubound second rank as the ubound of the sole 1-D rank. For universality, the only suggestion I can come up with would be error control; I'll post a suggestion below.

Here is some error control to overcome the rogue 2-D to 1-D array conversion.

```<code>'returns bottom-right element of 2D-array
Function someFunction(v As Variant) 'As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    'Debug.Print IsArray(v)
    'Debug.Print UBound(v, 1) & ":" & UBound(v, 2)

    On Error GoTo err_1D_array
    someFunction = v(UBound(v, 1), UBound(v, 2))
    Exit Function

err_1D_array:
    someFunction = v(UBound(v))

End Function
</code>```

Body:
I am on Excel 2010.

When a VBA user-defined function, say make2DArray, outputs a variant representing a 2D-array, this 2D-array can be then used as an input to another VBA function, say someFunction. While calling the functions from within VBA code. It works fine.

However when doing the same, passing make2DArray output as argument to someFunction, from within the sheet (via a formula in a cell), then it seems to work only for 2D-array with **2 or more rows**. Generating 2D-array with 1 row would fail. It seems that the 1-row 2D-array is then transformed automatically into an equivalent 1D-array.

A small example :

Option Explicit

'returns last (top-most, right-most) element
Function someFunction(v As Variant) As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    someFunction = v(UBound(v, 1), UBound(v, 2))
End Function

Function make2DArray(h As Integer, w As Integer) As Variant
    Dim i As Integer, j  As Integer
    Dim v2d As Variant

    ReDim v2d(1 To h, 1 To w)
    For i = 1 To h
        For j = 1 To w
            v2d(i, j) = i * j
        Next j
    Next i

    make2DArray = v2d
End Function

Sub test()
    'also works when called from sheet
    Debug.Print someFunction(make2DArray(2, 3)) 'returns 6
    'doesn't work when called from sheet
    Debug.Print someFunction(make2DArray(1, 3)) 'returns 3
End Sub

The test function will work fine from within VBA. Similarly =someFunction(make2DArray(2, 3)) or any =someFunction(make2DArray(i, j)) cell formula would work well for i>1, however =someFunction(make2DArray(1, 3)) or any =someFunction(make2DArray(1, j)) will only produce a #VALUE! result in the sheet.

My question : Is this behavior documented somewhere? Is there a way to avoid the "casting" from 2D-array to 1D-array for 1-row 2D-arrays?

Body:
From my comments:

I've never seen that before. It is like it is using transpose to convert a 2-D (one row) array into a 1-D array. I consider this a bug in that the VBA overhead is looking at a 2-D variant array with one 'row' (e.g. 1 as ubound first rank) and converting it to a 1-D array with the original ubound second rank as the ubound of the sole 1-D rank. For universality, the only suggestion I can come up with would be error control; I'll post a suggestion below.

Here is some error control to overcome the rogue 2-D to 1-D array conversion.

'returns bottom-right element of 2D-array
Function someFunction(v As Variant) 'As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    'Debug.Print IsArray(v)
    'Debug.Print UBound(v, 1) & ":" & UBound(v, 2)

    On Error GoTo err_1D_array
    someFunction = v(UBound(v, 1), UBound(v, 2))
    Exit Function

err_1D_array:
    someFunction = v(UBound(v))

End Function


问:
How to make smooth marker movement using Google Maps API?
My marker jerks too sharply when it instantly changes its position. Is there any equivalent of a CSS transiton: 1s linear in Google Maps API so that my marker can move smoothly?
Here is my map init code:

var marker;

    function initMap() {
    // Map initialization
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 1,
            center: { lat: 59.325, lng: 18.070 }
        });
    // Marker settings
        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: { lat: 59.327, lng: 18.067 }
        });
    // Marker moves every second
        setInterval( () => {
            moveMarker();
        }, 1000);
    }

    var a = 1;
    function moveMarker() {
        marker.setPosition(new google.maps.LatLng(a++, a++));
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  width: 500px;
  height: 500px;
}</code>```

```

答:
It's very doable but takes work. The important bit is identifying the DIVs Google Maps is using for your marker (There are 2 one is transparent for touch events) The investigation has been done for you and you really only have to understand it once.

A complete example can be found here See how smoothly Hansel and Gretel move around the map! And the transition times coalesce if there is any delay.

All the code for my Brotkrumen Ultimate Web App can be found here you will be mostly interested in the HandleMap.js file but there is a aaa_readme.txt

Here is part of the code: -

```<code>function showJourney(){
    map.setZoom(map.getZoom());
    map.setOptions({gestureHandling: "none"});
    zoomOut.style.display = "none";
    zoomIn.style.display  = "none";

    hat.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    hat.setVisible(true);
    hat.setAnimation(bounce);

    HandG.setPosition(
        new google.maps.LatLng(
                firstPos.coords.latitude,
                firstPos.coords.longitude));
    HandG.setVisible(true);

    map.panTo(path[0]);
    google.maps.event.trigger(map, 'resize');

    if (document.querySelectorAll(MARKER_SELECTOR).length == 0){
        observer.observe(mapDiv, {
                        childList     : true,
                        subtree       : true ,
                        attributes    : true ,
                        characterData : false
                        })
    } else {
        setTimeout(plotTrip,0);
    }
}
function plotTrip(){
    nextFunc = plotStep;
    hat.setAnimation(bounce);
    HandG.setPosition(path[0]);
    dirPoly.setVisible(true);
    progressPath = [];
    progressPath.push(path[0]);
    dirPoly.setPath(path);
    stepPoly.setPath(progressPath);
    stepPoly.setVisible(true);
    currStep = 1;
    markerDivs = [];
    var markerImgs = document.querySelectorAll(MARKER_SELECTOR);
    for (var i=0; i<markerImgs.length; i++){
        console.log(markerImgs[i].src);
        markerDivs[i] = markerImgs[i].parentNode;
        markerDivs[i].style.transitionDuration = "0s";
        markerDivs[i].style.transitionProperty = "left, top";
        markerDivs[i].style.transitionTimingFunction = "linear";
    }

    setTimeout(plotStep,0);
    abort = false;
    btn.value = "Cancel";
    btn.disabled = false;
}
function plotStep(){
    if (abort) return;

    if (legs[currStep].didLoiter){
        countDown = legs[currStep].restTime;
        infoWindow.setContent(
            "<div id='waitDiv'><span>Waiting</span></div>");
        infoWindow.open(map,HandG);
        showInterval();
    } else {
        plotIt();
    }
}
function showInterval(){
    if (abort) return;

    infoWindow.setContent(
        "<div id='waitDiv'><span>Waiting "+deltaDate(countDown)+"</span></div>");
    countDown -= (ONE_SEC * multiSpeed);
    if (countDown < 1){
        infoWindow.close();
        plotIt();
    } else {
        setTimeout(showInterval, ONE_SEC);
    }
}
function plotIt(){
    if (abort) return;

    progressPath.push(path[currStep]);
    stepPoly.setPath(progressPath);
    map.panTo(path[currStep]);
    var transitionMS = legs[currStep].duration / multiSpeed;
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = transitionMS + "ms";
    }
    HandG.setPosition(path[currStep])

    if (++currStep >= path.length)
        nextFunc = cleanUp;

    plotTimer = setTimeout(nextFunc,transitionMS);
}
function cleanUp(){
    infoWindow.close();
    hat.setAnimation();
    btn.value = "Replay";
    btn.disabled = false;
    clearTimeout(plotTimer);
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = "0s";
    }
    HandG.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    HandG.setVisible(false);
    map.setOptions({gestureHandling: "cooperative"});
    zoomIn.style.display  = "";
    zoomOut.style.display = "";
    if (canTalk && !abort)
        speechSynthesis.speak(finish);
}
function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" &&
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0)
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}
</code>```

Body:
My marker jerks too sharply when it instantly changes its position. Is there any equivalent of a CSS transiton: 1s linear in Google Maps API so that my marker can move smoothly?
Here is my map init code:

var marker;

    function initMap() {
    // Map initialization
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 1,
            center: { lat: 59.325, lng: 18.070 }
        });
    // Marker settings
        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: { lat: 59.327, lng: 18.067 }
        });
    // Marker moves every second
        setInterval( () => {
            moveMarker();
        }, 1000);
    }

    var a = 1;
    function moveMarker() {
        marker.setPosition(new google.maps.LatLng(a++, a++));
    }

#map {
  width: 500px;
  height: 500px;
}

Body:
It's very doable but takes work. The important bit is identifying the DIVs Google Maps is using for your marker (There are 2 one is transparent for touch events) The investigation has been done for you and you really only have to understand it once.

A complete example can be found here See how smoothly Hansel and Gretel move around the map! And the transition times coalesce if there is any delay.

All the code for my Brotkrumen Ultimate Web App can be found here you will be mostly interested in the HandleMap.js file but there is a aaa_readme.txt

Here is part of the code: -

function showJourney(){
    map.setZoom(map.getZoom());
    map.setOptions({gestureHandling: "none"});
    zoomOut.style.display = "none";
    zoomIn.style.display  = "none";

    hat.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    hat.setVisible(true);
    hat.setAnimation(bounce);

    HandG.setPosition(
        new google.maps.LatLng(
                firstPos.coords.latitude,
                firstPos.coords.longitude));
    HandG.setVisible(true);

    map.panTo(path[0]);
    google.maps.event.trigger(map, 'resize');

    if (document.querySelectorAll(MARKER_SELECTOR).length == 0){
        observer.observe(mapDiv, {
                        childList     : true,
                        subtree       : true ,
                        attributes    : true ,
                        characterData : false
                        })
    } else {
        setTimeout(plotTrip,0);
    }
}
function plotTrip(){
    nextFunc = plotStep;
    hat.setAnimation(bounce);
    HandG.setPosition(path[0]);
    dirPoly.setVisible(true);
    progressPath = [];
    progressPath.push(path[0]);
    dirPoly.setPath(path);
    stepPoly.setPath(progressPath);
    stepPoly.setVisible(true);
    currStep = 1;
    markerDivs = [];
    var markerImgs = document.querySelectorAll(MARKER_SELECTOR);
    for (var i=0; i<markerImgs.length; i++){
        console.log(markerImgs[i].src);
        markerDivs[i] = markerImgs[i].parentNode;
        markerDivs[i].style.transitionDuration = "0s";
        markerDivs[i].style.transitionProperty = "left, top";
        markerDivs[i].style.transitionTimingFunction = "linear";
    }

    setTimeout(plotStep,0);
    abort = false;
    btn.value = "Cancel";
    btn.disabled = false;
}
function plotStep(){
    if (abort) return;

    if (legs[currStep].didLoiter){
        countDown = legs[currStep].restTime;
        infoWindow.setContent(
            "<div id='waitDiv'><span>Waiting</span></div>");
        infoWindow.open(map,HandG);
        showInterval();
    } else {
        plotIt();
    }
}
function showInterval(){
    if (abort) return;

    infoWindow.setContent(
        "<div id='waitDiv'><span>Waiting "+deltaDate(countDown)+"</span></div>");
    countDown -= (ONE_SEC * multiSpeed);
    if (countDown < 1){
        infoWindow.close();
        plotIt();
    } else {
        setTimeout(showInterval, ONE_SEC);
    }
}
function plotIt(){
    if (abort) return;

    progressPath.push(path[currStep]);
    stepPoly.setPath(progressPath);
    map.panTo(path[currStep]);
    var transitionMS = legs[currStep].duration / multiSpeed;
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = transitionMS + "ms";
    }
    HandG.setPosition(path[currStep])

    if (++currStep >= path.length)
        nextFunc = cleanUp;

    plotTimer = setTimeout(nextFunc,transitionMS);
}
function cleanUp(){
    infoWindow.close();
    hat.setAnimation();
    btn.value = "Replay";
    btn.disabled = false;
    clearTimeout(plotTimer);
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = "0s";
    }
    HandG.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    HandG.setVisible(false);
    map.setOptions({gestureHandling: "cooperative"});
    zoomIn.style.display  = "";
    zoomOut.style.display = "";
    if (canTalk && !abort)
        speechSynthesis.speak(finish);
}
function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" &&
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0)
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}


问:
Subaccount SID & Token Retrieval
I currently am developing a PHP application for a large amount of users using the Twilio API.

I was successful in allowing users to login and create a subaccount, but what I found I need to do in order for them to be able to individually purchase their own numbers is dynamically pull each subaccount SID & Access token based on whatever account is currently logged in (or so I think this is the way of going about it).

From what I can see in the API documentation, it doesn't seem like there's a straightforward way of doing this.

Can anyone offer any guidance?

答:
As long as you set the FriendlyName to match you member's ID or linkable name; you can pull it from Twilio like:</p>

```<code>$client = new Client($masterSID, $masterToken);
$subAccounts = $client->api->accounts->read(
        array("friendlyName" => "Member:1")
);
$subAccount = array_pop($subAccounts);
echo $subAccount->sid . "\r\n";
echo $subAccount->authToken . "\r\n";
echo $subAccount->status;
</code>```

Title: Subaccount SID & Token Retrieval

Body:
As long as you set the FriendlyName to match you member's ID or linkable name; you can pull it from Twilio like:

$client = new Client($masterSID, $masterToken);
$subAccounts = $client->api->accounts->read(
        array("friendlyName" => "Member:1")
);
$subAccount = array_pop($subAccounts);
echo $subAccount->sid . "\r\n";
echo $subAccount->authToken . "\r\n";
echo $subAccount->status;


问:
How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator
I have the following simple code written in Swift 3:

```<code>let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)
</code>```

From Xcode 9 beta 5, I get the following warning:

'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.

How can this slicing subscript with partial range from be used in Swift 4?

答:
Creating SubString (prefix and suffix) from String using Swift 4:

```<code>let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}
</code>```

Output

```<code>prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix :
</code>```

If you want to generate a substring between 2 indices , use :

```<code>let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following simple code written in Swift 3:

let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)

From Xcode 9 beta 5, I get the following warning:

'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.

How can this slicing subscript with partial range from be used in Swift 4?

Body:
Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix :

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex


问:
Mocking adding items to a list in .NET NMock2
I'm using NMock2 (2.1.3641.27570) in my unit tests.

IList<MyObj> values = _mock.NewMock<IList<MyObj>>();

That mock I return when my tested object calls the Values get property on my mocked object:

Expect.AtLeastOnce.On(_myKeepMock).GetProperty("Values").Will(Return.Value(values));

Then I expect value which is a MyObj to be added to my list values:

Expect.AtLeastOnce.On(values).Method("Add").With(value);

In order to avoid unexpected invocation of list'1.Add upon execution I understand I have to override the Equals method in the MyObj class:

public override bool Equals(object obj) { ...}

and compare by value instead of reference. But it doesn't even get called when executing the test (breakpoint not hit).

What do I need to do in order to pass the test when the item added to the list in the call is equal in value to the one added by the tested object?

I read about custom matchers but not sure if those apply here.

UPDATE

Full example:

```<code>using System.Collections.Generic;
using System.Linq;
using NMock2;
using NUnit.Framework;

public class Data
{
    public int Val { get; set; }

    public Data(int val) { Val = val; }

}
public class ModData
{
    public int Val { get; set; }

    protected bool Equals(ModData other)
    {
        return this.Val.Equals(other.Val);
    }

    public override int GetHashCode()
    {
        return this.Val.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        ModData m = (ModData)obj;

        return m != null && this.Val == m.Val;
    }

}

public interface IAllData
{
    IList<Data> Data { get; set; }
    IList<ModData> ModData { get; set; }
}

public class AllData : IAllData
{
    public IList<Data> Data { get; set; }
    public IList<ModData> ModData { get; set; }

}

public class Calco
{
    private IAllData _allData;

    public Calco(IAllData allData)
    {
        _allData = allData;
    }

    public void Sum()
    {
        _allData.ModData.Add(new ModData { Val = _allData.Data.Sum(d => d.Val) });
    }
}

public class CalcoTest
{
    [Test]
    public void Test()
    {
        Mockery mockery = new Mockery();
        IList<Data> data = new List<Data>();
        IList<ModData> modData = mockery.NewMock<IList<ModData>>();
        IAllData allData = mockery.NewMock<IAllData>();

        ModData modDatum = new ModData { Val = 4 };

        data.Add(new Data(1));
        data.Add(new Data(10));

        Calco c = new Calco(allData);

        Expect.AtLeastOnce.On(allData).GetProperty("Data").Will(Return.Value(data));
        Expect.AtLeastOnce.On(allData).GetProperty("ModData").Will(Return.Value(modData));
        Expect.AtLeastOnce.On(modData).Method("Add").With(modDatum);

        c.Sum();

        mockery.VerifyAllExpectationsHaveBeenMet();

    }
}
</code>```

Output:

```<code>NMock2.Internal.ExpectationException : unexpected invocation of list`1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)
Expected:
  at least 1 time: allData.Data, will return <System.Collections.Generic.List`1[WRM.Common.RiskCalculation.Tests.Data]> [called 1 time]
  at least 1 time: allData.ModData, will return <list`1> [called 1 time]
  at least 1 time: list`1.Add(equal to <WRM.Common.RiskCalculation.Tests.ModData>) [called 0 times]
</code>```

Notice how it expects invocation of list'1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)
and then shows it didn't call list'1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)

答:
Custom Matchers ARE the answer: http://nmock.sourceforge.net/advanced.html

```<code>public class IsMod
{
    public static Matcher Equal(ModData otherMod)
    {
        return new ModMatcher(otherMod);
    }
}

internal class ModMatcher : Matcher
{
    private readonly ModData _mod;

    public ModMatcher(ModData mod)
    {
        _mod = mod;
    }

    public override bool Matches(object o)
    {

        ModData m = (ModData)o;
        return _mod.Val.Equals(m.Val);
    }

    public override void DescribeTo(TextWriter writer)
    {
        writer.Write("Value same ");
        writer.Write(_mod.Val);
    }
}
</code>```

And then

```<code>Expect.AtLeastOnce.On(modData).Method("Add").With(IsMod.Equal(modDatum));
</code>```

Done!

Body:
I'm using NMock2 (2.1.3641.27570) in my unit tests.

IList<MyObj> values = _mock.NewMock<IList<MyObj>>();

That mock I return when my tested object calls the Values get property on my mocked object:

Expect.AtLeastOnce.On(_myKeepMock).GetProperty("Values").Will(Return.Value(values));

Then I expect value which is a MyObj to be added to my list values:

Expect.AtLeastOnce.On(values).Method("Add").With(value);

In order to avoid unexpected invocation of list'1.Add upon execution I understand I have to override the Equals method in the MyObj class:

public override bool Equals(object obj) { ...}

and compare by value instead of reference. But it doesn't even get called when executing the test (breakpoint not hit).

What do I need to do in order to pass the test when the item added to the list in the call is equal in value to the one added by the tested object?

I read about custom matchers but not sure if those apply here.

UPDATE

Full example:

using System.Collections.Generic;
using System.Linq;
using NMock2;
using NUnit.Framework;

public class Data
{
    public int Val { get; set; }

    public Data(int val) { Val = val; }

}
public class ModData
{
    public int Val { get; set; }

    protected bool Equals(ModData other)
    {
        return this.Val.Equals(other.Val);
    }

    public override int GetHashCode()
    {
        return this.Val.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        ModData m = (ModData)obj;

        return m != null && this.Val == m.Val;
    }

}

public interface IAllData
{
    IList<Data> Data { get; set; }
    IList<ModData> ModData { get; set; }
}

public class AllData : IAllData
{
    public IList<Data> Data { get; set; }
    public IList<ModData> ModData { get; set; }

}

public class Calco
{
    private IAllData _allData;

    public Calco(IAllData allData)
    {
        _allData = allData;
    }

    public void Sum()
    {
        _allData.ModData.Add(new ModData { Val = _allData.Data.Sum(d => d.Val) });
    }
}

public class CalcoTest
{
    [Test]
    public void Test()
    {
        Mockery mockery = new Mockery();
        IList<Data> data = new List<Data>();
        IList<ModData> modData = mockery.NewMock<IList<ModData>>();
        IAllData allData = mockery.NewMock<IAllData>();

        ModData modDatum = new ModData { Val = 4 };

        data.Add(new Data(1));
        data.Add(new Data(10));

        Calco c = new Calco(allData);

        Expect.AtLeastOnce.On(allData).GetProperty("Data").Will(Return.Value(data));
        Expect.AtLeastOnce.On(allData).GetProperty("ModData").Will(Return.Value(modData));
        Expect.AtLeastOnce.On(modData).Method("Add").With(modDatum);

        c.Sum();

        mockery.VerifyAllExpectationsHaveBeenMet();

    }
}

Output:

NMock2.Internal.ExpectationException : unexpected invocation of list`1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)
Expected:
  at least 1 time: allData.Data, will return <System.Collections.Generic.List`1[WRM.Common.RiskCalculation.Tests.Data]> [called 1 time]
  at least 1 time: allData.ModData, will return <list`1> [called 1 time]
  at least 1 time: list`1.Add(equal to <WRM.Common.RiskCalculation.Tests.ModData>) [called 0 times]

Notice how it expects invocation of list'1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)
and then shows it didn't call list'1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)

Body:
Custom Matchers ARE the answer: http://nmock.sourceforge.net/advanced.html

public class IsMod
{
    public static Matcher Equal(ModData otherMod)
    {
        return new ModMatcher(otherMod);
    }
}

internal class ModMatcher : Matcher
{
    private readonly ModData _mod;

    public ModMatcher(ModData mod)
    {
        _mod = mod;
    }

    public override bool Matches(object o)
    {

        ModData m = (ModData)o;
        return _mod.Val.Equals(m.Val);
    }

    public override void DescribeTo(TextWriter writer)
    {
        writer.Write("Value same ");
        writer.Write(_mod.Val);
    }
}

And then

Expect.AtLeastOnce.On(modData).Method("Add").With(IsMod.Equal(modDatum));

Done!


问:
What am I doing wrong with realloc() in c?
I would like to ask, what am I doing wrong with memory management. I just want to read some int array from stdin and then print it. Starting from 2 elements, then allocating by 2 to amount I will be satisfied with.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

void read (int * array, int * n, int * l) {
    int * tmp;
    printf("Enter values:\n");
    for (*l = 0; *l < *n; (*l)++) {
        if (*l == *n - 1) {
            (*n) *= 2;
            tmp = (int*) realloc (array, sizeof(int) * (*n));
            if (tmp != NULL) {
                array = tmp;
                free(tmp);
            }
            else {
                printf("Error!\n");
                free(tmp);
        }
        if (scanf("%d", &array[*l]) != 1) break;
    }
}

void print (int * array, int length) {
    int i;
    printf("Your values:\n");
    for (i = 0; i < length; i++) printf("%d ", array[i]);
}

int main (void) {
    int n = 2; /* number of array elements */
    int length = 0;
    int * array = (int *) malloc(sizeof(int) * n);

    read(array, &n, &length);
    print(array, length);
    free(array);
    return 0;
}
</code>```

答: Remove the free after a successful realloc.  Realloc takes care of that for you.  Also, if you ever hit the error case, you will double free() your buffer.</p>

Body:
I would like to ask, what am I doing wrong with memory management. I just want to read some int array from stdin and then print it. Starting from 2 elements, then allocating by 2 to amount I will be satisfied with.

#include <stdio.h>
#include <stdlib.h>

void read (int * array, int * n, int * l) {
    int * tmp;
    printf("Enter values:\n");
    for (*l = 0; *l < *n; (*l)++) {
        if (*l == *n - 1) {
            (*n) *= 2;
            tmp = (int*) realloc (array, sizeof(int) * (*n));
            if (tmp != NULL) {
                array = tmp;
                free(tmp);
            }
            else {
                printf("Error!\n");
                free(tmp);
        }
        if (scanf("%d", &array[*l]) != 1) break;
    }
}

void print (int * array, int length) {
    int i;
    printf("Your values:\n");
    for (i = 0; i < length; i++) printf("%d ", array[i]);
}

int main (void) {
    int n = 2; /* number of array elements */
    int length = 0;
    int * array = (int *) malloc(sizeof(int) * n);

    read(array, &n, &length);
    print(array, length);
    free(array);
    return 0;
}


问:
iOS Development: What are some reasons I should to use XAuth to authenticate a twitter user?
I see many people using XAuth in their app to authenticate twitter users and I'm wondering what are some situations that I would want to use XAuth in my own apps.

Thanks for your wisdom!

答: xAuth lets you skip showing a web view containing the Twitter login. It makes for a simpler and less jarring user experience for non-web apps.</p>

ContentLicense: CC BY-SA 2.5


问:
Toggle logscale option for dygraph in rmarkdown
I would really like a dygraph that comes with a checkbox to toggle the Y axis to logscale. I know I can do this with shiny, but I can do pretty much everything else I need for this project using rmarkdown without shiny, which allows me to deliver .html without having to set up a shiny server.

I know it isn't complicated on the dygraph side of things
http://dygraphs.com/options.html#logscale

And I think rmarkdown is certainly flexible enough to do it
http://livefreeordichotomize.com/2017/01/24/custom-javascript-visualizations-in-rmarkdown/

But how?

答:
You could use {.tabset} and plot both scales separately.

```<code>---
output:
  html_document:
    code_folding: hide
    theme: flatly
    toc: yes
    toc_depth: 3
    toc_float: yes
---

```{r setup, include=FALSE}
library(tidyr)
library(dplyr)
library(tibble)
library(dygraphs)
```

# Plots {.tabset .tabset-fade .tabset-pills}

## Normal Y

```{r plot_norm}
dygraph(AirPassengers, main = "Airline Passengers / Month") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dyAxis("y", label = "Passengers (Thousands)") %>%
  dyOptions(includeZero = TRUE,
            axisLineColor = "navy",
            gridLineColor = "lightblue")
```

## Log Y

```{r plot_log}
dygraph(AirPassengers, main = "Airline Passengers / Month") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dyAxis("y", label = "Passengers (Thousands)", logscale = TRUE) %>%
  dyOptions(logscale = TRUE,
            axisLineColor = "navy",
            gridLineColor = "lightblue")
```
</code>```

Body:
You could use {.tabset} and plot both scales separately.

---
output:
  html_document:
    code_folding: hide
    theme: flatly
    toc: yes
    toc_depth: 3
    toc_float: yes
---

```{r setup, include=FALSE}
library(tidyr)
library(dplyr)
library(tibble)
library(dygraphs)
```

# Plots {.tabset .tabset-fade .tabset-pills}

## Normal Y

```{r plot_norm}
dygraph(AirPassengers, main = "Airline Passengers / Month") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dyAxis("y", label = "Passengers (Thousands)") %>%
  dyOptions(includeZero = TRUE,
            axisLineColor = "navy",
            gridLineColor = "lightblue")
```

## Log Y

```{r plot_log}
dygraph(AirPassengers, main = "Airline Passengers / Month") %>%
  dyAxis("x", drawGrid = FALSE) %>%
  dyAxis("y", label = "Passengers (Thousands)", logscale = TRUE) %>%
  dyOptions(logscale = TRUE,
            axisLineColor = "navy",
            gridLineColor = "lightblue")
```


问:
Mvvmcross Android TextInputEditText Binding Enabled
I have a Switch and a TextInputEditText. Both 'Enabled' are bound to the same field in the viewmodel.

When the activity is loaded, the bound field is set to false. The Switch is disabled as expected. However, the TextInputEditText is enabled. The 'Clickable' has the same issue. Text is bound successfully.

After changed the bound field to true and then false, the TextInputEditText Enable & Clickable work correctly. It seems that it only happens when it is loaded initially.

```<code>            <android.support.v7.widget.SwitchCompat
                style="@style/EntryTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                local:MvxLang="Text LabelDeferArrivalNotice"
                local:MvxBind="Checked RouteMarker.DeferArrivalNotice; Enabled RouteMarker.ArrivalNotice" />
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <android.support.design.widget.TextInputEditText
                    android:id="@+id/edittext_route_marker_EffectiveFromDateTime"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:singleLine="true"
                    android:editable="false"
                    android:focusableInTouchMode="false"
                    style="@style/EntryTextStyle"
                    local:MvxLang="Hint LabelEffectiveFromTime"
                    local:MvxBind="Text DateTimeToString(RouteMarker.EffectiveFromDateTime);
                                   Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice;
                                   Click PromptDeferTimeCommand" />
</code>```

Is there anything special I have to do with the TextInputEditText?

Thanks

答:
This is an issue with MvvmCross, as Stuart said, there are some interaction between ICommand.CanExecute and the Enabled property. Switching the binding to :

```<code>local:MvxBind="Click PromptDeferTimeCommand;Enabled RouteMarker.ArrivalNotice;Clickable RouteMarker.ArrivalNotice;"
</code>```

Hope to help somebody who searched this problem.

Body:
I have a Switch and a TextInputEditText. Both 'Enabled' are bound to the same field in the viewmodel.

When the activity is loaded, the bound field is set to false. The Switch is disabled as expected. However, the TextInputEditText is enabled. The 'Clickable' has the same issue. Text is bound successfully.

After changed the bound field to true and then false, the TextInputEditText Enable & Clickable work correctly. It seems that it only happens when it is loaded initially.

            <android.support.v7.widget.SwitchCompat
                style="@style/EntryTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                local:MvxLang="Text LabelDeferArrivalNotice"
                local:MvxBind="Checked RouteMarker.DeferArrivalNotice; Enabled RouteMarker.ArrivalNotice" />
            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <android.support.design.widget.TextInputEditText
                    android:id="@+id/edittext_route_marker_EffectiveFromDateTime"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:singleLine="true"
                    android:editable="false"
                    android:focusableInTouchMode="false"
                    style="@style/EntryTextStyle"
                    local:MvxLang="Hint LabelEffectiveFromTime"
                    local:MvxBind="Text DateTimeToString(RouteMarker.EffectiveFromDateTime);
                                   Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice;
                                   Click PromptDeferTimeCommand" />

Is there anything special I have to do with the TextInputEditText?

Thanks

Body:
This is an issue with MvvmCross, as Stuart said, there are some interaction between ICommand.CanExecute and the Enabled property. Switching the binding to :

local:MvxBind="Click PromptDeferTimeCommand;Enabled RouteMarker.ArrivalNotice;Clickable RouteMarker.ArrivalNotice;"

Hope to help somebody who searched this problem.


问:
Is there a maximum length for django request URL?

I was trying to send a get request to django beackend which encodes a list of ids that I need. I noticed that when this list of id(string) goes too long, the django will not handle this request. I can see the request in the django test server, but it never actually enter any view. In the browser, nginx gives me 404.

```<code>URL: "/xxx/xxx/xxx?type=xxx&ids=4918230_25808605%2C4996758_49144848%2C5121093_43940616%2C56944804_40780188...."
</code>```

I know I can maybe use post to encode params in the body instead, but I just want to find out the reason behind this.

答: The length of URL is often restricted by the Web Browser</p>

Body:
I was trying to send a get request to django beackend which encodes a list of ids that I need. I noticed that when this list of id(string) goes too long, the django will not handle this request. I can see the request in the django test server, but it never actually enter any view. In the browser, nginx gives me 404.

URL: "/xxx/xxx/xxx?type=xxx&ids=4918230_25808605%2C4996758_49144848%2C5121093_43940616%2C56944804_40780188...."

I know I can maybe use post to encode params in the body instead, but I just want to find out the reason behind this.


问:
Memory leaks caused due to CoreFoundation Framework
I am developing an iPhone application which mainly makes use of the Address Book and database. After fetching about 3000 contacts from the address book, I am attaching string tags to the contacts (5 for each). I am saving my tags in the database.

For Load testing purpose i have added 10,000 tags to the App. But during the load testing of my application, I observed some memory leaks which were not related to the Application code but represents a set of Instruction sets. Also Instruments showed Foundation as the  responsible library for the Leak (Extensive use of NSString,NSDictionary,NSArray which belongs to the Foundation framework). My application crashes after 10 - 15 mins of usage.The Crash report mentions, application crashed due to low memory.

Memory profiling using CLANG shows zero leaks. How do i solve these memory leaks?
Are these leaks the real culprit behind the crash? Are there any other tools available to check memory leaks?

答:
Most likely you have code that is creating the foundation objects.  Leaks shows you the place of allocation but that is generally due to a call your code made to create the object.  You can look at the call chain in Instruments and go back along the call chain until you get to your code - that is the place where you are causing the allocation.  Now, for that allocation, look at your memory handling for that object: Do you release it some time later?

There are lots of ways you can fail to release memory property so it would be hard to guess which one you might be hitting. Ones I see when helping people include allocating an object and assigning it to an instance variable via a property with the retain attribute, something like this:

@property (retain) NSString* myString;

...

self.myString = [[NSString alloc] initWithString: @"foo"];

the alloc+init creates a retained object, the self.myString =  increments the retain count again.  If coded correctly, the dealloc method releases the property via one of:

[myString release];
or
self.myString = nil;

And that takes care of the retain added with the self.myString =   but does NOT take care of the retain from creation.  Solutions, ONE of the following:

myString = [[NSString alloc] initWithString: @"foo"];  // doesn't call the setter method so no assignment retain - but doesn't call the setter which might be bad if non-trivial setter.

self.myString = [[[NSString alloc] initWithString: @"foo"] autorelease];

autorelease releases the alloc+init retain.

Now of course this is a contrived example because you'd probably really use:

self.myString = [NSString stringWithString: @"foo"];

which is a class method returning an autoreleased string and avoids the problem.  But the idea is to show a simple example to explain this type of issue.

There are many other ways to not release memory properly, but the advice to work your way back up the call-chain until you get to your code is the way to go look at where you are triggering the allocation of the memory and then you can figure out why you aren't releasing that properly.


问:
Spark Job submitted - Waiting (TaskSchedulerImpl : Initial job not accepted)
API call made to submit the Job. Response states - It is Running

On Cluster UI -

Worker (slave) - worker-20160712083825-172.31.17.189-59433 is Alive

Core 1 out of 2 used

Memory 1Gb out of 6 used

Running Application

app-20160713130056-0020 - Waiting since 5hrs

Cores - unlimited

Job Description of the Application

Active Stage

reduceByKey at /root/wordcount.py:23

Pending Stage

takeOrdered at /root/wordcount.py:26

Running Driver -

```<code>stderr log page for driver-20160713130051-0025

WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
</code>```

According to Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
Slaves haven't been started - Hence it doesn't have resources.

However in my case - Slave 1 is working

According to Unable to Execute More than a spark Job "Initial job has not accepted any resources"
I am using deploy-mode = cluster (not client) Since I have 1 master 1 slave and Submit API is being called via Postman / anywhere

Also the Cluster has available Cores, RAM, Memory - Still Job throws the error
as conveyed by the UI

According to TaskSchedulerImpl: Initial job has not accepted any resources;
I assigned

```<code>~/spark-1.5.0/conf/spark-env.sh
</code>```

Spark Environment Variables

```<code>SPARK_WORKER_INSTANCES=1
SPARK_WORKER_MEMORY=1000m
SPARK_WORKER_CORES=2
</code>```

Replicated those across the Slaves

```<code>sudo /root/spark-ec2/copy-dir /root/spark/conf/spark-env.sh
</code>```

All the cases in the answer to above question - were applicable still no solution found. Hence because I was working with APIs and Apache SPark - maybe some other assistance is required.

Edited July 18,2016

Wordcount.py - My PySpark application code -

```<code>from pyspark import SparkContext, SparkConf

logFile = "/user/root/In/a.txt"

conf = (SparkConf().set("num-executors", "1"))

sc = SparkContext(master = "spark://ec2-54-209-108-127.compute-1.amazonaws.com:7077", appName = "MyApp", conf = conf)
print("in here")
lines = sc.textFile(logFile)
print("text read")
c = lines.count()
print("lines counted")
</code>```

Error

```<code>Starting job: count at /root/wordcount.py:11
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Got job 0 (count at /root/wordcount.py:11) with 2 output partitions
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Final stage: ResultStage 0 (count at /root/wordcount.py:11)
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Parents of final stage: List()
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Missing parents: List()
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Submitting ResultStage 0 (PythonRDD[2] at count at /root/wordcount.py:11), which has no missing parents
16/07/18 07:46:39 INFO storage.MemoryStore: Block broadcast_1 stored as values in memory (estimated size 5.6 KB, free 56.2 KB)
16/07/18 07:46:39 INFO storage.MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 3.4 KB, free 59.7 KB)
16/07/18 07:46:39 INFO storage.BlockManagerInfo: Added broadcast_1_piece0 in memory on 172.31.17.189:43684 (size: 3.4 KB, free: 511.5 MB)
16/07/18 07:46:39 INFO spark.SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1006
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Submitting 2 missing tasks from ResultStage 0 (PythonRDD[2] at count at /root/wordcount.py:11)
16/07/18 07:46:39 INFO scheduler.TaskSchedulerImpl: Adding task set 0.0 with 2 tasks
16/07/18 07:46:54 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
</code>```

According to Spark UI showing 0 cores even when setting cores in App,

Spark WebUI states zero cores used and indefinite wait no tasks running. The application is also using NO MEMORY whatsoever during run time or cores and immediately hits a status of waiting when starting

Spark version 1.6.1
Ubuntu
Amazon EC2

答:
You can take a look at my answer in a similar question Apache Spark on Mesos: Initial job has not accepted any resources:

While most of other answers focuses on resource allocation (cores, memory) on spark slaves, I would like to highlight that firewall could cause exactly the same issue, especially when you are running spark on cloud platforms.

If you can find spark slaves in the web UI, you have probably opened the standard ports 8080, 8081, 7077, 4040. Nonetheless, when you actually run a job, it uses SPARK_WORKER_PORT, spark.driver.port and spark.blockManager.port which by default are randomly assigned. If your firewall is blocking these ports, the master could not retrieve any job-specific response from slaves and return the error.

You can run a quick test by opening all the ports and see whether the slave accepts jobs.

Body:
API call made to submit the Job. Response states - It is Running

On Cluster UI -

Worker (slave) - worker-20160712083825-172.31.17.189-59433 is Alive

Core 1 out of 2 used

Memory 1Gb out of 6 used

Running Application

app-20160713130056-0020 - Waiting since 5hrs

Cores - unlimited

Job Description of the Application

Active Stage

reduceByKey at /root/wordcount.py:23

Pending Stage

takeOrdered at /root/wordcount.py:26

Running Driver -

stderr log page for driver-20160713130051-0025

WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources

According to Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
Slaves haven't been started - Hence it doesn't have resources.

However in my case - Slave 1 is working

According to Unable to Execute More than a spark Job "Initial job has not accepted any resources"
I am using deploy-mode = cluster (not client) Since I have 1 master 1 slave and Submit API is being called via Postman / anywhere

Also the Cluster has available Cores, RAM, Memory - Still Job throws the error
as conveyed by the UI

According to TaskSchedulerImpl: Initial job has not accepted any resources;
I assigned

~/spark-1.5.0/conf/spark-env.sh

Spark Environment Variables

SPARK_WORKER_INSTANCES=1
SPARK_WORKER_MEMORY=1000m
SPARK_WORKER_CORES=2

Replicated those across the Slaves

sudo /root/spark-ec2/copy-dir /root/spark/conf/spark-env.sh

All the cases in the answer to above question - were applicable still no solution found. Hence because I was working with APIs and Apache SPark - maybe some other assistance is required.

Edited July 18,2016

Wordcount.py - My PySpark application code -

from pyspark import SparkContext, SparkConf

logFile = "/user/root/In/a.txt"

conf = (SparkConf().set("num-executors", "1"))

sc = SparkContext(master = "spark://ec2-54-209-108-127.compute-1.amazonaws.com:7077", appName = "MyApp", conf = conf)
print("in here")
lines = sc.textFile(logFile)
print("text read")
c = lines.count()
print("lines counted")

Error

Starting job: count at /root/wordcount.py:11
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Got job 0 (count at /root/wordcount.py:11) with 2 output partitions
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Final stage: ResultStage 0 (count at /root/wordcount.py:11)
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Parents of final stage: List()
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Missing parents: List()
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Submitting ResultStage 0 (PythonRDD[2] at count at /root/wordcount.py:11), which has no missing parents
16/07/18 07:46:39 INFO storage.MemoryStore: Block broadcast_1 stored as values in memory (estimated size 5.6 KB, free 56.2 KB)
16/07/18 07:46:39 INFO storage.MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 3.4 KB, free 59.7 KB)
16/07/18 07:46:39 INFO storage.BlockManagerInfo: Added broadcast_1_piece0 in memory on 172.31.17.189:43684 (size: 3.4 KB, free: 511.5 MB)
16/07/18 07:46:39 INFO spark.SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1006
16/07/18 07:46:39 INFO scheduler.DAGScheduler: Submitting 2 missing tasks from ResultStage 0 (PythonRDD[2] at count at /root/wordcount.py:11)
16/07/18 07:46:39 INFO scheduler.TaskSchedulerImpl: Adding task set 0.0 with 2 tasks
16/07/18 07:46:54 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources

According to Spark UI showing 0 cores even when setting cores in App,

Spark WebUI states zero cores used and indefinite wait no tasks running. The application is also using NO MEMORY whatsoever during run time or cores and immediately hits a status of waiting when starting

Spark version 1.6.1
Ubuntu
Amazon EC2


问:
JQuery to get input field value based on label

I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

```<code><label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</code>```

For normal scenario it will be just

```<code>$('#custcode_2').val($('#custcode_1').val());
</code>```

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

答:
You can wrap the elements in a span or div with a class and then use that as your scope.</p>

```<code><span class="custWrapper">
<label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</span>

$('.custWrapper').on('load', function(){
    var inpts = $(this).find('input');

    $(inpts[1]).val($(inpts[0]).val());
});
</code>```

Body:
I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

Code
<input type="text" value="1234"  id="custcode_1" />

Copy Code
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

Body:
You can wrap the elements in a span or div with a class and then use that as your scope.

<span class="custWrapper">
<label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</span>

$('.custWrapper').on('load', function(){
    var inpts = $(this).find('input');

    $(inpts[1]).val($(inpts[0]).val());
});


问:
How to put multiple images control in array or list in c#?
I have 60 images control of . I have two requirements:

put all images control in array

I have an roll no of 6 digits. and I want to match first digit to index of first 10 Images control, then 2nd digit to next 10 images and so on...
following is my code:

```<code>protected void Page_Load(object sender, EventArgs e)
{
        //for roll no
        int rollNo = int.Parse(Request.QueryString["RollNo"]);
        var rollNoArray = rollNo.ToString().Select(t =>
           int.Parse(t.ToString())).ToArray();
        int index1=0;
            int index2=0, index3=0, index4 = 0
            ,index5 = 0, index6 = 0;
        for (int i = 0; i < rollNoArray.Length; i++)
        {
            //Response.Write(rollNoArray[i]+"<br>");
            LBLRollNo.Text += "   " +
            rollNoArray[i].ToString();
            if (i == 0)
            {
                index1 = rollNoArray[0];
            }
            if (i == 1)
            {
                index2 = rollNoArray[1];
            }
            if (i == 2)
            {
                index3 = rollNoArray[2];
            }
            if (i == 3)
            {
                index4 = rollNoArray[3];
            }
            if (i == 4)
            {
                index5 = rollNoArray[4];
            }
            if (i == 5)
            {
                index6 = rollNoArray[5];
            }
        }
        Response.Write(index1);

        //index
        matchBubbles(index1);
        }
     }
      public void matchBubbles(int index)
       {
        Image[] a =new Image[10];
        for (int i = 0; i < 10; i++)
        {
            a[0] = Image0;
            a[1] = Image1;
            a[2] = Image2;
            a[3] = Image3;
            a[4] = Image4;
            a[5] = Image5;
            a[6] = Image6;
            a[7] = Image7;
            a[8] = Image8;
            a[9] = Image9;

            if (index == a[i])
            {

            }
        }
}
</code>```

I want to manipulate the psd file in a way that Whatever rollno is return from previous .aspx page an image(in my folder) should be inserted in the exact place against the index of the roll no means there is 10 boxes below for every digit and I want to insert the image there according to each digit of the roll no. Please help me!
Help me Please

答:
In such case, you can do it simple way.

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Check Roll No query string cannot be null
            if (Request["RollNo"] != null)
            {
                //Check Roll No cannot exeed 6 digits
                if (Request["RollNo"].Length <= 6)
                {
                    string RollNo = Request["RollNo"];

                    //Check Roll No. must be all digits
                    int iRollNo;
                    if (Int32.TryParse(RollNo, out iRollNo))
                    {
                        //Prefix with zero for RollNo less than 6 digits
                        if (RollNo.Length < 6)
                        {
                            RollNo = new String('0', 6 - RollNo.Length) + RollNo;
                        }

                        //Display 6 images
                        Image1.ImageUrl = "~/Number/" + RollNo[0] + ".png";
                        Image2.ImageUrl = "~/Number/" + RollNo[1] + ".png";
                        Image3.ImageUrl = "~/Number/" + RollNo[2] + ".png";
                        Image4.ImageUrl = "~/Number/" + RollNo[3] + ".png";
                        Image5.ImageUrl = "~/Number/" + RollNo[4] + ".png";
                        Image6.ImageUrl = "~/Number/" + RollNo[5] + ".png";
                    }
                }
            }
        }
    }
</code>```

Result

if RollNo. not all digits or more than 6 digits, not display
if RollNo. less than 6 digits, prefix with zero

Body:
I have 60 images control of . I have two requirements:

put all images control in array

I have an roll no of 6 digits. and I want to match first digit to index of first 10 Images control, then 2nd digit to next 10 images and so on...
following is my code:

protected void Page_Load(object sender, EventArgs e)
{
        //for roll no
        int rollNo = int.Parse(Request.QueryString["RollNo"]);
        var rollNoArray = rollNo.ToString().Select(t =>
           int.Parse(t.ToString())).ToArray();
        int index1=0;
            int index2=0, index3=0, index4 = 0
            ,index5 = 0, index6 = 0;
        for (int i = 0; i < rollNoArray.Length; i++)
        {
            //Response.Write(rollNoArray[i]+"
");
            LBLRollNo.Text += "   " +
            rollNoArray[i].ToString();
            if (i == 0)
            {
                index1 = rollNoArray[0];
            }
            if (i == 1)
            {
                index2 = rollNoArray[1];
            }
            if (i == 2)
            {
                index3 = rollNoArray[2];
            }
            if (i == 3)
            {
                index4 = rollNoArray[3];
            }
            if (i == 4)
            {
                index5 = rollNoArray[4];
            }
            if (i == 5)
            {
                index6 = rollNoArray[5];
            }
        }
        Response.Write(index1);

        //index
        matchBubbles(index1);
        }
     }
      public void matchBubbles(int index)
       {
        Image[] a =new Image[10];
        for (int i = 0; i < 10; i++)
        {
            a[0] = Image0;
            a[1] = Image1;
            a[2] = Image2;
            a[3] = Image3;
            a[4] = Image4;
            a[5] = Image5;
            a[6] = Image6;
            a[7] = Image7;
            a[8] = Image8;
            a[9] = Image9;

            if (index == a[i])
            {

            }
        }
}

I want to manipulate the psd file in a way that Whatever rollno is return from previous .aspx page an image(in my folder) should be inserted in the exact place against the index of the roll no means there is 10 boxes below for every digit and I want to insert the image there according to each digit of the roll no. Please help me!
Help me Please

Body:
In such case, you can do it simple way.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Check Roll No query string cannot be null
            if (Request["RollNo"] != null)
            {
                //Check Roll No cannot exeed 6 digits
                if (Request["RollNo"].Length <= 6)
                {
                    string RollNo = Request["RollNo"];

                    //Check Roll No. must be all digits
                    int iRollNo;
                    if (Int32.TryParse(RollNo, out iRollNo))
                    {
                        //Prefix with zero for RollNo less than 6 digits
                        if (RollNo.Length < 6)
                        {
                            RollNo = new String('0', 6 - RollNo.Length) + RollNo;
                        }

                        //Display 6 images
                        Image1.ImageUrl = "~/Number/" + RollNo[0] + ".png";
                        Image2.ImageUrl = "~/Number/" + RollNo[1] + ".png";
                        Image3.ImageUrl = "~/Number/" + RollNo[2] + ".png";
                        Image4.ImageUrl = "~/Number/" + RollNo[3] + ".png";
                        Image5.ImageUrl = "~/Number/" + RollNo[4] + ".png";
                        Image6.ImageUrl = "~/Number/" + RollNo[5] + ".png";
                    }
                }
            }
        }
    }

Result

if RollNo. not all digits or more than 6 digits, not display
if RollNo. less than 6 digits, prefix with zero


问:
Objective C: Passing variables between classes
I want to pass an NSMutableDictionary from one class through a timer to another class that is called from the timer. I get an error at @selector([generateStickFig:enemies]) I've tried taking [] out but it still errs.

```<code>-(void)awakeFromNib {

//start timer that fires every second
NSMutableDictionary *enemies = [[NSMutableDictionary alloc] init];
[NSTimer scheduledTimerWithTimeInterval:(0.001) target:self selector:@selector([generateStickFig:enemies]) userInfo:nil repeats:YES];

}

-(void) generateStickFig:(NSMutableDictionary *)enemies {

int x = random() % 1000;

if (x == 1) {
    stickFig = [[UIButton alloc] initWithFrame:CGRectMake(0, 650, 50, 50)];
    [stickFig setBackgroundColor:[UIColor blackColor]];
    [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
    [enemies setObject:object forKey:[NSString stringWithFormat:@"object%i",i]];
    [self.view addSubview:stickFig];
}
}
</code>```

Any suggestions?

答:
Try

```<code>[NSTimer scheduledTimerWithTimeInterval:(0.001) target:self selector:@selector(generateStickFig:) userInfo:enemies repeats:YES];
</code>```

to create the timer. Then change the callback method to

```<code>-(void) generateStickFig:(NSTimer *)timer {
NSDictionary *enemies = (NSDictionary *)timer.userInfo;
    ...
}
</code>```

Body:
I want to pass an NSMutableDictionary from one class through a timer to another class that is called from the timer. I get an error at @selector([generateStickFig:enemies]) I've tried taking [] out but it still errs.

-(void)awakeFromNib {

//start timer that fires every second
NSMutableDictionary *enemies = [[NSMutableDictionary alloc] init];
[NSTimer scheduledTimerWithTimeInterval:(0.001) target:self selector:@selector([generateStickFig:enemies]) userInfo:nil repeats:YES];

}

-(void) generateStickFig:(NSMutableDictionary *)enemies {

int x = random() % 1000;

if (x == 1) {
    stickFig = [[UIButton alloc] initWithFrame:CGRectMake(0, 650, 50, 50)];
    [stickFig setBackgroundColor:[UIColor blackColor]];
    [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
    [enemies setObject:object forKey:[NSString stringWithFormat:@"object%i",i]];
    [self.view addSubview:stickFig];
}
}

Any suggestions?

Body:
Try

[NSTimer scheduledTimerWithTimeInterval:(0.001) target:self selector:@selector(generateStickFig:) userInfo:enemies repeats:YES];

to create the timer. Then change the callback method to

-(void) generateStickFig:(NSTimer *)timer {
NSDictionary *enemies = (NSDictionary *)timer.userInfo;
    ...
}


问:
scanf prematurely terminating while loop (I think)
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?</p>

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

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }
</code>```

答:
Personally I like to use fflush while under Windows

```<code>fflush(stdin);               //-- clear the input buffer
scanf("%c", &response );
</code>```

or fseek under Linux environments.

```<code>fseek(stdin,0,SEEK_END);    //-- prepare the input buffer to allow fresh data from the keyboard
scanf("%c", &response );
</code>```

Body:
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?

    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }

Body:
Personally I like to use fflush while under Windows

fflush(stdin);               //-- clear the input buffer
scanf("%c", &response );

or fseek under Linux environments.

fseek(stdin,0,SEEK_END);    //-- prepare the input buffer to allow fresh data from the keyboard
scanf("%c", &response );


问:
i use use multiple query it not display the correct information
```<code>include "connect_db.php";
$sql = "SELECT
COUNT(*) AS numberOfRows,value,cf7_id,data_id,name,created

FROM
wp_cf7_data, wp_cf7_data_entry

WHERE
wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'";

$query = mysqli_query($conn, $sql);
?>
<table width="600" border="1">
  <tr>
    <th width="91"> <div align="center">id </div></th>
    <th width="98"> <div align="center">สร้างวันที่ </div></th>
    <th width="198"> <div align="center">cf7_id </div></th>
    <th width="97"> <div align="center">name </div></th>
    <th width="59"> <div align="center">value </div></th>

  </tr>
<?php
while($result=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>
  <tr>
    <td><div align="center"><?php echo $result["id"];?></div></td>
    <td><?php echo $result["created"];?></td>
    <td><?php echo $result["cf7_id"];?></td>
    <td><div align="center"><?php echo $result["name"];?></div></td>
    <td align="right"><?php echo $result["value"];?></td>

  </tr>
<?php
}
?>
</table
</code>```

>

count and detail in table it show now

why count show 12  but Table data is only one row.

img

Information was created between 2017-11-27 08:54:39 and 2017-12-03 08:54:39 There are more than 1 information.

sorry i'm not good english
thank you

答:
```<code>$query = "SELECT COUNT(*) AS numberOfRows
  FROM wp_cf7_data, wp_cf7_data_entry
  WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
  UNION
  SELECT count(*)
  FROM wp_cf7_data, wp_cf7_data_entry
  WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
</code>```

Body:
include "connect_db.php";
$sql = "SELECT
COUNT(*) AS numberOfRows,value,cf7_id,data_id,name,created

FROM
wp_cf7_data, wp_cf7_data_entry

WHERE
wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'";

$query = mysqli_query($conn, $sql);
?>

id

สร้างวันที่

cf7_id

name

value

<?php
while($result=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>

<?php echo $result["id"];?>

    <?php echo $result["created"];?>
    <?php echo $result["cf7_id"];?>

<?php echo $result["name"];?>

    <?php echo $result["value"];?>

<?php
}
?>
</table

>

count and detail in table it show now

why count show 12  but Table data is only one row.

img

Information was created between 2017-11-27 08:54:39 and 2017-12-03 08:54:39 There are more than 1 information.

sorry i'm not good english
thank you


问:
Parse a substring in Python using regular expression
I am trying to parse a substring using re.

From the string present in variable s,I would like to split the string present till the first !(the string stored in s has two !) and store it as a substring.From this substring(stored in variable result), I wish to parse another substring.

Here is the code,

```<code>import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#!'

Data={}

result = re.search('%s(.*)%s' % ('ec', '!'), s).group(1)
print result
ecNumber = re.search('%s(.*)%s' % ('Number*', '#kmValue*'), result).group(1)
Data["ecNumber"]=ecNumber
print Data
</code>```

The value corresponding to each tag present in the substring(example:ecNumber)  is stored in between * and # (example: *2.4.1.11#).I attempted to parse the value stored for the tag ecNumber in the first substring.
The output I obtain is

```<code>result='Number*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#'
{'ecNumber': '*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081'}
</code>```

The desired output is

```<code>result= 'ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
{'ecNumber': '2.4.1.11'}
</code>```

I would like to store each tag and its corresponding value.For example,

```<code>{'ecNumber': '2.4.1.11','kmValue':'0.021','kmValueMaximum':'1.25'}
</code>```

答:
You can try this:

```<code>import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
new_data = re.findall('(?<=^)[a-zA-Z]+(?=\*)|(?<=#)[a-zA-Z]+(?=\*)|(?<=\*)[-\d\.]+(?=#)', s)
final_data = dict([new_data[i:i+2] for i in range(0, len(new_data)-1, 2)])
</code>```

Output:

```<code>{'kmValue': '0.57', 'kmValueMaximum': '1.25', 'ecNumber': '2.4.1.11'}
</code>```

Body:
I am trying to parse a substring using re.

From the string present in variable s,I would like to split the string present till the first !(the string stored in s has two !) and store it as a substring.From this substring(stored in variable result), I wish to parse another substring.

Here is the code,

import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#!'

Data={}

result = re.search('%s(.*)%s' % ('ec', '!'), s).group(1)
print result
ecNumber = re.search('%s(.*)%s' % ('Number*', '#kmValue*'), result).group(1)
Data["ecNumber"]=ecNumber
print Data

The value corresponding to each tag present in the substring(example:ecNumber)  is stored in between * and # (example: *2.4.1.11#).I attempted to parse the value stored for the tag ecNumber in the first substring.
The output I obtain is

result='Number*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#'
{'ecNumber': '*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081'}

The desired output is

result= 'ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
{'ecNumber': '2.4.1.11'}

I would like to store each tag and its corresponding value.For example,

{'ecNumber': '2.4.1.11','kmValue':'0.021','kmValueMaximum':'1.25'}

Body:
You can try this:

import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
new_data = re.findall('(?<=^)[a-zA-Z]+(?=\*)|(?<=#)[a-zA-Z]+(?=\*)|(?<=\*)[-\d\.]+(?=#)', s)
final_data = dict([new_data[i:i+2] for i in range(0, len(new_data)-1, 2)])

Output:

{'kmValue': '0.57', 'kmValueMaximum': '1.25', 'ecNumber': '2.4.1.11'}


问:
Creating constructor for hashset and hashmap
I have the following data structures created..

```<code>private Scanner scan;
HashSet<String> hset = new HashSet<String>();
HashMap<String, ArrayList<Integer>> hmap = new HashMap<String, ArrayList<Integer>>();
ArrayList<Integer> myList = new ArrayList<Integer>();
</code>```

I am confused on how to create a constructor to initialize these. I have the scanner I am pretty sure but some help with the others would be great.

```<code>public SpellChecker(){
    scan = new Scanner(System.in);
    hset = new HashSet<String>();
    hmap = new HashMap<String, ArrayList<Integer>>();
    myList = new ArrayList<Integer>();

}
</code>```

答:
Based on your comments, you can define those variables as class member variables, so that you can use the variable in the scope that you want (with the right access modifier that is )</p>

```<code>public class SpellChecker {
    private Scanner scan;
    private HashSet<String> hset;
    private HashMap<String, ArrayList<Integer>> hmap;
    private ArrayList<Integer> myList;

    public SpellChecker(){
        scan = new Scanner(System.in);
        hset = new HashSet<String>();
        hmap = new HashMap<String, ArrayList<Integer>>();
        myList = new ArrayList<Integer>();
    }

}
</code>```

Body:
I have the following data structures created..

private Scanner scan;
HashSet<String> hset = new HashSet<String>();
HashMap<String, ArrayList<Integer>> hmap = new HashMap<String, ArrayList<Integer>>();
ArrayList<Integer> myList = new ArrayList<Integer>();

I am confused on how to create a constructor to initialize these. I have the scanner I am pretty sure but some help with the others would be great.

public SpellChecker(){
    scan = new Scanner(System.in);
    hset = new HashSet<String>();
    hmap = new HashMap<String, ArrayList<Integer>>();
    myList = new ArrayList<Integer>();

}

Body:
Based on your comments, you can define those variables as class member variables, so that you can use the variable in the scope that you want (with the right access modifier that is )

public class SpellChecker {
    private Scanner scan;
    private HashSet<String> hset;
    private HashMap<String, ArrayList<Integer>> hmap;
    private ArrayList<Integer> myList;

    public SpellChecker(){
        scan = new Scanner(System.in);
        hset = new HashSet<String>();
        hmap = new HashMap<String, ArrayList<Integer>>();
        myList = new ArrayList<Integer>();
    }

}


问:
spark Athena connector
I need to use Athena in spark but spark uses preparedStatement when using JDBC drivers and it gives me an exception
"com.amazonaws.athena.jdbc.NotImplementedException: Method Connection.prepareStatement is not yet implemented"

Can you please let me know how can I connect Athena in spark

答:
You can't directly connect Spark to Athena.  Athena is simply an implementation of Prestodb targeting s3.  Unlike Presto, Athena cannot target data on HDFS.

However, if you want to use Spark to query data in s3, then you are in luck with HUE, which will let you query data in s3 from Spark on Elastic Map Reduce (EMR).

See Also:
Developer Guide for Hadoop User Experience (HUE) on EMR.

Title: spark Athena connector