答:
Look at the objects in your links array:

```<code>[{"source": "0", "target": "1", "value": 1},...
//this is a string ---------^
</code>```

You don't have numbers here, just strings. For the force to work, you have to set the number of the source and the target.

A simple solution is coercing:

```<code>links.forEach(function(d) {
    d.source = +d.source;
    d.target = +d.target;
})
</code>```

Here is the resulting code:

var nodes = [{
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxxn"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}];
var links = [{
  "source": "0",
  "target": "1",
  "value": 1
}, {
  "source": "2",
  "target": "1",
  "value": 1
}, {
  "source": "3",
  "target": "1",
  "value": 1
}, {
  "source": "4",
  "target": "1",
  "value": 1
}, {
  "source": "5",
  "target": "1",
  "value": 1
}, {
  "source": "6",
  "target": "1",
  "value": 1
}, {
  "source": "7",
  "target": "1",
  "value": 1
}, {
  "source": "8",
  "target": "1",
  "value": 1
}, {
  "source": "9",
  "target": "1",
  "value": 1
}, {
  "source": "10",
  "target": "1",
  "value": 1
}, {
  "source": "11",
  "target": "1",
  "value": 1
}, {
  "source": "12",
  "target": "1",
  "value": 1
}, {
  "source": "13",
  "target": "1",
  "value": 1
}, {
  "source": "14",
  "target": "1",
  "value": 1
}, {
  "source": "1",
  "target": "15",
  "value": 1
}, {
  "source": "1",
  "target": "16",
  "value": 1
}, {
  "source": "1",
  "target": "17",
  "value": 1
}, {
  "source": "1",
  "target": "18",
  "value": 1
}, {
  "source": "1",
  "target": "19",
  "value": 1
}, {
  "source": "1",
  "target": "20",
  "value": 1
}, {
  "source": "1",
  "target": "21",
  "value": 1
}, {
  "source": "1",
  "target": "22",
  "value": 1
}, {
  "source": "1",
  "target": "23",
  "value": 1
}, {
  "source": "1",
  "target": "24",
  "value": 1
}, {
  "source": "1",
  "target": "25",
  "value": 1
}, {
  "source": "1",
  "target": "26",
  "value": 1
}, {
  "source": "1",
  "target": "27",
  "value": 1
}, {
  "source": "1",
  "target": "28",
  "value": 1
}, {
  "source": "1",
  "target": "29",
  "value": 1
}, {
  "source": "1",
  "target": "30",
  "value": 1
}, {
  "source": "1",
  "target": "31",
  "value": 1
}, {
  "source": "1",
  "target": "32",
  "value": 1
}, {
  "source": "1",
  "target": "33",
  "value": 1
}, {
  "source": "1",
  "target": "34",
  "value": 1
}, {
  "source": "1",
  "target": "35",
  "value": 1
}, {
  "source": "1",
  "target": "36",
  "value": 1
}];
links.forEach(function(d) {
  d.source = +d.source;
  d.target = +d.target;
})
var width = 400,
  height = 400;
var svg = d3.select('body').append('svg')
  .attr('width', width)
  .attr('height', height);

var force = d3.layout.force()
  .size([width, height])
  .nodes(nodes)
  .links(links);

force.linkDistance(width / 2);

var link = svg.selectAll('.link')
  .data(links)
  .enter().append('line')
  .attr('class', 'link');

var node = svg.selectAll('.node')
  .data(nodes)
  .enter().append('circle')
  .attr('class', 'node');

force.on("start", function(){
  svg.append("text")
    .attr("class", "text")
    .attr("x", 150)
    .attr("y", 80)
    .text("Calculating...");
});

force.on('end', function() {
  svg.select(".text").remove();
  node.attr('r', width / 25)
    .attr('cx', function(d) {
      return d.x;
    })
    .attr('cy', function(d) {
      return d.y;
    });
  link.attr('x1', function(d) {
      return d.source.x;
    })
    .attr('y1', function(d) {
      return d.source.y;
    })
    .attr('x2', function(d) {
      return d.target.x;
    })
    .attr('y2', function(d) {
      return d.target.y;
    });

});
force.start();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://d3js.org/d3.v3.min.js'></script></code>```

EDIT: Since you're using .on("end" to paint your nodes, you'll have to wait until the force finishes.

Title: D3 force directed uncaught type error

Body:
I am trying to generate a D3 force direct graph based on the code here. I generated the following script:

(the xxxs are actual names).  It is throwing "Uncaught TypeError: Cannot read property 'push' of undefined".  I read in another thread that this can be caused if the nodes are improperly numbered, but I am numbering the nodes from zero and as far as I can tell there are no nodes in links that don't exist in nodes. Can anyone tell me what's wrong?

Body:
Look at the objects in your links array:

[{"source": "0", "target": "1", "value": 1},...
//this is a string ---------^

You don't have numbers here, just strings. For the force to work, you have to set the number of the source and the target.

A simple solution is coercing:

links.forEach(function(d) {
    d.source = +d.source;
    d.target = +d.target;
})

Here is the resulting code:

var nodes = [{
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxxn"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}, {
  "name": "xxx"
}];
var links = [{
  "source": "0",
  "target": "1",
  "value": 1
}, {
  "source": "2",
  "target": "1",
  "value": 1
}, {
  "source": "3",
  "target": "1",
  "value": 1
}, {
  "source": "4",
  "target": "1",
  "value": 1
}, {
  "source": "5",
  "target": "1",
  "value": 1
}, {
  "source": "6",
  "target": "1",
  "value": 1
}, {
  "source": "7",
  "target": "1",
  "value": 1
}, {
  "source": "8",
  "target": "1",
  "value": 1
}, {
  "source": "9",
  "target": "1",
  "value": 1
}, {
  "source": "10",
  "target": "1",
  "value": 1
}, {
  "source": "11",
  "target": "1",
  "value": 1
}, {
  "source": "12",
  "target": "1",
  "value": 1
}, {
  "source": "13",
  "target": "1",
  "value": 1
}, {
  "source": "14",
  "target": "1",
  "value": 1
}, {
  "source": "1",
  "target": "15",
  "value": 1
}, {
  "source": "1",
  "target": "16",
  "value": 1
}, {
  "source": "1",
  "target": "17",
  "value": 1
}, {
  "source": "1",
  "target": "18",
  "value": 1
}, {
  "source": "1",
  "target": "19",
  "value": 1
}, {
  "source": "1",
  "target": "20",
  "value": 1
}, {
  "source": "1",
  "target": "21",
  "value": 1
}, {
  "source": "1",
  "target": "22",
  "value": 1
}, {
  "source": "1",
  "target": "23",
  "value": 1
}, {
  "source": "1",
  "target": "24",
  "value": 1
}, {
  "source": "1",
  "target": "25",
  "value": 1
}, {
  "source": "1",
  "target": "26",
  "value": 1
}, {
  "source": "1",
  "target": "27",
  "value": 1
}, {
  "source": "1",
  "target": "28",
  "value": 1
}, {
  "source": "1",
  "target": "29",
  "value": 1
}, {
  "source": "1",
  "target": "30",
  "value": 1
}, {
  "source": "1",
  "target": "31",
  "value": 1
}, {
  "source": "1",
  "target": "32",
  "value": 1
}, {
  "source": "1",
  "target": "33",
  "value": 1
}, {
  "source": "1",
  "target": "34",
  "value": 1
}, {
  "source": "1",
  "target": "35",
  "value": 1
}, {
  "source": "1",
  "target": "36",
  "value": 1
}];
links.forEach(function(d) {
  d.source = +d.source;
  d.target = +d.target;
})
var width = 400,
  height = 400;
var svg = d3.select('body').append('svg')
  .attr('width', width)
  .attr('height', height);

var force = d3.layout.force()
  .size([width, height])
  .nodes(nodes)
  .links(links);

force.linkDistance(width / 2);

var link = svg.selectAll('.link')
  .data(links)
  .enter().append('line')
  .attr('class', 'link');

var node = svg.selectAll('.node')
  .data(nodes)
  .enter().append('circle')
  .attr('class', 'node');

force.on("start", function(){
  svg.append("text")
    .attr("class", "text")
    .attr("x", 150)
    .attr("y", 80)
    .text("Calculating...");
});

force.on('end', function() {
  svg.select(".text").remove();
  node.attr('r', width / 25)
    .attr('cx', function(d) {
      return d.x;
    })
    .attr('cy', function(d) {
      return d.y;
    });
  link.attr('x1', function(d) {
      return d.source.x;
    })
    .attr('y1', function(d) {
      return d.source.y;
    })
    .attr('x2', function(d) {
      return d.target.x;
    })
    .attr('y2', function(d) {
      return d.target.y;
    });

});
force.start();

<script src='https://d3js.org/d3.v3.min.js'></script>

EDIT: Since you're using .on("end" to paint your nodes, you'll have to wait until the force finishes.


来源: stackexchange

问:
FilmPass in three.js not working
So I am currently just trying to prototype the FilmPass effect in three.js and no matter what I try, I keep receiving the same error messages. I have been on a ton of different websites and I keep coming up with problems.

Here is the code I am using:

```<code><script src="three.min.js"></script>

    <script src="CopyShader.js"></script>
    <script src="DotScreenShader.js"></script>
    <script src="RGBShiftShader.js"></script>
    <script src="FilmShader.js"></script>
    <script src="FilmPass.js"></script>

    <script src="EffectComposer.js"></script>
    <script src="RenderPass.js"></script>
    <script src="MaskPass.js"></script>
    <script src="ShaderPass.js"></script>

    <script>

        var camera, scene, renderer, composer;
        var object, light;

        init();
        animate();

        function init() {

            renderer = new THREE.WebGLRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            var composer = new THREE.EffectComposer(renderer);

            //

            camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
            camera.position.z = 400;

            scene = new THREE.Scene();
            scene.fog = new THREE.Fog( 0x000000, 1, 1000 );

            object = new THREE.Object3D();
            scene.add( object );

            var geometry = new THREE.SphereGeometry( 1, 4, 4 );
            var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );

            for ( var i = 0; i < 100; i ++ ) {

                var mesh = new THREE.Mesh( geometry, material );
                mesh.position.set( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize();
                mesh.position.multiplyScalar( Math.random() * 400 );
                mesh.rotation.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 );
                mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50;
                object.add( mesh );

            }

            scene.add( new THREE.AmbientLight( 0x222222 ) );

            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( 1, 1, 1 );
            scene.add( light );

            // postprocessing

            composer = new THREE.EffectComposer( renderer );
            // composer.addPass( new THREE.RenderPass( scene, camera ) );
            //
            // var effect = new THREE.ShaderPass( THREE.DotScreenShader );
            // effect.uniforms[ 'scale' ].value = 4;
            // composer.addPass( effect );
            //
            // var effect = new THREE.ShaderPass( THREE.RGBShiftShader );
            // effect.uniforms[ 'amount' ].value = 0.0015;
            // effect.renderToScreen = true;
            // composer.addPass( effect );

            var renderPass = new THREE.RenderPass(scene, camera);
            composer.addPass(renderPass);

            var effectFilm = new THREE.FilmPass();
            effectFilm.renderToScreen = true;
            composer.addPass(effectFilm);

            var clock = new THREE.Clock()

            function render() {
                var delta = clock.getDelta();
                composer.render(delta); //parameter must be set with render
                requestAnimationFrame(render);
            }
            render();
            //

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );
            composer.setSize( window.innerWidth, window.innerHeight );

        }

        function animate() {

            requestAnimationFrame( animate );

            object.rotation.x += 0.005;
            object.rotation.y += 0.01;

        //  composer.render();

        }

    </script>

</body>
</code>```

Here are the error messages I am getting:

答:
The offending line 38 contains a reference to THREE.Pass.prototype which is not defined yet. THREE.Pass is defined in EffectComposer.js, so you need to put that higher up in your scripts.

```<code><script src="EffectComposer.js"></script> <!-- ADD HERE -->
<script src="CopyShader.js"></script>
<script src="DotScreenShader.js"></script>
<script src="RGBShiftShader.js"></script>
<script src="FilmShader.js"></script>
<script src="FilmPass.js"></script>

<!-- <script src="EffectComposer.js"></script> REMOVE HERE -->
<script src="RenderPass.js"></script>
<script src="MaskPass.js"></script>
<script src="ShaderPass.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Title: FilmPass in three.js not working

Body:
So I am currently just trying to prototype the FilmPass effect in three.js and no matter what I try, I keep receiving the same error messages. I have been on a ton of different websites and I keep coming up with problems.

Here is the code I am using:

Here are the error messages I am getting:

Body:
The offending line 38 contains a reference to THREE.Pass.prototype which is not defined yet. THREE.Pass is defined in EffectComposer.js, so you need to put that higher up in your scripts.

<script src="EffectComposer.js"></script> <!-- ADD HERE -->
<script src="CopyShader.js"></script>
<script src="DotScreenShader.js"></script>
<script src="RGBShiftShader.js"></script>
<script src="FilmShader.js"></script>
<script src="FilmPass.js"></script>

<!-- <script src="EffectComposer.js"></script> REMOVE HERE -->
<script src="RenderPass.js"></script>
<script src="MaskPass.js"></script>
<script src="ShaderPass.js"></script>


问:
Changing the location of the busyIndicator when using ShinySky for Shiny?
Running this snippet of code allows you to see an example of all the goodies that ShinySky offers:

```<code>if (require(devtools)) install.packages("devtools")#if not alrady installed
devtools::install_github("AnalytixWare/ShinySky")
library(shinysky)
shinysky::run.shinysky.example()
</code>```

Of these, I'm trying to use the busyIndicator.

Unfortunately, the default position (i.e., in the middle of the app) of the image doesn't work for me. For some reason, the busyIndicator is being obscured and covered up by my ggplots.

I looked at the arguments for the busyIndicator and it looks like the only levers we have to play with are

```<code>text
img
wait
</code>```

Of which I've played with and aren't relevant.

The ideal situation would be to simply move up it a few inches or so. Does anyone have any advice? Thanks.

答:
You can use css.  A high z-index should put it in front of your plots. </p>

```<code>.shinysky-busy-indicator {
  z-index: 1000;
}
</code>```

Body:
Running this snippet of code allows you to see an example of all the goodies that ShinySky offers:

if (require(devtools)) install.packages("devtools")#if not alrady installed
devtools::install_github("AnalytixWare/ShinySky")
library(shinysky)
shinysky::run.shinysky.example()

Of these, I'm trying to use the busyIndicator.

Unfortunately, the default position (i.e., in the middle of the app) of the image doesn't work for me. For some reason, the busyIndicator is being obscured and covered up by my ggplots.

I looked at the arguments for the busyIndicator and it looks like the only levers we have to play with are

text
img
wait

Of which I've played with and aren't relevant.

The ideal situation would be to simply move up it a few inches or so. Does anyone have any advice? Thanks.

Body:
You can use css.  A high z-index should put it in front of your plots.

.shinysky-busy-indicator {
  z-index: 1000;
}


问:
How to serialize object array with a dictionary inside
I'm trying to serialize an object array which contains a dictionary as one of its values, and I'm getting  this run-time SerializationException:

```<code>Type 'System.Collections.Generic.Dictionary`2 ...with data contract name 'ArrayOfKeyValueOfstringanyType
is not expected. Consider using a DataContractResolver if you are using
DataContractSerializer or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to the serializer.
</code>```

This is how I'm trying to accomplish the task:

```<code>        object[] taskArgs = new object[] { 1, 2 };
        IDictionary<string, object> kwargs = new Dictionary<string, object>();
        IDictionary<string, object> embed = new Dictionary<string, object>();
        embed.Add("callbacks", null);
        embed.Add("errbacks", null);
        embed.Add("chain", null);
        embed.Add("chord", null);

        var knownTypes = new List<Type> { typeof(IDictionary<string, object>), typeof(object []), typeof(List<string>) };
        //object[] arguments = new object[] { taskArgs, "{}", "{}"  };
        object[] arguments = new object[] { taskArgs, kwargs, embed };

        MemoryStream stream1 = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(object[]), knownTypes);
        ser.WriteObject(stream1, arguments);
        stream1.Position = 0;
        StreamReader sr = new StreamReader(stream1);
        string message = sr.ReadToEnd();
</code>```

Even though I've tried to add typeof(IDictionary<string, object>) to knownTypes, it won't work.

答:
You must use the concrete type typeof(Dictionary<string, object>) instead of the interface type typeof(IDictionary<string, object>) for a known type:

```<code>var knownTypes = new List<Type> { typeof(Dictionary<string, object>), typeof(object[]), typeof(List<string>) };
</code>```

A type in the list of known types much match the exact type (as returned by GetType()) of an object of otherwise unknown type to take effect.  Matching a base class type or implemented interface type is not sufficient, and in any event the data contract serializers do not support serializing interfaces.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to serialize an object array which contains a dictionary as one of its values, and I'm getting  this run-time SerializationException:

Type 'System.Collections.Generic.Dictionary`2 ...with data contract name 'ArrayOfKeyValueOfstringanyType
is not expected. Consider using a DataContractResolver if you are using
DataContractSerializer or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to the serializer.

This is how I'm trying to accomplish the task:

        object[] taskArgs = new object[] { 1, 2 };
        IDictionary<string, object> kwargs = new Dictionary<string, object>();
        IDictionary<string, object> embed = new Dictionary<string, object>();
        embed.Add("callbacks", null);
        embed.Add("errbacks", null);
        embed.Add("chain", null);
        embed.Add("chord", null);

        var knownTypes = new List<Type> { typeof(IDictionary<string, object>), typeof(object []), typeof(List<string>) };
        //object[] arguments = new object[] { taskArgs, "{}", "{}"  };
        object[] arguments = new object[] { taskArgs, kwargs, embed };

        MemoryStream stream1 = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(object[]), knownTypes);
        ser.WriteObject(stream1, arguments);
        stream1.Position = 0;
        StreamReader sr = new StreamReader(stream1);
        string message = sr.ReadToEnd();

Even though I've tried to add typeof(IDictionary<string, object>) to knownTypes, it won't work.

Body:
You must use the concrete type typeof(Dictionary<string, object>) instead of the interface type typeof(IDictionary<string, object>) for a known type:

var knownTypes = new List<Type> { typeof(Dictionary<string, object>), typeof(object[]), typeof(List<string>) };

A type in the list of known types much match the exact type (as returned by GetType()) of an object of otherwise unknown type to take effect.  Matching a base class type or implemented interface type is not sufficient, and in any event the data contract serializers do not support serializing interfaces.


问:
List with checkbox using LWUIT
I am using LWUIT for getting a search facility for selection in the List.
Now I want to know how can I display the list with CheckBoxes?

```<code>list=new List(vector);
cform.addComponent(list);
cform.addComponent(t);
cform.show();
</code>```

答:
I don't know if there is a more simple solution then mine, but mine is highly customizable and can serve for a lot of purposes.

```<code>List l = new List;

Vector v = new Vector();
for(int i = 0; i < 10; ++i){
   v.addElement(new CheckItem("itemtekst"));
}

l.setListCellRenderer(new CheckItemRenderer());
l.setModel(new CheckItemModel(v));
</code>```

the code above makes it work. As you can guess you have to make a new class and override two to make it work.

CHECKITEM: this class has a string and an image. as well as setters and getters. it also has a boolean that shows if it is checked or not.

CHECKITEMRENDERER: has a label for the string and the image of the checkitem it extends Container and implements ListCellRenderer

CHECKITEMMODEL: this extends the defaultlistmodel. it has methods to get the checkeditems and setthem checked or unchecked.

to recap:

set the correct items in the vector

set the correct renderer

set the correct model

and to use it add an actionlistener or it will al be for nothing.

Title: List with checkbox using LWUIT

Body:
I am using LWUIT for getting a search facility for selection in the List.
Now I want to know how can I display the list with CheckBoxes?

list=new List(vector);
cform.addComponent(list);
cform.addComponent(t);
cform.show();

Body:
I don't know if there is a more simple solution then mine, but mine is highly customizable and can serve for a lot of purposes.

List l = new List;

Vector v = new Vector();
for(int i = 0; i < 10; ++i){
   v.addElement(new CheckItem("itemtekst"));
}

l.setListCellRenderer(new CheckItemRenderer());
l.setModel(new CheckItemModel(v));

the code above makes it work. As you can guess you have to make a new class and override two to make it work.

CHECKITEM: this class has a string and an image. as well as setters and getters. it also has a boolean that shows if it is checked or not.

CHECKITEMRENDERER: has a label for the string and the image of the checkitem it extends Container and implements ListCellRenderer

CHECKITEMMODEL: this extends the defaultlistmodel. it has methods to get the checkeditems and setthem checked or unchecked.

to recap:

set the correct items in the vector

set the correct renderer

set the correct model

and to use it add an actionlistener or it will al be for nothing.

ContentLicense: CC BY-SA 2.5


问:
How can I create a DataGridView in a TabPage of 2nd from by clicking the button in the 1st Form
This is Form1:

```<code>private void Btn_Create_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(txt_LedgerName.Text);
    frm2.Show();
}
</code>```

And this is Form2:

```<code>public partial class Form2 : Form
{
    public Form2(string message)
    {
        InitializeComponent();
        TabPage tbpg = new TabPage();
        tbpg.Text = message;
        //var dlt = tabControl1.TabPages[0];
        //dlt.Hide();
        tabControl1.TabPages.Add(tbpg);
    }
}
</code>```

答:
You can use this to add a control to a tabPage on Form2 from Form1.

On Form2 create a function:

```<code>// Adds a control to an existing tab page # or creates a new page if it doesn't exist
// The value returned will be the actual page number which may not match
// the requested page number.
public int AddControl(int tabPage, Control control)
{
    TabPage tbpg;
    if (tabControl1.TabPages.Count <= tabPage)
        tbpg = tabControl1.TabPages[tabPage];
    else
    {
        tbpg = new TabPage();
        tabControl1.TabPages.Add(tbpg);
    }
    tbpg.controls.Add(control);
    return tabcontrol1.TabPages.IndexOf(tbpg);
}
</code>```

Body:
This is Form1:

private void Btn_Create_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(txt_LedgerName.Text);
    frm2.Show();
}

And this is Form2:

public partial class Form2 : Form
{
    public Form2(string message)
    {
        InitializeComponent();
        TabPage tbpg = new TabPage();
        tbpg.Text = message;
        //var dlt = tabControl1.TabPages[0];
        //dlt.Hide();
        tabControl1.TabPages.Add(tbpg);
    }
}

Body:
You can use this to add a control to a tabPage on Form2 from Form1.

On Form2 create a function:

// Adds a control to an existing tab page # or creates a new page if it doesn't exist
// The value returned will be the actual page number which may not match
// the requested page number.
public int AddControl(int tabPage, Control control)
{
    TabPage tbpg;
    if (tabControl1.TabPages.Count <= tabPage)
        tbpg = tabControl1.TabPages[tabPage];
    else
    {
        tbpg = new TabPage();
        tabControl1.TabPages.Add(tbpg);
    }
    tbpg.controls.Add(control);
    return tabcontrol1.TabPages.IndexOf(tbpg);
}


问:
Heatmap colors not working in plotly
I'm trying to print out a grid of heatmaps using plotly for R in Shiny. I want to give them a custom color scale, but it's not behaving how I want it to. When I use the colors= option when building my plotly chart, it seems to use the distribution of values, rather than the zmin and zmax that I gave it to assign colors.

In my example code below, you can see that I give each plot the same colorscale (colorScale) using the colors= option. This works how I expect when I have a well distributed set of data, as in the first, second, and fourth row of plots.

However, in the third row, where the plots have very skewed data, you can see that the scales look different than everything else - they have the blue and red, but skip over the white in the middle, instead having purple.

In my actual code, this is causing a big problem for a chart that has a lot of values around the middle, with some extremes on either end - I want those values in the middle to appear white, to show that there was no change, but instead they are purple, making it harder to pick out the important values (the extreme ones).

Is there a way to force the color assignment to behave how I want it to?

Thanks,
Cliff

server.R

```<code>if (!require("pacman")) install.packages("pacman")

pacman::p_load(shiny,data.table,plotly)

colorScale <- colorRamp(c("darkblue","cornflowerblue","white","sandybrown","firebrick"))

nCodeNames <- c("a","b","c","d","e","f","g","h","i","j","k","l")
means = c(rnorm(600,0,2.5),runif(600,-5,5),runif(130,-4,-3.9),runif(70,4.5,5),rnorm(150,-3),rnorm(50,4),rnorm(180,-2.5),runif(20,4.93,4.98),runif(300,-4,3),rnorm(300,3.5))

dt <- data.table(age=rep(rep(c(11:20),times=20),times=12),composite=rep(rep(c(81:100),each=10),times=12),mean=means,n_code=rep(nCodeNames,each=200))

sub<-dt[n_code=="a"]

shinyServer(function(input, output) {

for(Ncode in nCodeNames){
  local({
    ncode = Ncode
    output[[paste0("grid",ncode)]] <- renderPlotly({
      sub <- dt[n_code == ncode]
      p <- plot_ly(data=sub, x=~age, y=~composite, z=~mean, type="heatmap", zmin=-5,zmax=5,
                   colors = colorScale, colorbar=list(thickness="15"))%>%
           layout(title=ncode,xaxis=list(type="category",tickvals=c(11,15,20)),yaxis=list(title="",ticks=""))
    })
  })
}
})
</code>```

ui.R

```<code>if (!require("pacman")) install.packages("pacman")

pacman::p_load(shiny, plotly)

nCodeNames <- c("a","b","c","d","e","f","g","h","i","j","k","l")

shinyUI(navbarPage(
  "E-N Matrics: Proportion of E-Code Resulting in each N-Code",

  tabPanel("Grid",

            lapply(c(1:4), function(i) fluidRow(
              lapply(c(1:3), function(j) column(4, plotlyOutput(paste0("grid",nCodeNames[(i-1)*3+j]))))
             ))

           #fluidRow(column(4,plotlyOutput(paste0("grid",nCodeNames[(1-1)*3+1]))),column(4,plotly))
  )
  ))
</code>```

答:
I encountered similar issues with the colorscale in R plotly heatmap. When the data for the z argument has screwed distribution, only a few colors specified in the colorscale are used by plotly.

I found a work-around solution by creating a new variable according to the quantiles of the original variable, and pass it to the z argument. Here is the R code for the general idea. You will need to customize it to make it work for a specific problem.

```<code>library(plotly)
library(RColorBrewer)

# create a dataframe where z has a skewed distribution
set.seed(1)
df = data.frame(x = rep(1:50, 20) , y = rep(1:20,each =50), z = rgamma(1000, 2, 0.5))

# check distribution of z
plot_ly(data = df, x = ~z, type = "histogram")%>%
    layout(title = "histogram of z")

# original heatmap
# pass the column z with screwed distribution to z argument
plot_ly(data=df, x=~x, y=~y, z=~z, type="heatmap",
        colors = "Spectral") %>%
    layout(title = "original heatmap")

# some data processing work

# find unique quantiles of z
quantiles = unique(quantile(df$z, seq(0,1,0.1)))

# create a dummy column z1 of discrete values using the quantiles as cut off
# the ideas is to arrage the data to subgroups of roughly the same size
df$z1= cut(df$z, breaks =  c(quantiles[1]-1,quantiles[-1]), right = TRUE, labels = FALSE)

# check distribution of z1
plot_ly(data = df, x = ~z1, type = "histogram")%>%
    layout(title = "histogram of z1")

# new heatmap
# passes the new column z1 to z argument
plot_ly(data=df, x=~x, y=~y, z=~z1, type="heatmap",
        # make sure hovering over displays original z
        text =~z, hoverinfo = "text",
        # use the color palettes from RColorBrewer,
        # or your customized colorscale
        colors = "Spectral",
        # map the label of the colorbar back to the quantiles
        colorbar=list(tickmode="array", tickvals = 1:(length(quantiles)-1), ticktext = round(quantiles,2)[-1], title = "z")) %>%
layout(title = "new heat map")
</code>```

Below are the original heatmap and the new heatmap generated by plotly. The new heatmap uses more colors from "Spectral" palette to differetiate between smaller values.

Hope this helps!

Update on April 3,2017

I opened a request on the R plotly repository for capability to transform the color scale.

https://github.com/ropensci/plotly/issues/920

Title: Heatmap colors not working in plotly

Body:
I'm trying to print out a grid of heatmaps using plotly for R in Shiny. I want to give them a custom color scale, but it's not behaving how I want it to. When I use the colors= option when building my plotly chart, it seems to use the distribution of values, rather than the zmin and zmax that I gave it to assign colors.

In my example code below, you can see that I give each plot the same colorscale (colorScale) using the colors= option. This works how I expect when I have a well distributed set of data, as in the first, second, and fourth row of plots.

However, in the third row, where the plots have very skewed data, you can see that the scales look different than everything else - they have the blue and red, but skip over the white in the middle, instead having purple.

In my actual code, this is causing a big problem for a chart that has a lot of values around the middle, with some extremes on either end - I want those values in the middle to appear white, to show that there was no change, but instead they are purple, making it harder to pick out the important values (the extreme ones).

Is there a way to force the color assignment to behave how I want it to?

Thanks,
Cliff

server.R

if (!require("pacman")) install.packages("pacman")

pacman::p_load(shiny,data.table,plotly)

colorScale <- colorRamp(c("darkblue","cornflowerblue","white","sandybrown","firebrick"))

nCodeNames <- c("a","b","c","d","e","f","g","h","i","j","k","l")
means = c(rnorm(600,0,2.5),runif(600,-5,5),runif(130,-4,-3.9),runif(70,4.5,5),rnorm(150,-3),rnorm(50,4),rnorm(180,-2.5),runif(20,4.93,4.98),runif(300,-4,3),rnorm(300,3.5))

dt <- data.table(age=rep(rep(c(11:20),times=20),times=12),composite=rep(rep(c(81:100),each=10),times=12),mean=means,n_code=rep(nCodeNames,each=200))

sub<-dt[n_code=="a"]

shinyServer(function(input, output) {

for(Ncode in nCodeNames){
  local({
    ncode = Ncode
    output[[paste0("grid",ncode)]] <- renderPlotly({
      sub <- dt[n_code == ncode]
      p <- plot_ly(data=sub, x=~age, y=~composite, z=~mean, type="heatmap", zmin=-5,zmax=5,
                   colors = colorScale, colorbar=list(thickness="15"))%>%
           layout(title=ncode,xaxis=list(type="category",tickvals=c(11,15,20)),yaxis=list(title="",ticks=""))
    })
  })
}
})

ui.R

if (!require("pacman")) install.packages("pacman")

pacman::p_load(shiny, plotly)

nCodeNames <- c("a","b","c","d","e","f","g","h","i","j","k","l")

shinyUI(navbarPage(
  "E-N Matrics: Proportion of E-Code Resulting in each N-Code",

  tabPanel("Grid",

            lapply(c(1:4), function(i) fluidRow(
              lapply(c(1:3), function(j) column(4, plotlyOutput(paste0("grid",nCodeNames[(i-1)*3+j]))))
             ))

           #fluidRow(column(4,plotlyOutput(paste0("grid",nCodeNames[(1-1)*3+1]))),column(4,plotly))
  )
  ))

Body:
I encountered similar issues with the colorscale in R plotly heatmap. When the data for the z argument has screwed distribution, only a few colors specified in the colorscale are used by plotly.

I found a work-around solution by creating a new variable according to the quantiles of the original variable, and pass it to the z argument. Here is the R code for the general idea. You will need to customize it to make it work for a specific problem.

library(plotly)
library(RColorBrewer)

# create a dataframe where z has a skewed distribution
set.seed(1)
df = data.frame(x = rep(1:50, 20) , y = rep(1:20,each =50), z = rgamma(1000, 2, 0.5))

# check distribution of z
plot_ly(data = df, x = ~z, type = "histogram")%>%
    layout(title = "histogram of z")

# original heatmap
# pass the column z with screwed distribution to z argument
plot_ly(data=df, x=~x, y=~y, z=~z, type="heatmap",
        colors = "Spectral") %>%
    layout(title = "original heatmap")

# some data processing work

# find unique quantiles of z
quantiles = unique(quantile(df$z, seq(0,1,0.1)))

# create a dummy column z1 of discrete values using the quantiles as cut off
# the ideas is to arrage the data to subgroups of roughly the same size
df$z1= cut(df$z, breaks =  c(quantiles[1]-1,quantiles[-1]), right = TRUE, labels = FALSE)

# check distribution of z1
plot_ly(data = df, x = ~z1, type = "histogram")%>%
    layout(title = "histogram of z1")

# new heatmap
# passes the new column z1 to z argument
plot_ly(data=df, x=~x, y=~y, z=~z1, type="heatmap",
        # make sure hovering over displays original z
        text =~z, hoverinfo = "text",
        # use the color palettes from RColorBrewer,
        # or your customized colorscale
        colors = "Spectral",
        # map the label of the colorbar back to the quantiles
        colorbar=list(tickmode="array", tickvals = 1:(length(quantiles)-1), ticktext = round(quantiles,2)[-1], title = "z")) %>%
layout(title = "new heat map")

Below are the original heatmap and the new heatmap generated by plotly. The new heatmap uses more colors from "Spectral" palette to differetiate between smaller values.

Hope this helps!

Update on April 3,2017

I opened a request on the R plotly repository for capability to transform the color scale.

https://github.com/ropensci/plotly/issues/920


问:
How to highlight the transcript of a audio file?
Im beginner in javascript so I'm very sorry for my amateurish codes.
I have a audio and some text that is subtitles of it.
I have the timestamps of conversation.
for example the timestamp of "hi" in audio is "1.525487" sec.
I want to highlight the text "hi"  in that moment.

When I use a integer number for "span id" for example "ts1" it works correctly,
but when I use decimal number like "1.525487" it dose not work.
what should I do?

Thanks for your helps.

```<code><body>
<audio id = "adi" controls>
<source src="Greeting.mp3"></source>
</audio>

<div>
```
A: Hi , how are you doing?
```
</div>

<script>
var spns = document.getElementsByTagName("SPAN");
var audi = document.getElementById("adi");

audi.addEventListener("timeupdate", f1);
function f1(){
    var i;
    for (i = 0 ; i< spns.length ; i++){
        if(spns[i].id == "ts" + audi.currentTime){
            spns[i].style.backgroundColor = "red";
        }
    }
}
</script>
</body>
</code>```

答:
That's because you're not dealing with a exact number. Put a console.log(audi.currentTime) in the event and you'll see what I mean. You have to consider a time interval not an exact time value. Here, try this way:

```<code><body>
<audio id = "adi" controls>
<source src="Greetings.mp3"></source>
</audio>

<div>
```
A: Hi , how are you doing?
```
</div>

<script>
var spns = document.getElementsByTagName("SPAN");
var audi = document.getElementById("adi");

audi.addEventListener("timeupdate", f1);
function f1(){
    var i;
    for (i = 0 ; i< spns.length ; i++){
    var time = Number(spns[i].id.slice(2));
        if(time < audi.currentTime){
            if (i>0) spns[i -1].style.backgroundColor = "white";
            spns[i].style.backgroundColor = "red";
        }
    }
}
</script>
</body>
</code>```

Here's a running example:

var spns = document.getElementsByTagName("SPAN");
var audi = document.getElementById("adi");

audi.addEventListener("timeupdate", f1);
function f1(){
  var i;
  for (i = 0 ; i< spns.length ; i++){
    var time = Number(spns[i].id.slice(2));
    if(time < audi.currentTime){
      if (i>0) spns[i -1].style.backgroundColor = "white";
      spns[i].style.backgroundColor = "red";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id = "adi" controls>
<source src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3"></source>
</audio>

<div>
```
A: Hi , how are you doing?
```
</div></code>```

JSFiddle: https://jsfiddle.net/d1wryoak/2/

Edit

After you understand the above code, try to understand the one below. It's a more modern aproach to it.

var audi = document.getElementById("adi");
audi.addEventListener("timeupdate", ()=>{
    var setBackground = (elem, color)=>elem.style.backgroundColor = color,
        last = undefined;
    Array.from(document.getElementsByTagName("SPAN")).forEach((spn)=>{
        if (!(spn.id.slice(2) < audi.currentTime)) return;
        last && setBackground(last, "white");
        setBackground((last = spn), "red");
    });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id = "adi" controls>
<source src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3"></source>
</audio>

<div>
```
A: Hi , how are you doing?
```
</div></code>```

https://jsfiddle.net/d1wryoak/4/

Body:
Im beginner in javascript so I'm very sorry for my amateurish codes.
I have a audio and some text that is subtitles of it.
I have the timestamps of conversation.
for example the timestamp of "hi" in audio is "1.525487" sec.
I want to highlight the text "hi"  in that moment.

When I use a integer number for "span id" for example "ts1" it works correctly,
but when I use decimal number like "1.525487" it dose not work.
what should I do?

Thanks for your helps.

<audio id = "adi" controls>
<source src="Greeting.mp3"></source>
</audio>

A: Hi , how are you doing?

Body:
That's because you're not dealing with a exact number. Put a console.log(audi.currentTime) in the event and you'll see what I mean. You have to consider a time interval not an exact time value. Here, try this way:

<body>
<audio id = "adi" controls>
<source src="Greetings.mp3"></source>
</audio>

<div>
<pre>
A: <span id="ts3.525487">Hi</span> , <span id="ts5.193877">how are you doing?</span>
</pre>
</div>

<script>
var spns = document.getElementsByTagName("SPAN");
var audi = document.getElementById("adi");

audi.addEventListener("timeupdate", f1);
function f1(){
    var i;
    for (i = 0 ; i< spns.length ; i++){
    var time = Number(spns[i].id.slice(2));
        if(time < audi.currentTime){
            if (i>0) spns[i -1].style.backgroundColor = "white";
            spns[i].style.backgroundColor = "red";
        }
    }
}
</script>
</body>

Here's a running example:

var spns = document.getElementsByTagName("SPAN");
var audi = document.getElementById("adi");

audi.addEventListener("timeupdate", f1);
function f1(){
  var i;
  for (i = 0 ; i< spns.length ; i++){
    var time = Number(spns[i].id.slice(2));
    if(time < audi.currentTime){
      if (i>0) spns[i -1].style.backgroundColor = "white";
      spns[i].style.backgroundColor = "red";
    }
  }
}

<audio id = "adi" controls>
<source src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3"></source>
</audio>

<div>
<pre>
A: <span id="ts1.525487">Hi</span> , <span id="ts3.193877">how are you doing?</span>
</pre>
</div>

JSFiddle: https://jsfiddle.net/d1wryoak/2/

Edit

After you understand the above code, try to understand the one below. It's a more modern aproach to it.

var audi = document.getElementById("adi");
audi.addEventListener("timeupdate", ()=>{
    var setBackground = (elem, color)=>elem.style.backgroundColor = color,
        last = undefined;
    Array.from(document.getElementsByTagName("SPAN")).forEach((spn)=>{
        if (!(spn.id.slice(2) < audi.currentTime)) return;
        last && setBackground(last, "white");
        setBackground((last = spn), "red");
    });
})

<audio id = "adi" controls>
<source src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3"></source>
</audio>

<div>
<pre>
A: <span id="ts1.525487">Hi</span> , <span id="ts3.193877">how are you doing?</span>
</pre>
</div>

https://jsfiddle.net/d1wryoak/4/


问:
use createHash in angular-md5
When I wanna use the createHash function in angular, this error raises : md5.createHash is not a function

Here's my code :

```<code>MyCtrl.$inject = ['md5'];
function MyCtrl(md5) {
var vm = this;

vm.reg = reg;

function reg() {
    vm.avatar = md5.createHash('salam'); // This Line Has Error
    console.log(vm.avatar);
...
</code>```

Note: I added the module dependency fine !

答:
Not sure what happened, but you might be able to backtrack from a fiddle I made you

  <input type="text" ng-model="email" placeholder="Message Here"> {{ message }}

```

`

Title: use createHash in angular-md5

Body:
When I wanna use the createHash function in angular, this error raises : md5.createHash is not a function

Here's my code :

MyCtrl.$inject = ['md5'];
function MyCtrl(md5) {
var vm = this;

vm.reg = reg;

function reg() {
    vm.avatar = md5.createHash('salam'); // This Line Has Error
    console.log(vm.avatar);
...

Note: I added the module dependency fine !

Body:
Not sure what happened, but you might be able to backtrack from a fiddle I made you

<body ng-app="YOUR_APP" ng-controller="MainCtrl">
  <img src="http://www.gravatar.com/avatar/{{ email | gravatar }}.jpg?d=identicon">
  <input type="text" ng-model="email" placeholder="Message Here"> {{ message }}
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-md5/0.1.10/angular-md5.js"></script>
<script>
  var app = angular.module('YOUR_APP', [
    'angular-md5', // you may also use 'ngMd5' or 'gdi2290.md5'
  ]).controller('MainCtrl', function($scope, md5) {

    $scope.$watch('email', function(val) {
      $scope.message = 'Your message Hash is: ' + md5.createHash($scope.email || '');
    });

  });
</script>

`


问:
Can this mysql subquery be shortened with JOINs?
I am attempting to find all entries in the 'archive' table that have the same workID as any rows where historyID is NULL, worktype = "WEST", and the completeDate at least four months old. I am using a sub query to complete this request. Is there a more efficient way? My query is below.

```<code>SELECT * from archive b WHERE b.workID IN
(SELECT a.workID FROM archive a, worktypes t
WHERE a.historyID IS NULL AND (t.worktype IN ('WEST') AND a.worktype = t.id)
AND a.completeDate >= DATE(NOW() - Interval 4 month));
</code>```

Additional Info: The tables are related only by the worktype. Basically I'm using the worktypes table just so I can type 'WEST' instead of giving an id number so it's easier to understand the query at-a-glance. I added on to the query. I didn't copy and paste it all. Oops.

Thank you!

答:
The problem with your query and the proposed solution is that we don't know how the tables relate to each other. What column do you have in archive that is also in worktypes?

Also you should avoid "IN" where possible, it is inefficient.

Body:
I am attempting to find all entries in the 'archive' table that have the same workID as any rows where historyID is NULL, worktype = "WEST", and the completeDate at least four months old. I am using a sub query to complete this request. Is there a more efficient way? My query is below.

SELECT * from archive b WHERE b.workID IN
(SELECT a.workID FROM archive a, worktypes t
WHERE a.historyID IS NULL AND (t.worktype IN ('WEST') AND a.worktype = t.id)
AND a.completeDate >= DATE(NOW() - Interval 4 month));

Additional Info: The tables are related only by the worktype. Basically I'm using the worktypes table just so I can type 'WEST' instead of giving an id number so it's easier to understand the query at-a-glance. I added on to the query. I didn't copy and paste it all. Oops.

Thank you!


问:
Using concat method with closure in child functions
I want to use .concat, not push, inside the scope of a child function then access it higher up the scope chain.

I have here a simple function to list files in a directory after running them through a regex function to filter out certain filenames and filetypes. The following function works fine with the .push array method, but it returns an empty array if I try to use .concat

```<code>fs.readdir('./schema', function(err,files){
  var filelist = [];
  if(err)
    throw err;
  else{
    var index = files.length;
    while(index>0){
      filelist.concat(isNOTswapfile(files[index]));
      index--;
      }
    console.log(filelist)
    }
  }
)
</code>```

Returns an empty array []

Help is welcome and appreciated.

答:
concat returns you a new Array back. So unless you reassign the filelist variable back, it will just remain []

```<code>while(index>0){
  filelist = filelist.concat(isNOTswapfile(files[index]));
  index--;
}
console.log(filelist)
</code>```

should work just fine.

You can read more on MDN Array.prototype.concat

Body:
I want to use .concat, not push, inside the scope of a child function then access it higher up the scope chain.

I have here a simple function to list files in a directory after running them through a regex function to filter out certain filenames and filetypes. The following function works fine with the .push array method, but it returns an empty array if I try to use .concat

fs.readdir('./schema', function(err,files){
  var filelist = [];
  if(err)
    throw err;
  else{
    var index = files.length;
    while(index>0){
      filelist.concat(isNOTswapfile(files[index]));
      index--;
      }
    console.log(filelist)
    }
  }
)

Returns an empty array []

Help is welcome and appreciated.

Body:
concat returns you a new Array back. So unless you reassign the filelist variable back, it will just remain []

while(index>0){
  filelist = filelist.concat(isNOTswapfile(files[index]));
  index--;
}
console.log(filelist)

should work just fine.

You can read more on MDN Array.prototype.concat


问:
AWS CloudSearch uploaded PDFs content not indexed
I am attempting to upload PDF to CloudSearch via the console. While the document is added, the content is not effectively searchable. The console generates SDF formatted JSON like this:

```<code>[ {
  "type" : "add",
  "id" : "Sample.pdf",
  "fields" : {
    "content_type" : "text/plain",
    "content_encoding" : "windows-1252",
    "resourcename" : "Sample.pdf",
    "content" : "%PDF-1.6\r\nCatalogx^½]ÛrÜ6�}Ÿ¯˜ÊÃ{...}\r\n%%EOF"
  }
} ]
</code>```

When I attempt to search for document content, the text readable above ("PDF", "Catalog") appears, but not any of the "useful" content of the document.

I was surprised to see that:

the content/type was text/plain instead of appliation/pdf, and

the content was not encoded as something like base64

I then hand-crafted my own batch XML file to attempt the same:

```<code><batch>
    <add id="pdftest1">
        <field name="content_type">application/pdf</field>
        <field name="resourcename">Sample1.pdf</field>
        <field name="content">{copied from aws console output}</field>
    </add>
</batch>
</code>```

and

```<code><batch>
    <add id="pdftest2">
        <field name="content_type">application/pdf</field>
        <field name="resourcename">Sample2.pdf</field>
        <field name="content">{base64 encoded pdf contents}</field>
    </add>
</batch>
</code>```

It is possible to have CloudSearch search the "useful" contents of a PDF without converting the PDF to a text file first?

If so, what am I doing wrong?

Edit 6/27/2016

The CloudSearch command line interface generates batches that work by converting the PDF to raw text. Not sure why the AWS CloudSearch console does not do the same.

```<code>C:\Downloads>cs-import-documents --source .\Sample.pdf --output .\1.json
</code>```

produced:

```<code>[ {
  "type" : "add",
  "id" : "xmlC:_Downloads_Sample.pdf",
  "fields" : {
    "content_type" : "application/pdf",
    "created" : "Fri Jun 17 11:14:45 EDT 2016",
    "resourcename" : "Sample.pdf",
    "content" : "6/17/2016 [... remaining text omitted for brevity ...]
  }
} ]
</code>```

The AWS documentation includes:

Amazon CloudSearch console provide a way to automatically generate
  properly formatted JSON or XML from several common file types: PDF,
  Microsoft Excel, Microsoft PowerPoint, Microsoft Word, CSV, text, and
  HTML.

This appears to be incorrect as of 6/24/2016 (or I've missed something in my usage of the console).

This leaves me with an alternate question: what is a reasonably efficient way to daily get several hundred new PDFs located in an S3 bucket into CloudSearch? Specifically:

Does the CloudSearch API offer the "pdf-to-text" as part of their API?

Must I use the CS CLI to perform the conversion?

If the CLI is the recommended way to go, that seems inefficient in that (I assume) the CLI must pull the PDF from S3, convert to text, and then push the resulting SDF to CloudSearch. It seems ... odd that AWS would not provide an API call against CS that would do precisely this for me.  Perhaps they do offer it and I'm missing it?

答:
Finally, I was able to get it to work! The way it worked for me is to us cs-import-documents AWS Cloudsearch command.
cs-import-documents --source "c:\test.pdf" --output "C:\test.sdf"

It produced a .json file. I uploaded this to the Cloudsearch through the console and the search provided results.

Good luck,
Raj

Body:
I am attempting to upload PDF to CloudSearch via the console. While the document is added, the content is not effectively searchable. The console generates SDF formatted JSON like this:

[ {
  "type" : "add",
  "id" : "Sample.pdf",
  "fields" : {
    "content_type" : "text/plain",
    "content_encoding" : "windows-1252",
    "resourcename" : "Sample.pdf",
    "content" : "%PDF-1.6\r\nCatalogx^½]ÛrÜ6�}Ÿ¯˜ÊÃ{...}\r\n%%EOF"
  }
} ]

When I attempt to search for document content, the text readable above ("PDF", "Catalog") appears, but not any of the "useful" content of the document.

I was surprised to see that:

the content/type was text/plain instead of appliation/pdf, and

the content was not encoded as something like base64

I then hand-crafted my own batch XML file to attempt the same:

<batch>
    <add id="pdftest1">
        <field name="content_type">application/pdf</field>
        <field name="resourcename">Sample1.pdf</field>
        <field name="content">{copied from aws console output}</field>
    </add>
</batch>

and

<batch>
    <add id="pdftest2">
        <field name="content_type">application/pdf</field>
        <field name="resourcename">Sample2.pdf</field>
        <field name="content">{base64 encoded pdf contents}</field>
    </add>
</batch>

It is possible to have CloudSearch search the "useful" contents of a PDF without converting the PDF to a text file first?

If so, what am I doing wrong?

Edit 6/27/2016

The CloudSearch command line interface generates batches that work by converting the PDF to raw text. Not sure why the AWS CloudSearch console does not do the same.

C:\Downloads>cs-import-documents --source .\Sample.pdf --output .\1.json

produced:

[ {
  "type" : "add",
  "id" : "xmlC:_Downloads_Sample.pdf",
  "fields" : {
    "content_type" : "application/pdf",
    "created" : "Fri Jun 17 11:14:45 EDT 2016",
    "resourcename" : "Sample.pdf",
    "content" : "6/17/2016 [... remaining text omitted for brevity ...]
  }
} ]

The AWS documentation includes:

Amazon CloudSearch console provide a way to automatically generate
  properly formatted JSON or XML from several common file types: PDF,
  Microsoft Excel, Microsoft PowerPoint, Microsoft Word, CSV, text, and
  HTML.

This appears to be incorrect as of 6/24/2016 (or I've missed something in my usage of the console).

This leaves me with an alternate question: what is a reasonably efficient way to daily get several hundred new PDFs located in an S3 bucket into CloudSearch? Specifically:

Does the CloudSearch API offer the "pdf-to-text" as part of their API?

Must I use the CS CLI to perform the conversion?

If the CLI is the recommended way to go, that seems inefficient in that (I assume) the CLI must pull the PDF from S3, convert to text, and then push the resulting SDF to CloudSearch. It seems ... odd that AWS would not provide an API call against CS that would do precisely this for me.  Perhaps they do offer it and I'm missing it?