text:
Q: Three.js - Vertex Shader UV variable return only 0,0 I loaded an object with OBJLoader. I want to use a Shader Material with a texture. I pass my texture to the uniforms parameters of the material.
I pass the UV variable from the vertex shader to the fragment shader.
But when I use the uv coordinate for mapping my texture I get always 0,0 or at least this is what it looks like. The whole object is coloured with the bottom left pixel of the texture.
Here are my shaders:
  <script type='x-shader/x-vertex' id='vertex-shader'>
    uniform float u_time;
    varying vec2 vUv;
    void main() {
      vUv = uv;
      vec4 pos = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      gl_Position = pos;
    }
  </script>
  <script type='x-shader/x-fragment' id='fragment-shader'>
    precision highp float;
    uniform float u_time;
    uniform vec2 u_resolution;
    uniform sampler2D texture;
    varying vec2 vUv;
    void main(){
      vec2 st = vUv;
      vec4 tex = texture2D(texture, st);
      gl_FragColor = tex;
     }
  </script>

And here is how I load the object and assign the material
var loader = new THREE.OBJLoader();
loader.load(
    'assets/standing.obj',
    function (object){

    main.man = object;
    main.man.position.set(0,-600,400);

    main.texture = new THREE.TextureLoader().load( 'assets/na_00004c.jpg' );

    main.texture_needsUpdate = true;
    var uniforms = {
      u_time:{type:'f', value:0.0},
      u_mouse:{type:'v2', value: new THREE.Vector2()},
      u_resolution: {type: 'v2', value: {x:2048.,y:1024.}},
      texture: {type: 't', value: main.texture}
    }

    main.material = new THREE.ShaderMaterial({
      uniforms: uniforms,
      vertexShader: document.getElementById('vertex-shader').textContent,
      fragmentShader: document.getElementById('fragment-shader').textContent,
      transparent: true
    });

    main.material.needsUpdate = true;
    main.material.side = THREE.DoubleSide;

    main.man.traverse(function(child){
      if(child instanceof THREE.Mesh){
        child.material = main.material;
        child.material.needsUpdate = true;
        child.geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
        child.geometry.computeVertexNormals();
        child.geometry.elementsNeedUpdate = true;
        child.geometry.mergeVertices();
        child.verticesNeedUpdate = true;
        child.normalsNeedUpdate = true;
        child.uvsNeedUpdate = true;
        child.material.flatShading = THREE.SmoothShading;
      }
    });

        main.scene.add(main.man);

    },
    function (xhr){
        console.log((xhr.loaded/xhr.total*100)+'% loaded');
    },
    function (error){
        console.log(error,'An error happened');
    }
);

Here there is the full example
http://cmt.re/dev/na/
This is the image that I want to use as a texture
http://cmt.re/dev/na/assets/na_00004c.jpg
Does somebody know why this is happening?
Thanks a lot.

A: Your code works fine, but your *.obj file doesn't contain any texture coordinates. The Wavefront OBJ file (.obj file) is a text file, texture coordinates are the entries with the key vt, if this entries are missing, the mesh doesn't have any texture coordinates.
Your code works fine, see the example, where I used your original code with a simple model:

var main = new function(){

  this.init = function(){

    this.initThree();

  }

  this.initThree = function(){

    main.scene = new THREE.Scene();
    main.scene.background = new THREE.Color(0xCCCCCC);

    var aspectRatio = window.innerWidth / window.innerHeight;
    main.camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 100000);
    //main.camera.position.set(-40, 0, 512);
    main.camera.position.set(1,2,0);

    main.renderer = new THREE.WebGLRenderer({antialias: true});
    main.renderer.setPixelRatio(window.devicePixelRatio);
    main.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(main.renderer.domElement);

    main.controls = new THREE.OrbitControls(main.camera, main.renderer.domElement);
    main.controls.enableDamping = true;
    main.controls.dampingFactor = 0.1;
    main.controls.screenSpacePanning = false;

    var helper = new THREE.GridHelper(2000, 100);
    helper.material.opacity = 0.25;
    helper.material.transparent = true;
    main.scene.add(helper);

    var axis = new THREE.AxesHelper();
    main.scene.add(axis);

    makeTextFile = function (text) {
      var data = new Blob([text], {type: 'text/plain'});
      var textFile = window.URL.createObjectURL(data);
      return textFile;
    }
    var textbox_obj = document.getElementById('plane_obj');
    var obj_url = makeTextFile(textbox_obj.value);

    var loader = new THREE.OBJLoader();
    loader.load(
     obj_url,
     function (object){

        main.man = object;
        //main.man.position.set(0,-600,400);
        main.man.position.set(0,0,0);

        main.texture = new THREE.TextureLoader().load( 'https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/Gominolas.png' );

        main.texture_needsUpdate = true;
        var uniforms = {
          u_time:{type:'f', value:0.0},
          u_mouse:{type:'v2', value: new THREE.Vector2()},
          u_resolution: {type: 'v2', value: {x:2048.,y:1024.}},
          texture: {type: 't', value: main.texture}
        }

        main.material = new THREE.ShaderMaterial({
          uniforms: uniforms,
          vertexShader: document.getElementById('vertex-shader').textContent,
          fragmentShader: document.getElementById('fragment-shader').textContent,
          transparent: true
        });

        main.material.needsUpdate = true;
        main.material.side = THREE.DoubleSide;

        // main.material = new THREE.MeshNormalMaterial();

        main.man.traverse(function(child){
          if(child instanceof THREE.Mesh){
            child.material = main.material;
            child.material.needsUpdate = true;
            child.geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
            child.geometry.computeVertexNormals();
            child.geometry.elementsNeedUpdate = true;
            child.geometry.mergeVertices();
            child.verticesNeedUpdate = true;
            child.normalsNeedUpdate = true;
            child.uvsNeedUpdate = true;
            child.material.flatShading = THREE.SmoothShading;
          }
        });

      main.scene.add(main.man);

     },
     function (xhr){
      console.log((xhr.loaded/xhr.total*100)+'% loaded');
     },
     function (error){
      console.log(error,'An error happened');
     }
    );

    window.onresize = main.onResize;

    this.render();

  }

  this.render = function(){

    var time = Date.now();
    main.controls.update();
    requestAnimationFrame(main.render);
    main.renderer.render(main.scene, main.camera);

  }

  this.onResize = function(event) {

    main.renderer.setSize(window.innerWidth, window.innerHeight);
    main.camera.aspect = window.innerWidth / window.innerHeight;
    main.camera.updateProjectionMatrix();

  }

}

 main.init();
<script src="https://cdn.jsdelivr.net/npm/three@0.115/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.115/examples/js/controls/OrbitControls.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/loaders/OBJLoader.js"></script>

<textarea id="plane_obj" style="display:none;">
    v -1.000000 0.000000 1.000000
    v 1.000000 0.000000 1.000000
    v -1.000000 0.000000 -1.000000
    v 1.000000 0.000000 -1.000000

    vt 0.000000 0.000000
    vt 1.000000 0.000000
    vt 0.000000 1.000000
    vt 1.000000 1.000000

    vn 0.0000 1.0000 0.0000

    f 1/1/1 2/2/1 4/4/1 3/3/1
</textarea>

<script type='x-shader/x-vertex' id='vertex-shader'>
uniform float u_time;
varying vec2 vUv;
void main() {
    vUv = uv;
    vec4 pos = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    gl_Position = pos;
}
</script>

<script type='x-shader/x-fragment' id='fragment-shader'>
precision highp float;
uniform float u_time;
uniform vec2 u_resolution;
uniform sampler2D texture;
varying vec2 vUv;
void main(){
    vec2 st = vUv;
    vec4 tex = texture2D(texture, st);
    gl_FragColor = tex;
}
</script>


text:
Q: The Alternating Product of Determinant Bundles is Trivial This is Vakil 13.5 H, self-study.
We are to show that given an exact sequence of finite rank locally free sheaves on $X$
$$0 \to \mathcal F_1 \to \mathcal F_2 \to ... \to \mathcal F_n \to 0$$
we must have
$$\det \mathcal F_1 \otimes \det (\mathcal F_2)^{\vee} \otimes \det \mathcal F_3 \ \otimes ... \otimes \det \mathcal (F_n)^{(-1)^n} \simeq \mathcal O_X$$
where $\det \mathcal F := \bigwedge^{\text{rank} \ \mathcal F} \mathcal F$. The hint is to break up into short exact sequences and show those are short exact sequences of finite rank locally free sheaves. I have done so using a previous exercise, yielding short exact sequences of finite rank locally free sheaves
$$0 \to \operatorname{coker} \phi_{i - 2} \to \mathcal F_i \to \operatorname{image} \phi_i \to 0$$
where the $\phi_i : \mathcal F_i \to \mathcal F_{i + 1}$ come from the original exact sequence. We are then supposed to use the fact that for a short exact sequence $0 \to \mathcal F' \to \mathcal F \to \mathcal F'' \to 0$ of locally free finite rank sheaves,
$$\det \mathcal F \simeq \det \mathcal F' \otimes \det \mathcal F''$$
Using this hint, we obtain
$$\det \mathcal F_i \simeq \det (\operatorname{image} \phi_{i}) \otimes \det (\operatorname{coker}  \phi_{i - 2})$$
Main question: how do I use this fact to conclude? I do not know how to envision the dual of the determinant, nor do I see how using the fact above gives us what we want.
Small side question: what does the $(-1)^n$ mean in the original exact sequence? I gather it is supposed to mean that we are alternating between dual and no dual, but I do not understand why that is appropriate notation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set Version number of TFS Build in C# File Hy,
is it possible to set the number of the TFS Build in a C# File?
The TFS Build should replace the version number with the current one.

public const string SERVICE_VERSION = "2.0 Build: 20130518.1";

EDIT:
The const is in a class called SharedMethods:

public static class SharedMethods
{
    public const string SERVICE_VERSION = "2.0 Build: 20130518.1";
    ...
    ...
}

The TFS build should check out the element, update the version, check in the element and continue the normal build process.

A: If your file contains only theses lines, perhaps you could do something like that :
    <WriteLinesToFile File="$(VersionFilePath)" Lines="public const string SERVICE_VERSION = %22$(Version)%22%3B" Overwrite="true" Encoding="ASCII"/>

Note that " should be replaced by %22 and ; by %3B (when you add a ';', a new line char is inserted).
Otherwise, you could write C# code in a msbuild to do what you want. An exemple :
<UsingTask TaskName="UpdateApplicationRevision" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
   <ParameterGroup>
        <ProjectFilePath ParameterType="System.String" Required="true" />
    </ParameterGroup>
        <Task>
          <Reference Include="$(MSBuildToolsPath)\Microsoft.Build.dll" />
          <Reference Include="System.Xml" />
        <Code Type="Fragment" Language="cs">
            <![CDATA[
      var project = new Microsoft.Build.Evaluation.Project(ProjectFilePath);
      var property = project.GetProperty("ApplicationRevision");
      property.UnevaluatedValue = "" + (System.Int32.Parse(property.EvaluatedValue) + 1);
      project.Save();
]]>
        </Code>
    </Task>
</UsingTask>

Here, I modify a csproj (xml) file, but feel free to write your own code to read your file and update it...

A: Check out this article:
Create a Custom WF Activity to Sync Version and Build Numbers
It describes how to change the version number in the AssemblyInfo.cs file. You could tweak this to suit your needs.


text:
Q: DataGrid.SelectedItems not recongnised I am using a datagrid to display data from a database, I need to get the selected row, but when i use DataGrid.SelectedItem, it does not recognize the property SelectedItem.Does any one know what the reason might be?
I use bindinglist to bind the data to the grid.
    private void delete_btn_Click(object sender, RoutedEventArgs e)
    {
        if (selectAll == true)
        {
            ThisAddIn.sourceContext.removeAll();
        }
        else
        {
            var grid = sender as DataGrid;
            var selected = grid.SelectedItems;

            foreach (var item in selected)
            {
                ThisAddIn.sourceContext.removeEntity ((Source)item);
            }
        }
    }

        DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
        ItemsSource="{Binding ObservableEvtCode}"
        Name="SourceDataGrid" AutoGenerateColumns="True" Margin="10,40,10,10" IsReadOnly="True"

A: SelectedItem is part of the DataGrid class.
However, if nothing is selected, then you run into issues.
Does this help?
      var selected = grid.SelectedItems;
      if (selected != null)
      {
        foreach (var item in selected)
        {
            ThisAddIn.sourceContext.removeEntity ((Source)item);
        }
      }


text:
Q: Extreme points of $f(x)= 2x+\cot x$ I want to find the extreme points of the function $f(x) =2x+\cot x$.
I began by observing that the function is defined on $D=\mathbb{R} - \{k\pi | k\in \mathbb{Z} \} $. Now, $f'(x) =2-\frac{1}{\sin^2 x} $ $\forall x \in D$. I tried to study $f'$'s sign, but I don' t know how to get around the points where the function is not defined.

A: $D_f = \mathbb{R} - \{k\pi, k\in \mathbb{Z}\}$
$f(x) = 2x+\cot x $
$f'(x) = 2 - \csc^2x$

At extreme points, $f'(x) = 0$

$2 = \csc^2x \implies \sin^2x = \frac{1}{2} = \sin^2\frac{\pi}{4}$

$$x = 2k\pi\pm\pi/4$$

These are the extreme points.
It'd be clear from the graph below of $f(x)$


text:
Q: display user information in fragment I'm using Android Studio 3.5.
I built bottom navigation with fragment and then I'm trying to display user information such as (name - email - image and so on) that is  retrieved from a Firebase store .. when reach to :
documentReference.addSnapshotListener (this, new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot documentSnapshot,
            @Nullable FirebaseFirestoreException e) {
        t_name.setText(documentSnapshot.getString("name"));
        t_email.setText(documentSnapshot.getString("email"));
    }
});

It gave me a red line under the code... When click Alt + Enter, it gives me solve put cast (Executor) before (this) after the cast the app doesn't work ...

I don't know how to solve it ..
Note: This is on fragment not in activity
And if I want to display image that retrieve from Firebase... How can I do it?
Thanks
account Fragment
public class accountFragment extends Fragment {
    FirebaseAuth fAuth;
    FirebaseFirestore fStore;
    String userID;
    TextView logout_account , t_name , t_email , t_country ;

    public  accountFragment(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_account, container, false);

    fAuth = FirebaseAuth.getInstance();
    fStore = FirebaseFirestore.getInstance();
    userID = fAuth.getCurrentUser().getUid();

    t_country = v.findViewById(R.id.t_country);
    t_email = v.findViewById(R.id.t_email);
    t_name = v.findViewById(R.id.t_name);

    DocumentReference documentReference = fStore.collection("eng.users").document(userID);
    documentReference.addSnapshotListener (this, new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot,
                @Nullable FirebaseFirestoreException e) {
            t_name.setText(documentSnapshot.getString("name"));
            t_email.setText(documentSnapshot.getString("email"));
            t_country.setText(documentSnapshot.getString("country"));
        }
    });
}

Activity_account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".categories.accountFragment">

    <LinearLayout
    android:id="@+id/banner_pro"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/banner2"
    android:orientation="horizontal"
    android:paddingLeft="50dp"
    android:paddingTop="10dp">

    <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:src="@drawable/mypic"
    app:civ_border_color="@color/colorDarkBlue"
    app:civ_border_width="2dp" />

    <LinearLayout
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    >

    <TextView
    android:textColor="@color/colorDarkBlue"
    android:id="@+id/t_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Name"
    android:textSize="20dp"
    android:textStyle="bold"/>

    <TextView
    android:id="@+id/t_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="9dp"
    android:text="Email"
    android:textSize="15dp" />

    <TextView
    android:id="@+id/t_country"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="country"
    android:textSize="15dp" />

    </LinearLayout>

    </LinearLayout>

    <TextView
    android:paddingLeft="20dp"
    android:id="@+id/logout_account"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/banner_pro"
    android:layout_marginTop="20dp"
    android:text="LogOut"
    android:textSize="30dp" />

</RelativeLayout>

A: The problem is on
documentReference.addSnapshotListener (this, ...

use
documentReference.addSnapshotListener (getActivity(), ...

You are in a fragment


text:
Q: Printing the n most frequent words in a file (string) The goal:

Write a function that takes two parameters: (1) a String representing a text document and (2) an integer providing the number of items to return. Implement the function such that it returns a list of Strings ordered by word frequency, the most frequently occurring word first.  Use your best judgement to decide how words are separated. Your solution should run in O(n) time where n is the number of characters in the document.

My thoughts were that, in the worst case, the input to the function could be the total number of words in the document, reducing the problem to sorting the words by their frequencies. This made me think that the lower bound for time complexity would be O (n log n) if I used a comparison sorting method. So, my thought was that the best approach was to implement a counting sort. Here is my code.
I would like for you to tell me whether my analysis is correct, I've annotated the code with my idea of what the time complexity is, but it could definitely be incorrect. What is the actual time and space complexity of this code? Also I would like to hear if this is in fact a good approach, if there are any alternate approaches that would be used in practice.
### n is number of characters in string, k is number of words ###
def word_frequencies(string, n)
  words = string.split(/\s/)  # O(n)
  max = 0
  min = Float::INFINITY
  frequencies = words.inject(Hash.new(0)) do |hash,word|  # O(k)
    occurrences = hash[word] += 1                     # O(1)
    max = occurrences if occurrences > max            # O(1)
    min = occurrences if occurrences < min            # O(1)
    hash;                                             # O(1)
  end

  ### perform a counting sort ###
  sorted = Array.new(max + words.length)

  delta = 0

  frequencies.each do |word, frequency|   #O(k)
    p word + "--" + frequency.to_s
    index = frequency
    if sorted[index]
      sorted[index] = sorted[index].push(word)  # ??? I think O(1).
    else
      sorted[index] = [word]                    # O(1)
    end
  end

  return sorted.compact.flatten[-n..-1].reverse
  ### Compact is O(k).  Flatten is O(k).  Reverse is O(k). So O(3k)
end

### Total --- O(n + 5k) = O(n).  Correct?
### And the space complexity is O(n) for the hash + O(2k) for the sorted array.
### So total O(n).

text = "hi hello hi my name is what what hi hello hi this is a test test test test hi hi hi what hello these are some words these these"

p word_frequencies(text, 4)

A: Two ways:
def word_counter(string, max)
  string.split(/\s+/)
        .group_by{|x|x}
        .map{|x,y|[x,y.size]}
        .sort_by{|_,size| size} # Have to sort =/
        .last(max)
end

def word_counter(string, max)

  # Create a Hash and a List to store values in.
  word_counter, max_storage = Hash.new(0), []

  #Split the string an and add each word to the hash:
  string.split(/\s+/).each{|word| word_counter[word] += 1}

  # Take each word and add it to the list (so that the list_index = word_count)
  # I also add the count, but that is not really needed
  word_counter.each{|key, val| max_storage[val] = [*max_storage[val]] << [key, val]}

  # Higher count will always be at the end, remove nils and get the last "max" elements.
  max_storage.compact.flatten(1).last(max)

end

A: One idea is following:

*

*You are already constructing a hash map that gives the frequency of a given word.

*Now iterate through this hash map and create a reverse "hash set". That is the set of words for a given frequency.

*Find the maximum frequency and output the set of words for that frequency.

*Decrement it, and check for words in the hash set.

*Keep doing this till the required number of words.

The order of this algorithm shall be O(f) where f is the maximum frequency of any word. The maximum frequency of any word shall be at most n where n is the number of characters as required.

A: Sample, quick way :)
#assuming you read from the file and get it to a string called str

h = {}
arr = str.split("\n")
arr.each do |i|
  i.split(" ").each do |w|
    if h.has_key[w]
      h[w] += 1
    else
      h[w] = 1
    end
  end
end
Hash[h.sort_by{|k, v| v}.reverse]

This works, but could be improved.


text:
Q: ASP.NET MVC: First access after some minutes slow, then every following request is fast when I access any page of my ASP.NET MVC website first time, then this first request is slow. It needs about 4-5 seconds to load. But every following request to any page is fast.
When I wait some minutes or a hour then every first request is slow again. Every following request is fast.
I think that IIS 7 is compiling the code and keep it in memory. After some time it will delete it from memory so it needs to compile it again.
What can I do that every first request is as fast as every following request?
(Without precompiling my source, if possible)
Thank you very much in advance!

A: This is almost-certainly your app pool idle timeout setting (and not your code being recompiled).
The default app pool idle timeout in IIS is 20 minutes. Which means that, if 20 minutes pass and no requests come in to your app, IIS will shut down the worker process for your app pool, making your app "cold" again. Whoever makes the next request will be waiting several seconds as IIS restarts the worker process and "warms" your app back up.
If you don't want IIS to automatically "cool down" your app after a period of inactivity, you can disable the app pool idle timeout by setting it to 0.

A: If this is a production server then why not try adding a website monitor; such as up time robot. It basically  asks for your websites headers and gets status codes like "200-ok", "404-not found", etc. every 5 minutes. This way your site is always spun up and does not impact log files/analytics as only headers are requested. I use this for my cloud sites as I find that they take 5 seconds to spin up which has an impact on site loading. With the monitor they are instant.
Oh and its free for up to 50 sites!

A: This could be the recycle worker processes setting on the application pool, check the value for that and either turn it off or make it longer.
Could also be the Shutdown worker process after being idle under performance for the application pool.
It's probably the second as that defaults to 20 minutes, the first one defaults to 29 hours I believe.

A: Assuming that you have a regular stream of visitors, this should not be a problem in production. Also, unless you're physically altering any of your source files, IIS would not recompile it when it spins up your app.
Also, take a look at the .NET compilation settings available:
http://technet.microsoft.com/en-us/library/cc725812(WS.10).aspx

A: tl; dr
After quite extensive testing and gathering of relevant sources to attempt to resolve the issue, I think that the minimal solution may be (not verified) to add this code to the global.asax:
    protected void Application_End()
    {
        ...
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://web_domain.tld");
        using (HttpWebResponse response = (HttpWebResponse)
            request.GetResponse())
        {
        }
        ...
    }

In the time of writing the post, this is used to effectevely maintain the site I worked on 'always-up' - with conjuction of setting the Idle Time-out (minutes) in IIS to 0 as mentioned in other answers. However I think that changing Idle Time-out (minutes) may not be necessary (assuming that Application_end event is raised when the switch of application pool to Idle mode occurs).
How it works (assuming it does):

*

*There are 2 settings in the IIS application pool settings that affect when the application is suspended or terminated. One of them is Idle Time-out (minutes) which defaults to 20 minutes and when the specified time elapses since the last request, the worker process is suspended or terminated. When a next request comes, the worker process is resumed or started again and the Application_start event is raised (and so if the Application_start handler is defined in global.asax, it is executed). In case of the project I worked on, the Application_start took about 17 seconds to complete. So if the site was 'left alone' for 21 minutes and then the new request came, it took about a little more than 17 seconds before the response was sent back (Application_start + page processing). When another request was sent in the window of 20 minutes, the response was sent significantly faster (perhaps less than 1s), since the Application_start has already been processed.

Setting the Idle Time-out (minutes) value to 0 causes the worker process to never be suspended / terminated (at least due to the idle time - there may be another cause described below).

*Apart from Idle Time-out (minutes), there is also the Regular time interval (minutes) setting in Recycling section of the IIS advanced settings. This defaults to 1740 minutes (29 hours) and is a regular scheduled task that causes the Application pool to periodically recycle (the period is fixed). This, I understood, is to prevent the accumulation of possible memory-leaks which, if present, may eventually crash the server by exhasting all the memory. The effect of app-pool recycling is that Application_end event is raised. However, after the application ends it is not automatically started again, so the Application_start event is not raised until an actual request comes (which is similar to the first case). So in the case of the aforementioned web application I worked on, it would again take about 17 seconds to process the first request to arrive after the recycling occured. Changing this value to 0 turns the recycling off, but I suppose that it is reasonable not to turn the recycling completely off due to the possibility of accumuluation of memory leaks over time (which may possibly even be caused by bugs in 3rd party libraries). I understand that the opinions differ on whether to set this value to 0 or not and may change over time.

Posible solution (without changing IIS settings):
If the requests are sent frequently enough, the app-pool may never switch to Idle mode. On the event of recycling, this would also cause to the application to start again. This can be achieved, for example, by using 3rd party service as described by @Rippo.
Proposed solution:
It has been observed that application pool recycling caused Application_end event to be raised. Assuming that it is also raised upon switching of the application pool to Idle mode, it would seem to be sufficient to create a request in the Application_end event handler to the website, which in both cases would then cause the application to start again (raising the Application_start event). The code is at the top of the answer.


text:
Q: Can I use SQL to balance 'IN' transactions against 'OUT' transactions? Fair warning, I am very new to this and am likely going about things altogether the wrong way. Sorry for my formatting.
I am working with an SQL database that manages all inventory and transactions within the company. Using the transaction log (translog), I want to be able to identify how many parts exist in a current location by balancing the 'OUT' and 'IN' quantities.
Effectively, I have a table like this:

ITEMNO
LOT_NO
TRANS_IN_OUT
TRANS_QUAN
LOC_DESC

Adpa01
156222
IN
21
IN_TRANSIT

Adpa01
156222
OUT
21
IN_TRANSIT

Adpa01
156222
IN
22
IN_TRANSIT

Adpa02
156133
IN
21
IN_TRANSIT

Adpa02
156134
IN
21
IN_TRANSIT

Adpa02
156133
OUT
11
IN_TRANSIT

Adpa01
156223
IN
21
IN_TRANSIT

At minimum, I'm hoping for the output:

ITEM_NO
LOT_NO
QTY

Adpa01
156222
22

Adpa02
156133
11

Adpa02
156134
21

Adpa01
156223
21

I got as far as a basic query filtering out the results that I'm trying to work with.
Newbie code:
Select TRANSLOG.ITEMNO,
  TRANSLOG.TRANS_QUAN,
  TRANSLOG.LOC_DESC,
  TRANSLOG.LOTNO
From TRANSLOG
Where TRANSLOG.ITEMNO Like '<filter>' And TRANSLOG.TRANS_QUAN > 0 And
  TRANSLOG.LOC_DESC Like 'IN TRANSIT'
Order By TRANSLOG.ITEMNO

My concept is to sum the 'IN' quantities minus the 'OUT' quantities for each unique Lot Number, but I'm not sure if I'm just making things more difficult than they need to be.
Any help is greatly appreciated!


text:
Q: Maintainance of a (Gitlab) Wiki (Broken Links, Page Rename, etc.) I'm trying to create a documentation Wiki for our internal software on Gitlab.
The starting point was a messy set of texts, partly from some LaTeX script but also other sources.
My biggest issue at this point is to ensure the correctness of all cross-references/links within the wiki.
I'm steadily cleaning up page by page, but it seems impossible to fix all the broken links. Especially, if some pages are renamed, or moved to another folder, every reference to this page is broken. It is also annoying to verify each link manually, i.e. by clicking on it just to see whether it links to some destination or not.
So, my question is: Are there any tools for checking the integrity of a Gitlab wiki?
I'm thinking of something like this: If I clone the entire Wiki into my machine (via git), I have a folder structure, populated with markdown files. Some tools should run recursively through all these files/folders and at least give me a list of broken links.
Of course, some re-factoring tools that would update links in other pages if I move/rename a page would be even more awesome.

A: Consider whether markdown-link-check might work for you. FOSDEM has a good introductory article.
I was not able to use markdown-link-check for an Azure DevOps Wiki (cloned git repo.), presumably due to the need for an implicit '.md' added to the links. Although, I did not put much effort into the attempt.
I could - and may eventually - fork the source and adapt it to Azure DevOps Wiki. You might find that it works out-of-the-box for GitLab's Wiki or, you may be able to adapt it.


text:
Q: Double quotes need to be removed and insert statement order need to be fixed I am using ora2pg to export TABLE and INSERT type from oracle database. https://ora2pg.darold.net/documentation.html#:~:text=Ora2Pg%20consist%20of,QUERY%2C%20KETTLE%2C%20SYNONYM.
I have 2 questions.
The TABLE and INSERT sql statements have double quotes for table and column names but I want to create them without double quotes. Is it possible to configure this in the .conf file?
The INSERT sql file that is generated by ora2pg does not have the sql statements in right order. The parent table data should be inserted first before trying to insert data into child table due to foreign key constraints. But the INSERT sql file generated by ora2pg is not taking this into account so this is causing error because the child table insert statement is present before the parent table. Is this how ora2pg works or am I doing something wrong in the .conf file?


text:
Q: Setting NSTextAttachment bounds doesn't work on iOS 15     let attachment = NSTextAttachment()
    attachment.image = UIImage(named: "icon")
    attachment.bounds = CGRect(x: 8, y: 0, width: 12, height: 12)

The above code works well on mobile phones under iOS15, but the interval between text and image is always zero on iOS15
the bounds not work!


text:
Q: What's preventing Android from finding a resource file in drawable? I'm working on a bug of my Android application and it only occurs on a Galaxy Nexus with Android version 4.2.2, but works fine on my Nexus 5 with 4.4.2.
Basically it's not able to find a png file on this device.
The png file is only located in res/drawable and here is the structure of my res folder:
res/drawable
res/drawable-de
res/drawable-fr
res/drawable-it
res/drawable-hdpi
res/drawable-ldpi
res/drawable-mdpi
res/drawable-xhdpi
res/drawable-xxhdpi

What could be preventing Android to fallback to the drawable folder in this case?

A: Without knowing anything about the image its hard to say, but the image may be too large. Alternatively, unless there's a compelling reason not to, you should probably put it in a *dpi folder anyway

A: What is the configuration of your device when the drawable resource couldn't be found? When the device language is German, it might happen that one of the resource directory, e.g res/drawable-de has taken precedence of the drawable directory.
Take a look at here how android find the best matching resources.


text:
Q: iterate over all values of a pg_conn query in Ruby I have a ruby script where I need to retrieve all values from a database and do stuff with each one retrieved. Currently I am hard coding each retrieval, but this only works if there are 3 values coming back. How can I iterate over this? Below is my code:
  require 'pg'
  pg_conn = PGconn.connect(host = "main-pg-db-super.center.com", port = 6433, options = '', tty = '',
                        dbname = "master_data", login = "user", password = "password")

  all_children = pg_conn.exec("SELECT id FROM pt.tests WHERE parent = '1';") # will return 3 results
  puts all_children[0]['id']
  puts all_children[1]['id']
  puts all_children[2]['id']

A: all_children.each do |child|
  puts child['id']
end

Does this not work?


text:
Q: convert current and actual time to GMT in ionic datetime select? I have ion-datetime from ionic : I need when the user select the time to convert it to gmt it means if the user select 12:00 pm the time will receive on the server 9:00am
<ion-datetime displayFormat="MMM DD, YYYY HH:mm"
                formControlName="TripDateTime">

  </ion-datetime>


text:
Q: an error of starting hadoop-2.7.3 after finishing installation of hadoop-2.7.3 with java jdk1.8.0_111 in ubuntu
I used this command to start Hadoop
sbin/start-all.sh

it showed to me an error message

This script is Deprecated. Instead use start-dfs.sh and start-yarn.sh
  [Fatal Error] core-site.xml:19:1: Content is not allowed in prolog.

so I used the other command
sbin/start-dfs.sh

again another error show it to me

[Fatal Error] core-site.xml:19:1: Content is not allowed in prolog.

A: i think its hadoop cluster suppose to be started form bin in the hadoop installation dir example : /usr/local/bin/start-all.sh


text:
Q: Save texts on webpages (1000 pages) I have 1000 of URLs. I need a tools that get my URLs and export all the text that appears on those pages.
I need the texts that a is shown on the webpages, not the background html code.
Do you know any software or way to do it?

A: Save this as bat file (i.e. innerTextGet.bat):
@if (@X)==(@Y) @end /* JScript comment
        @echo off

        cscript //E:JScript //nologo "%~f0" %*
        ::pause
        exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

var link=WScript.Arguments.Item(0);
var saveTo=WScript.Arguments.Item(1);

var IE = new ActiveXObject("InternetExplorer.Application");
IE.Visible=false;
IE.Navigate2(link);

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

var counter=0;
while (IE.Busy && counter<60*60*10) {
    //WScript.Echo(IE.Busy);
    sleep(1000);
    counter++;
}

if(IE.Busy){
    WScript.Echo("Cant wait 4ever");
    WScript.Quit(10);
}

function writeContent(file,content) {
        var ado = WScript.CreateObject("ADODB.Stream");
        ado.Type = 2;  // adTypeText = 2
        ado.CharSet = "iso-8859-1";  // right code page for output (no adjustments)
        //ado.Mode=2;
        ado.Open();

        ado.WriteText(content);
        ado.SaveToFile(file, 2);
        ado.Close();
}

var innerText=IE.document.body.innerText;
IE.Quit();
writeContent(saveTo,innerText);

And use it like:
call innerTextGet.bat "https://stackoverflow.com/questions/46611374/save-texts-on-webpages-1000-pages"  result.txt

It is not fail safe - does not check if the result file already exists if the parameters are correctly passed and so on, but it works at least. It again uses innerText property of InternetExplorer.Application object as proposed by @omegastripes though I prefer jscript because it is easier to be plugged into batch file.
As you gave no information about where the links are stored I assume you know how to read and iterate through them.


text:
Q: Background image does not want to load in css I am creating a website in Django. I downloaded a html homepage template design on the internet that I want to improve upon and use for my website. since its been designed it came with a CSS file. now when I try to make the improvements specifically add a background image in one of the elements. it refuses to do so. the other elements respond to the CSS style but the background image refuses too. since I'm using Django i had to set up the static files and 'collect static' which I did but when I set that those pics to my background image in my CSS it refuses. here is the html file & css.
html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title> Home </title>
  <link rel="stylesheet" href="{% static 'style.css' %}">

  <link href=
 'https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css'
  rel='stylesheet'>
 <meta name="viewport" content="width=device-width, initial-
  scale=1.0">

the class="main" is where I'm trying to add the background-image too.
CSS
.home-section .main{
  background-image: url('https://www.pexels.com/photo/singer-
  singing-on-stage-beside-guitar-player-and-bass-player-
  167636/');
  padding: auto;
  margin: auto;
  background-size: 50pc;
 }
@media (max-width: 700px) {
.sidebar li .tooltip{
display: none;
 }
 }

I've tried everything but it refuses to acquis. Thanks in advance.

A: Load Static or have non-empty div
Without knowing what more code you have I can only guess that perhaps you forgot to load static files by including this on the top of your html file:
{% load static %}

Second, until the div is filled with something, it has no dimensions, so the image would occupy no space either.


text:
Q: bash sort / uniq -c: how to use tab instead of space as delimiter in output? I have a file strings.txt listing strings, which I am processing like this:
sort strings.txt | uniq -c | sort -n > uniq.counts

So the resulting file uniq.counts will list uniq strings sorted in the ascending order by their counts, so something like this:
 1 some string with    spaces
 5 some-other,string
25 most;frequent:string

Note that strings in strings.txt may contain spaces, commas, semicolons and other separators, except for the tab. How can I get uniq.counts to be in this format:
 1<tab>some string with    spaces
 5<tab>some-other,string
25<tab>most;frequent:string

A: You can do:
sort strings.txt | uniq -c | sort -n | sed -E 's/^ *//; s/ /\t/' > uniq.counts

sed will first remove all leading spaces at the beginning of the line (before counts) and then it will replace space after count to tab character.

A: You can simply pipe the output of the sort, etc to sed before writing to uniq.counts, e.g. add:
| sed -e 's/^\([0-9][0-9]*\)\(.*$\)/\1\t\2/' > uniq.counts

The full expression would be:
$ sort strings.txt | uniq -c | sort -n | \
sed -e 's/^\([0-9][0-9]*\)\(.*$\)/\1\t\2/' > uniq.counts

(line continuation included for clarity)

A: With GNU sed:
sort strings.txt | uniq -c | sort -n | sed -r 's/([0-9]) /\1\t/' > uniq.counts

Output to uniq.counts:

 1      some string with    spaces
 5      some-other,string
25      most;frequent:string

If you want to edit your file "in place" use sed's option -i.


text:
Q: Why is my TextInput out of sync with state when I give rapid inputs? I'm creating a typing race game with React Native which is producing an unexpected bug on Android.
When the user finishes typing a word/spacebar, I set the input state to an empty string.
However, if the user finishes typing a word/spacebar then immediately presses the first letter of the next word/spacebar, the onChangeText event returns the state which existed prior to setting it to a empty string, along with the new letter. It should instead return the new letter by itself.
The bug only occurs when typing very quickly on Android (emulator and real device), IOS hasn't been tested, and the web app works fine typing at any speed.
Snack to try it yourself with complete code: https://snack.expo.dev/@ariato/typing-race-bug-example?platform=android
const Race = () => {
  const [input, setInput] = useState("");
  const [wordIndex, setWordIndex] = useState(0);
  const [letterIndex, setLetterIndex] = useState(0);
  const [errorLength, setErrorLength] = useState(0);

  const totalIndex = getTotalIndex(wordIndex, letterIndex);

  const onChange = (val: string) => {
    setInput(val);
    checkInput(val);
  };

  const checkInput = (val: string) => {
    const inputLength: number = val.length;
    const answer = wordList[wordIndex].substring(0, inputLength);

    if (val === answer) {
      setErrorLength(0);
      if (val === wordList[wordIndex]) {
        const isLastWord = wordIndex === wordList.length - 1;
        if (isLastWord) {
          setWordIndex(0);
        } else {
          setWordIndex((wordIndex) => wordIndex + 1);
        }
        setLetterIndex(0);
        setInput("");
      } else {
        setLetterIndex(inputLength);
      }
    } else {
      setErrorLength(inputLength - letterIndex);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === "ios" ? "padding" : "height"}
    >
      <View style={styles.textContainer}>
        {wordList.map((word, wordIdx) => (
          <Text key={wordIdx}>
            {word.split("").map((letter, letterIdx) => (
              <Text key={letterIdx} style={getStyles(wordIdx, letterIdx)}>
                {letter}
              </Text>
            ))}
          </Text>
        ))}
      </View>
      <TextInput
        value={input}
        onChangeText={onChange}
        autoCapitalize="none"
        autoComplete="off"
        autoCorrect={false}
        spellCheck={false}
        importantForAutofill="no"
        autoFocus
        keyboardType="visible-password"
        style={styles.textInput}
      />
    </KeyboardAvoidingView>
  );
};

export default Race;

This screenshot is after typing It', and then typing s and a spacebar in rapid succession. The next character to type is underlined. For each incorrect character in the input there is a red letter.

These logs show how the input state is set to an empty string, then becomes It's_ in one key stroke, as though the internal state of the TextInput did not get changed to an empty string.

I tried:

*

*Moving the first setInput() in the onChange() to the if/else statements in checkInput() so that it would only trigger once per event, in case something strange was happening with setState() batching. No change, as expected.


text:
Q: Why isn't my view resizing when I show the keyboard? I've got a very basic webview app, and this is the layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />
</LinearLayout>

In the manifest I have:
android:windowSoftInputMode="stateVisible|adjustResize"

In the page I load, there is an input at the bottom of the page. When I click it, the keyboard shows, but obscures it. It's not a case of the view shrinking but not scrolling, as I can't scroll the webview to show the input with the keyboard visible. What am I doing wrong?

A: It's a bug with WebViews in fullscreen apps. More information in this other answer, but I fixed it by making my app non-fullscreen.


text:
Q: Applying bsxfun to function with multiple output arguments Let us assume we have a function myfunction with two output arguments
function [ arg1, arg2 ] = myfunction( a, b )
arg1 = a*b;
arg2 = a+b;
end

I want to apply myfunction to vector A and B:
fun = @myfunction;
A = 1:10;
B = 1:17;
[C, D] = bsxfun(fun,A,B)

This gives an error. How can I use bsxfun with functions having multiple output arguments?

A: bsxfun generates the output from all combinations of orthogonal matrices / vectors. Therefore to make your example work for even one output you have to transpose one of the inputs:
output1 = bsxfun(@myfunction,A,B.');

But as rayryeng commented, the problem with bsxfun is that it can return only one output. As Cris Luengo suggested in a comment you can instead use arrayfun. The difference is that for arrayfun you have to explicit generate all input combinations by expanding the input 1xN and 1xM vectors to NxM matrices:
For Matlab 2016b and later:
[output1, output2] = arrayfun(@myfunction,A.*ones(numel(B),1),B.'.*ones(1,numel(A)));

Matlab pre-2016b:
[output1, output2] = arrayfun(@myfunction,bsxfun(@times,A,ones(numel(B),1)),bsxfun(@times,B.',ones(1,numel(A))))

Instead of using bsxfun to expand the matrices you could also use repmat- but that's generally a bit slower.
Btw., If you have a function with many outputs and can't be bothered with writing [output1, output2, output3, ...] = ... you can just save them in a cell:
outputs = cell(nargout(@myfunction),1);
[outputs{:}] = arrayfun(@myfunction,....);

A: You cannot, the bsxfun is only for binary operations


text:
Q: howler.js: Which event is fired (continuously) while audio is playing? I am using howler.js to play audio. The feature I am trying to implement is highlighting text while audio is playing. I have timestamped (start and end) json data for each word.
To achieve highlighting word(s) with the audio, one way that I thought of is to loop through the words, for each word, if the current seek time is within the bounded range of a word's start and end time, then I will change attribute of the word's HTML SPAN.
Shouldn't I need an event that keeps firing while the audio is playing? In other words, if my goal was to implement an audio seek bar, how would I achieve that goal? From the documentation of howler.js, the objective of onseek function is unclear, its not firing. Here's what I tried from the documentation.
sound = new Howl({
   src: ['output.mp3'],
   html5: true,
   onseek: function() {
     console.log('seeking...');
   }
});

Or should I be looking at something else?

A: onseek is triggered when the audio is scrubbed to a different position. Normal playback does not trigger the seek event.
What I would recommend instead is something like this...
function isPlaying(){
   if(sound.playing()){
      console.log('audio is currently playing...');
      setTimeout(isPlaying, 1000); //adjust timeout to fit your needs
   }
}

sound = new Howl({
   src: ['output.mp3'],
   html5: true,
   onplay: isPlaying
});

Here's a very basic and dirty demo showing that it works: demo


text:
Q: Disable the zooming keyboard shortcuts in RStudio RStudio provides the option to use CTRL++ to zoom in on the whole workspace and I often hit that combination by accident, when I would like to execute selected code with CTRL+Enter. This is wasting time and I need to zoom out again afterwards.
So I would like to know if there's the possibility to disable these keybindings. These keyboard shortcuts are not available to edit under Tools - Modify Keyboard Shortcuts.
Rstudio version 1.1.456.


text:
Q: Text area not showing resize cursor when hover on corner Hi I have small css issue with my text-area inside react component. It is not show resizable cursor when hover on right bottom corner as it should show in normal case. How can I fix this issue please?
Here is my simple sandbox:
https://codesandbox.io/s/throbbing-moon-oxzpp?file=/src/App.js
Thx for any help


text:
Q: Using StateRestoreListener with Spring Cloud Kafka Streams binder I'm going to use StateRestoreListener with Spring Cloud Kafka Streams binder.
I need to monitor the restoration progress of fault-tolerant state stores of my applications.
There is example in confluent https://docs.confluent.io/current/streams/monitoring.html#streams-monitoring-runtime-status .

In order to observe the restoration of all state stores you provide
  your application an instance of the
  org.apache.kafka.streams.processor.StateRestoreListener interface. You
  set the org.apache.kafka.streams.processor.StateRestoreListener by
  calling the KafkaStreams#setGlobalStateRestoreListener method.

The first problem is getting the Kafka Streams from the app. I solved this problem with using
StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean("&stream-builder-process", StreamsBuilderFactoryBean.class);
KafkaStreams kafkaStreams = streamsBuilderFactoryBean.getKafkaStreams();

The second problem is setting StateRestoreListener to KafkaStreams, because I get error

java.lang.IllegalStateException: Can only set
  GlobalStateRestoreListener in CREATED state. Current state is: RUNNING

Is it possible to use StateRestoreListener in Spring Cloud Kafka Streams binder?
Thanks

A: You can do that by using a StreamsBuilderFactoryBeanCustomizer that gives you access to the underlying KafkaStreams object. If you are using binder versions 3.0 or above, this is the recommended approach. For e.g., you can provide the following bean in your application and customize it with the GlobalStateRestoreListener.
@Bean
public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
    return factoryBean -> {
        factoryBean.setKafkaStreamsCustomizer(new KafkaStreamsCustomizer() {
            @Override
            public void customize(KafkaStreams kafkaStreams) {
                kafkaStreams.setGlobalStateRestoreListener(...);
            }
        });
    };
}

This blog has more details on this strategy.


text:
Q: How to namespace coffeescript in a Rails project In my Rails project, in which I am using Coffeescript, I want to be able to do something like this in a view:
f.text_area :content, :size => "77x4", :oninput => 'Helpers.expandTextarea(300)'

This would call a coffeescript function that would expand the textarea when required. My problem is that I can't seem to properly namespace the coffeescript to get this to work. I tried to do it like this
# site.js.coffee
Helpers =
  expandTextarea: ->
    alert "function found!"

This doesn't work. Trying to call Helpers in the browser console will throw an undefined error. My question is this:
What code would I use in site.js.coffee to achieve the namespacing I want?

A: You could manually put Helpers into the global namespace:
window.Helpers =
  expandTextarea: ->
    alert "function found!"

Then you should be able to say Helpers.expandTextarea(300) anywhere you want. Assuming, of course, that site.js.coffee is included on every page.
CoffeeScript files are wrapped in functions by default:
(function() { /* compiled CoffeeScript goes here */ })();

to avoid polluting the global namespace. You can supply options to the CoffeeScript compiler to not wrap like this but you're better off explicitly putting global things into window.


text:
Q: How do i add a WAIT in a Web Performance Test loop? Writing a Web Performance Test for a process that will run for an undetermined time, and have to put a refresh command in a while that runs until the process state indicates it is done.
The refresh command consumes about 3 seconds. so do not want it running constantly in the loop. So, am trying to find a sleep/wait function to stop the execution between loops.
The only reference i've found is for Thread.Sleep which seems to do the job.
BUT, this method seems to also stop the test's timers. so, however many times the loop runs, and whatever the actual time taken by the process, the test report will only show the cumulative time of the refresh statements.
Is there another method that will not stop the test's timers?

A: If the refresh is in a loop within the Web Performance Test then set a suitable "think time" on the request. This will pause the test after the response is received. (Think times are normally used to simulate the time a person spends reading a web page and filling in forms etc before the next request is issued.)
Think times are set via the properties of the request. Think times (also reporting names) for all requests in a test can be viewed and modified using the "Set request detail" command accessed using the (rightmost) command icon in eth web test editor.
Think times can also be set or adjusted in the PreRequest method of a WebTestRequest plugin.


text:
Q: Bibliographic entries contained in second file not found For the following:
\usepackage[notes,isbn=false,url=false,backend=biber]{biblatex-chicago}

\addbibresource{main.bib}
\addbibresource{secondary.bib}

There are four entries in the first file and two in the second.  Biber doesn't seem to be able to find any of the entries in the second bib file, although it reports a total of 6 keys.  Note the absence of any reference to secondary.bib
INFO - This is Biber 0.9.9
...
INFO - Found 6 citekeys in bib section 0
INFO - Processing bib sectiong 0
INFO - Looking for bibtex format file 'main.bib' for section 0
INFO - Decoding LaTeX character macros into UTF-8
INFO - Finished Decoding LaTeX character macros into UTF-8
INFO - Found BibTeX data source 'main.bib'
INFO - Looking for bibtex format file 'main.bib' for section 0
WARN - I didn't find a database entry for 'source1' (section 0)
WARN - I didn't find a database entry for 'source2' (section 0)
INFO - Overriding locale 'en_US.UTF-8' default tailoring 'level = 4' with 'level = 2'
INFO - Sorting list 'MAIN' keys
INFO - No sort tailoring available for locale 'en_US.UTF-8'
INFO - Overriding locale 'en_US.UTF-8' default tailoring 'level = 4' with 'level = 2'
INFO - Sorting list 'SHORTHANDS' keys
INFO - No sort tailoring available for locale 'en_US.UTF-8'
...
INFO - WARNINGS: 2

If it matters, I am using TexPad
EDIT
bcf:
  <bcf:bibdata section="0">
    <bcf:datasource type="file" datatype="bibtex">main.bib</bcf:datasource>
    <bcf:datasource type="file" datatype="bibtex">secondary.bib</bcf:datasource>
  </bcf:bibdata>
  <bcf:section number="0">
    <bcf:citekey>main1</bcf:citekey>
    <bcf:citekey>main2</bcf:citekey>
    <bcf:citekey>main3</bcf:citekey>
    <bcf:citekey>main4</bcf:citekey>
    <bcf:citekey>source1</bcf:citekey>
    <bcf:citekey>source2</bcf:citekey>
  </bcf:section>

A: This seems to be a bug of your Biber. Since the current version of Biber is 1.5, try first of all upgrading your TeX distribution to the latest snapshot.
Since you're using MacTeX, ensure you have installed the 2012 version and run "TeX Live Utility" that you find in /Applications/TeX. Update all the available packages and the problem should disappear.


text:
Q: Function in React ES6 class doesn't change state class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      generations: 0,
      rows: 30,
      cols: 30,
      isGoing: false,
      speed: 500,
      gameField: []
    }

    this.generateGameField()
  }

  generateGameField() {
    var result = [];
    for (let i = 0; i < this.state.rows; i++) {
      result[i] = [];
      for (let j = 0; j < this.state.cols; j++) {
        result[i][j] = Math.round(Math.random());
      }
    }
    console.log(result)
    this.setState({ gameField: result })

  }

  render() {
    return (
      <button onClick={() => console.log(this.state)}>Click me</button>
    )
  }

}

ReactDOM.render(
  <Main />,
  document.body
)

Please help me. Function generateGameField supposed to create new array and fill it with 0 or 1. The function actually create array, but doesn't change state. Within the function I have access to the state, so I just don't know what went wrong

A: It seems to me you are trying to initialize the component. If that's what you want to achieve then you should use the react life cycle method; componentWillMount.
So to fix the bug, rename generateGameField function to componentWillMount and reorganize the code as below:
  class Main extends React.Component {
     constructor(props) {
       super(props);
     }

     componentWillMount() {
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result)
       this.setState({
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       })

     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)

This what I found in the react official documentation:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.

Abiding by that the above code could be modified to:
  class Main extends React.Component {
     constructor(props) {
       super(props);
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result);
       this.state = {
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       };
     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)


text:
Q: Displaying circle on a specific Latitude and Longitude in d3 map I am using a .svg file for plotting India map. It is displaying India map as desired.
Now I want to display circles on this map using latitude and longitude.
How can I draw circles by using places array? Any source code and web link would be appreciated.
My index.html code is as like below and the svg file I am using is here.
The final output of my script is here.
** Please also guide me, is this the correct way of displaying map?
    <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="d3.v3.min.js"></script>
        <style type="text/css">
        </style>
    </head>

    <body>
        <script type="text/javascript">
            var places = [
              {
                name: "GUNA",
                location: {
                  latitude: 24.5429,
                  longitude: 77.1032
                }
              },
              {
                name: "THE DANGS",
                location: {
                  latitude: 20.4633,
                  longitude: 73.4646
                }
              }
            ]

            d3.xml("toilet.svg", function(xml) {
                var x = document.importNode(xml.documentElement, true);
                document.body.appendChild(x)
            });
        </script>
    </body>
</html>


text:
Q: Scheme: advise on implementation of flatten My implementation of flatten looks like this:
(define flatten
  (lambda (lst)
    (if (null? lst)
        lst
        (append
          (rtn-lst (car lst))
          (flatten (cdr lst))))))

(define rtn-lst
  (lambda (lst)
    (cond
      ((null? lst)
        empty)
      ((atom? lst)
        (list lst))
      (else
        (flatten lst)))))

While standard implementation is:
(define (flatten lst)
  (cond
    ((null? list)
      empty)
    ((list? (car lst))
      (append (flatten (car lst)) (flatten (cdr lst))))
    (else
      (cons (car lst) (flatten (cdr lst))))))

Apart from the obvious verboseness, what else is wrong with my code?

A: I'd try this:
(define rtn-lst
  (lambda (lst)
    (cond
      ((list? lst)
        (if (null? lst)
            empty
            (flatten-list lst)))
      ((atom? lst)
        (list lst))
      (else
        (flatten-list lst)))))

Probably we have different implementations of Scheme.
EDIT:
With modified else branch:
(define rtn-lst
  (lambda (lst)
    (cond
      ((list? lst)
        (if (null? lst)
            empty
            (flatten-list lst)))
      (else
        (list lst)))))

A: I would consider atom? to be wrong. You want to know if the lst is a list, so use list?. atom? can return false on vector or string for some implementations. But i do not know for sure. The rest is quit good.

A: How about something like this:
(define foo
  (lambda (e)
    (cond ((pair? e) `(,@(foo (car e)) ,@(foo (cdr e))))
          ((null? e) '())
          (else (list e)))))

Where for example:
> (foo '(((2 3) (4 . 5) 8)))
(2 3 4 5 8)

Does this do what you want?

A: How about something like this:
(define (flatten x y)
    (if (null? x)
        y
        (if (list? (car x))
            (flatten (append (car x) (cdr x)) y)
            (flatten (cdr x) (append y (list (car x)))))))
(define (flat x)
    (flatten x '()))

> (flat '(1(2(3(4(5)6)7)8)9))
(1 2 3 4 5 6 7 8 9)

and closure version:
(define (flatten x)
        (define (flatten x y)
            (if (null? x)
                y
                (if (list? (car x))
                    (flatten (append (car x) (cdr x)) y)
                    (flatten (cdr x) (append y (list (car x)))))))
        (flatten x '()))

> (flatten '(1(2(3(4(5)6)7)8)9))
(1 2 3 4 5 6 7 8 9)


text:
Q: How work the jquery oriented object? I don't understand how work an object with Jquery/javascript.
And how create a private method/variable with? i see on the forum a closure but i have try and not work. And how see if the method/variable is private? because when I run the website, I see always the function and variable with the own value into my script...
Thanks for your help :).
By e.x:
var ClassName=function()
{
    validation : 0,
    name : 0,
            privateVar: 0,
    init : function ()
    {
        validation = 1;
        name ="toto";
    }
    privatefunction :function()
    {
        alert("a private function");
    }
};

A: Heres one of the multiple ways to have OOP in Javascript
var ClassName = function(){
    var privateVar = 0;

    function privateFunction(){
            alert("a private function");
    }

    return {
        validation : 0,
        name : 0,
        init : function (){
                validation = 1;
                name ="toto";
        }
    };
};

var myClass = ClassName();
myClass.name = "Foo";
myClass.init();

Javascript is not Class based, but prototype based. There are not class**, but instances that can be decorated or used as template to build new instances.  This code I have write here have all the proporties of a Class, but is just a instance.
** this is a lie


text:
Q: P5.js how to do 8 directional lerp color/color change? A last issue i have in this code is that i am not sure how to create color change effect as 8 directional.
I can only map a mouseX to make it lerpColor horizontally or vertically .
But how do i make it work through moving both mouseX and mouseY?
I had it in shift_Color method within the class. I tried to state that within a certain dist(), lerpColor. But now it only showing black color rather than the changing color effect.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.gap = 110
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    //fill(this.shift1);
    this.shift_Color();
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.shift1 = color(96);
      this.shift2 = color(244);
      this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
      this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
      fill(this.change);
    } else {
      fill(this.shift1);
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.attract = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.attract);
      rotateY(this.attract);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}

A: If I understood your question properly, there are two problems in your code.
The first is the fact that because you are trying to map the distance between mouse and the cube to number between 0 and 1, you should write lerpColor(this.shift2, this.shift1, this.shiftX) instead of lerpColor(this.shift1, this.shift2, this.shiftX), since this.shift2 is the lighter color and will be the inner color.
Another problem is when mapping the change variable, change should be calculated based on the distance between mouse and the cube (which is the distance variable), not mouseX or mouseY. Solution is to simply do map(distance, 0, this.gap, 0, 1);.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let cube of cubes) {
    cube.update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.gap = 110
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    //fill(this.shift1);
    this.shift_Color();
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.shiftX = map(distance, 0, this.gap, 0, 1);
      // this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
      this.change = lerpColor(this.shift2, this.shift1, this.shiftX);
      // this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
      fill(this.change);
    } else {
      fill(this.shift1);
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.attract = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.attract);
      rotateY(this.attract);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

I also modified some of your code. Like the line
this.shift1 = color(96);
this.shift2 = color(244);

which is not needed currently since neither of these variable changes during execution.


text:
Q: Image in box table I want put image in box, right before text I use this code but image goes up or down !

      Download link

      [xfgiven_download] [xfgiven_name] [xfvalue_name] [/xfgiven_name]	[/xfgiven_download]

A: Your structure has tag closing mistakes. Compare your structure with below structure.

      Download link

       [xfgiven_download]
        [xfgiven_name] [xfvalue_name] [/xfgiven_name][/xfgiven_download]

A: Add the style "float:left" to your image tag to align it with the text side by side.
your HTML should become something like;

        Download link

            [xfgiven_download] [xfgiven_name] [xfvalue_name]
                [/xfgiven_name]
        	[/xfgiven_download]

Hope it helps!


text:
Q: C# SQLDataReader accessing by column name I have a Visual Basic application where I have a connection to a MS SQL database.  I have code which defines a SqlDataReader, opens the connection, and executes the ExecuteReader() command.  I use the following code to retrieve the data from the reader
While myDataReader.Read()
    Session("menu_PEO") = myDataReader("menu_PEO")
    Session("menu_Transfer") = myDataReader("menu_Transfer")
    Session("menu_Loan") = myDataReader("menu_loan")
End While

menu_PEO, menu_Transfer, and menu_loan are 3 of the column headings in the data that the SQL returns.
I am now tasked with converting the code to c#.  I have the following code in c# which works:
while (dataReader.Read())
{
    dbMenuPEO = dataReader.GetString(1);
    dbMenuTransfer = dataReader.GetString(2);
    dbMenuLoan = dataReader.GetString(3);
}

Since my SQL is a SELECT *, I can not guarantee the order of the data being returned so I dont want to rely on specifying the instance of the GetString.
Is there a way in c# to specify the column name that I would like to retrieve similar to the way it works in Visual Basic?
Thanks!

A: There are two ways to do this. The easy way is to use the named indexer:
dbMenuPEO = (string)dataReader["menu_PEO"];

Which is essentially the same as:
dbMenuPEO = (string)dataReader.GetValue(dataReader.GetOrdinal("menu_PEO"));

You can move the ordinal lookup outside of the loop, which is a bit more efficient. You can also use the the strongly-typed accessor which avoids the cast. This can be important when reading value types (int, dateTime, etc) as it avoid needing to box the value, which would happen with GetValue.
var menuPeoIdx = dataReader.GetOrdinal("menu_PEO");
while(dataReader.Read())
{
   dbMenuPEO = dataReader.GetString(menuPeoIdx);
}

Generally, you should never use select * in a production system. Always explicitly list the columns you want. The reason is that it allows the underlying tables to change without having to fix the consuming code, or over-selecting columns that you don't need. Select * is a great tool for "exploring" a data set, but should only be used as a dev tool.

A:
I have code which defines a SqlDataReader, opens the connection, and executes the ExecuteReader()

And isn't it the most incredibly tedious code to have to write? Many people have thought this over the time and many things have been invented to relieve you of the tedium of it. MarkPflug's answer directly addresses your question, but just in case you aren't aware that there are significant productivity boosts available I'd like to introduce you to one of these technologies

Is there a way in c# to specify the column name that I would like to retrieve similar to the way it works in Visual Basic?

Here's a way to do it, in that when you do this you don't have to type it. It avoids typing the same thing again that you've already typed (twice - once for the variable name, once in the SQL)
Use the nuget package manager built into visual studio, to install Dapper
Then lets say you have a class that holds your data:
//C#
record DbMenu(string DbMenuPEO, string DbMenuTransfer, string DbMenuLoan);

'or VB, if you like that sort of thing
Class DbMenu
  Public Property DbMenuPEO as String
  Public Property DbMenuTransfer As String
  Public Property DbMenuLoan As String
End Class

You can get Dapper to make your query, add any parameters, open your connection, download your data, fill up a list full of your classes, close the connection and return it.. all in one line of code:
//C#
using var conn = ... //code here that gets a connection; doesn't need to be open
var myListOfDbMenus = conn.Query<DbMenu>("SELECT * FROM ... ");

'VB
Using conn = ...
  Dim myListOfDbMenus = conn.Query(Of DbMenu)("SELECT * FROM ... ");
End Using

The short short version is: your c# class properties should be named the same as your columns. If they aren't, it's easiest to use AS xyz in the SQL to equalize the names. If you want to write a parameterized query, you provide @parameterNames that are the same as the property names of an anonymous object you pass at the same time as your query:
var q = conn.Query<Type>("SELECT ... WHERE col = @val1", new {val1 = "hello" } );

If you like writing SQL and having that low level control/don't want to use an ORM like EF, then Dapper lets you carry on doing the SQL directly as you're doing, but takes away all the repetitive surrounding boilerplate

A: The SQLDataReader class exposes a set of instance methods that allow to retrieve the value of a field of a specific type, such as GetInt32() and GetString(), which can be used in combination with the GetOrdinal() method
Example
dataReader.GetString(dataReader.GetOrdinal("YOUR FIELD NAME HERE"))


text:
Q: How to include and link libraries to Octave C++ Dynamically Linked Functions? I have an octave DLD function say main.cpp which calls several functions declared and defined(in .h and .cpp files resp) in the directory mathlib/ which is in the same location as main.cpp.
I'm referring to this octave documentation page for compile options for including and linking libraries
I'm getting the following errors:
>> mkoctfile -Imathlib \ main.cpp
g++: warning:  main.cpp -o <PATH>\AppData\Local\Temp/oct-uoZEQc.o: linker input file unused because linking not done
g++: error:  main.cpp -o <PATH>\AppData\Local\Temp/oct-uoZEQc.o: linker input file not found: Invalid argument
error: mkoctfile: building exited with failure status

What are the other compile options and steps needed to get the linking to work and compile main.cpp successfully?


text:
Q: When I convert an email to html in c# the formatting on the email changes I'm currently working on an equipment return eform, people input the equipment they're returning and when they click submit an email is sent to them and the equipment return team. I've also added a function where by when submit is clicked the programme accesses a database and brings up all the equipment that user still has yet to return. It then adds a grid view of the equipment they have yet to return to the email. To make the grid view show up on the email i had to convert the email to html, but when it does this it ruins the formatting of the email and puts it into one big paragraph instead of a few lines e.g.
(how I want it)
Hello
Bob Johnson has returned a laptop to Steve Johnson on the 28th of may
They also have these items taken out:
(How it comes out)
Hello Bob Johnson has returned a laptop to Steve Johnson on the 28th of may
They also have these items taken out:
below I have included the c# method I've used to send the email
  }
    protected void emailconfirmation(ObjectClass obIn_survey);
  try
        {
            s_Body += " Hello" + " \n\n" +
       "*************** \n" +
       ob_survey.ob_Name + " " + "has Returned a" + " " + ob_survey.ob_Description_of_Equipment + " " + ob_survey.ob_asset_number + " " + "to" + " " + ob_survey.ob_Returned_To + " " + "(Charger returned, " + ob_survey.Return_Charger + ")" + " on" + " " + ob_survey.ob_Date_of_Return.ToShortDateString() + " " + " \n\n" +
       " \n\n" + "Regards" + " \n\n" + "RCI Team" + " \n\n" + "This User also has the current Item(s) taken out";

            s_GridView = GetGridviewData(gv_Equipment);

            utility.Email_GenericMessage("RCITeam@rotherham.gov.uk", ob_survey.ob_Email_Receipt_to + ",RCITeam@rotherham.gov.uk", "Equipment Return", s_Body + s_GridView);

            edited the above line

        }
        catch (Exception)
        {

            throw;
        }

Here is the method in the utility class
  public void Email_GenericMessage(String sIn_EmailFrom, String sIn_Emailto, String sIn_Subject, String sIn_Body )
    {
        using (MailMessage msg = new MailMessage(sIn_EmailFrom, sIn_Emailto, sIn_Subject, sIn_Body ))
        {
            msg.IsBodyHtml = true;
            using (SmtpClient clt = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]))
            {
                clt.Send(msg);
            }
        }

Can anyone help? Thanks

A: Use .html layout and placeholder for creating emails.
It's most ease and correct way.
        <!DOCTYPE html>

        <meta charset="utf-8" />

        <title></title>

{{NameFirst}}

{{NameSecond}}

{{Price}}

{{InvoiceNumber}}

    string forReplace = "{{" + prName + "}}";

    if (res.Contains(forReplace))
    {
        var prValue = item.GetValue(obj);

        res = res.Replace(forReplace, prValue.ToString());
    }

A: This seems like it could be solved with a string replace.  Have you tried s_Body.replace("\n", "
");? Since the message html new lines are represented as
 instead of \n.


text:
Q: Adding a new column to a matrix conditional on the values in the other columns I have this dataset
data
     [C1]  [C2] [C3] [C4] [C5] [C6] [C7] [C8]
[1,]    5    1    2    1    4    2    1   NA
[2,]    4    1    3    4    1    1   NA    2
[3,]    3    4    6    7    1    1    2    2
[4,]    1    3   NA    1   NA    2   NA   NA
[5,]    1    NA   5   NA   NA    4    1    2
[6,]    1    4   NA   NA   NA    4    1    2
[7,]    1    4   NA   NA   NA    4    1    2

I want to add new column C9 which could take two values 1 (True) if the corresponding row has the value 1 in columns C2 ,C3 or C4 or 0 (False) otherwise.
I have tried this code
C9<-data[,2:4]==1
#change the logical matrix into numeric
C9<-C9*1
#convert the matrix into vector #
C9<-rowSums(C9)
data=cbind(data,C9)

The code works well but consumes more time so  my question is there a unique way to do that , since  I am beginner in R ?.

A: If I understand the question correctly, C9 must be 1 if one of C2, C3, or C4 is exactly 1, 0 otherwise. So the solution has to deal with NAs.
This compares three approaches:
f.1 <- function() (rowSums(data[,2:4]==1, na.rm=TRUE)>0)*1L
f.2 <- function() {x<-rep(0L,nrow(data)); x[(data[,2]==1 | data[,3]==1 | data[,4]==1)]<-1L; x}
f.3 <- function() apply(data[,2:4], 1, function(x) any(x==1, na.rm=T))*1L
library(microbenchmark)
microbenchmark(f.1(),f.2(),f.3(), times=1000)
# Unit: microseconds
#   expr    min     lq      mean  median       uq       max neval cld
#  f.1() 11.845 15.991  20.76593  18.952  22.5050   293.751  1000  a
#  f.2() 10.660 14.806  44.43363  17.768  20.7290 25063.000  1000  a
#  f.3() 81.137 91.797 121.80148 103.050 125.8515  2719.566  1000   b

identical(f.1(),f.2())
# [1] TRUE
identical(f.1(),f.3())
# [1] TRUE

f.1() is your approach (more or less), f.2() is a very simple and direct approach, and f.3() is from the comment. As you can see, the simple/direct approach is fastest in this case, but just by a few percent.
Why do you think this is too slow?


text:
Q: delete a column with a certain % 0 I'm a newbie to R and I have a dataframe called pedM with 203 rows and 19 columns and I wanted to code a line to delete then columns that returned mostly a value of 0 in the dataframe (say, 98% of the column is 0).
I'm using the dataframe to output a heatmap which returns an image based on gene expression, and I want to get rid of the lines that have outliers that don't really contribute to the data.
I imagine the line of code I'm looking for is fairly simple, but I can't wrap my head around the correct way to do it. Just to reiterate, looking for a line that would basically remove a column from a dataframe that has 98% 0's or 2% nonzero's, whichever way is easier.
Thanks in advance.
Vivek

A: I like to do this in a few steps for clarity.  First define a function that checks a vector for 98% zeros and returns True or False:
myfun <- function(x, threshhold=0.98) {
  if(length(x[x==0])/length(x) > threshhold) {
    TRUE
  } else {
    FALSE
  }
}

Then create a boolean vector for each column using apply:
to.drop <- apply(pedM, 2, myfun)

Finally drop the columns you don't want:
pedM <- pedM[, !to.drop]


text:
Q: Query XML [SAML 2.0 Response] The below xml is causing me difficulty. I need to retrieve the following from the XML with c#, can you please help? Also is there a better way of reading/parsing SAML 2.0 response in c#?

*

*status code from <samlp:StatusCode value="urn:oasis:names:tc:SAML:2.0:status:**Success**"/>

*FIRSTNAME Value

*LASTNAME Value

*MAIL Value

*Issuer from   <saml:Issuer>**sso.localhost.dev**</saml:Issuer>

*Audience from  <saml:Audience>**Application-Test**</saml:Audience>
XML
    <samlp:Response Destination="http://localhost/SamlAuthenticate" IssueInstant="2014-03-27T14:49:35.395Z" ID="kBWlU3VWF.Ee6DKbkEpFomtlDAT" Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">sso.localhost.dev</saml:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#kBWlU3VWF.Ee6DKbkEpFomtlDAT"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>LgH7ZZJWwp5fN02IPteWxh9oAQ8=</ds:DigestValue></ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>gBCZ4upHHdYzrVUcTe4Nf+fElY51UFQOJcf81DFPFNKfFxZfLjnX88NwJ6O7CVU3YNo08EINoEpkvEu+f2oxI3VQVnYnT1EYpLGy1+6qpxsFaPbXaQ8h1/NCwAygir1NDu/sktAzRZ2tg2i5rVn2sevY3Y+47SKnB+hG4ukVHusmNumD0NXyKwKNPflG9XEhrLj3bw5xuftr5CAREX5s1VotANFs1HeJA7OE1Yq2yLhw7GmPsa1+fgYQh5tfFRCmvdnpVoiT+SXwoxlRSbWlf2BWgBOLbC8W4dhTpMFmp70lndk0Pwpnxj6z4jFAHT3z/SdGgm0Ow+TbuutceBIIAQ==</ds:SignatureValue>
</ds:Signature>
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<saml:Assertion Version="2.0" IssueInstant="2014-03-27T14:49:35.404Z" ID="w4BForMipBizsG1TA7d9QzhCM0-" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Issuer>sso.localhost.dev</saml:Issuer>
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">JSMITH009</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2014-03-27T14:54:35.404Z" Recipient="http://localhost/SamlAuthenticate"/></saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotOnOrAfter="2014-03-27T14:54:35.404Z" NotBefore="2014-03-27T14:44:35.404Z">
<saml:AudienceRestriction>
<saml:Audience>Application-Test</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2014-03-27T14:49:35.404Z" SessionIndex="w4BForMipBizsG1TA7d9QzhCM0-">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
<saml:AttributeStatement xmlns:xs="http://www.w3.org/2001/XMLSchema">
<saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="FIRSTNAME">
<saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">john</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="MAIL">
<saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">john.smith@email.localhost.dev</saml:AttributeValue></saml:Attribute>
<saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="LASTNAME"><saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">smith</saml:AttributeValue></saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>

A: Got the solution!
public class SAMLProcessor
{

    #region Properties
    public string DecodedSAML { get; set; }
    public string EncodedeSAML { get; set; }
    public string Audience { get; set; }
    public string SubjectNameID { get; set; }
    public string FirstName { get; set; }
    public string Mail { get; set; }
    public string LastName { get; set; }
    public bool AuthenticationStatus { get; set; }
    public string Issuer { get; set; }
    public string Destination { get; set; }
    public string ResponseID { get; set; }
    public bool VerifiedResponse { get; set; }
    public string SignatureValue { get; set; }
    public string SignatureReferenceDigestValue { get; set; }
    public DateTime AutheticationTime { get; set; }
    public string AuthenticationSession { get; set; }
    #endregion

    #region Ctror
    public SAMLProcessor(string rawSamlData)
    {
        EncodedeSAML = rawSamlData;
        // the sample data sent us may be already encoded,
        // which results in double encoding
        if (rawSamlData.Contains('%'))
        {
            rawSamlData = HttpUtility.UrlDecode(rawSamlData);
        }

        // read the base64 encoded bytes
        string samlAssertion = Decode64Bit(rawSamlData);
        DecodedSAML = samlAssertion;
        SamlParser(DecodedSAML);
    }
    #endregion

    private static string Decode64Bit(string rawSamlData)
    {
        byte[] samlData = Convert.FromBase64String(rawSamlData);

        // read back into a UTF string
        string samlAssertion = Encoding.UTF8.GetString(samlData);
        return samlAssertion;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="samldata"></param>
    /// <returns></returns>
    public string SamlParser(string samlXMLdata)
    {

        //samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata;
        string samldata = samlXMLdata;

        if (!samldata.StartsWith(@"<?xml version="))
        {
            samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata;
        }

        string firstName = string.Empty;
        XmlDocument xDoc = new XmlDocument();
        samldata = samldata.Replace(@"\", "");
        xDoc.LoadXml(samldata);
        //xDoc.Load(new System.IO.TextReader());//Suppose the xml you have provided is stored in this xml file.

        XmlNamespaceManager xMan = new XmlNamespaceManager(xDoc.NameTable);
        xMan.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
        xMan.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
        xMan.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

        XmlNode xNode = xDoc.SelectSingleNode("/samlp:Response/samlp:Status/samlp:StatusCode/@Value", xMan);
        if (xNode != null)
        {
            this.AuthenticationStatus = false;
            string statusCode = xNode.Value;
            if (statusCode.EndsWith("status:Success"))
            {
                this.AuthenticationStatus = true;
            }

        }

        xNode = xDoc.SelectSingleNode("/samlp:Response/@Destination", xMan);
        if (xNode != null)
        {
            this.Destination = xNode.Value;
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/@IssueInstant", xMan);
        if (xNode != null)
        {
            this.AutheticationTime = Convert.ToDateTime(xNode.Value);
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/@ID", xMan);
        if (xNode != null)
        {
            this.ResponseID = xNode.Value;
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Issuer", xMan);
        if (xNode != null)
        {
            this.Issuer = xNode.InnerText;
        }

        xNode = xDoc.SelectSingleNode("/samlp:Response/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue", xMan);
        if (xNode != null)
        {
            this.SignatureReferenceDigestValue = xNode.InnerText;
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/ds:Signature/ds:SignatureValue", xMan);
        if (xNode != null)
        {
            this.SignatureValue = xNode.InnerText;
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/@ID", xMan);
        if (xNode != null)
        {
            this.AuthenticationSession = xNode.Value;
        }

        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:Subject/saml:NameID", xMan);
        if (xNode != null)
        {
            this.SubjectNameID = xNode.InnerText;
        }
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:Conditions/saml:AudienceRestriction/saml:Audience", xMan);
        if (xNode != null)
        {
            this.Audience = xNode.InnerText;
        }

        //reverse order
        //</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion></samlp:Response>

        //string xQryStr = "//NewPatient[Name='" + name + "']";

        //XmlNode matchedNode = xDoc.SelectSingleNode(xQryStr);
        // samlp:Response  saml:Assertion saml:AttributeStatement saml:Attribute
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'FIRSTNAME']/saml:AttributeValue", xMan);
        if (xNode != null)
        {
            this.FirstName = xNode.InnerText;
        }

        // samlp:Response  saml:Assertion saml:AttributeStatement saml:Attribute
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'MAIL']/saml:AttributeValue", xMan);
        if (xNode != null)
        {
            this.Mail = xNode.InnerText;
        }

        // samlp:Response  saml:Assertion saml:AttributeStatement saml:Attribute
        xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'LASTNAME']/saml:AttributeValue", xMan);
        if (xNode != null)
        {
            this.LastName = xNode.InnerText;
        }

        return this.FirstName;
    }
}

A: If you just want to parse the XML, you can load it into an XElement.
You can also use the Saml2Response class of the Kentor.AuthServices package to parse and validate the response.


text:
Q: Error: invalid_request Invalid parameter value for redirect_uri: Uri must consist of printable ASCII characters: I Created Client Id and API Key in the Google Developer Console, I given same url in google console and in my config file
This is my url:
https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A81%2Fmoviemuseui%2Fpublic%2Flogin%2FcheckLogin+&client_id=XXXXXXXX-xxxxxxxxxxxxxxxxx.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&approval_prompt=force
I am getting a error

*That's an error.

Error: invalid_request
Invalid parameter value for redirect_uri: Uri must consist of
printable ASCII characters:
localhost:81/moviemuseui/public/login/checkLogin

How to solve this, I can't find the problem.

A: Your redirect uri must NOT contain space " "

A: Excluded US-ASCII Characters disallowed within the URI syntax:
   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

There are also some characters that may be allowed in URI syntax but can cause problems.
"{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

And the following characters are absolutely reserved for a query component and they are used for specific meaning in the protocol.
";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

A: You don't need to url encode everything.  The first call to for authentication just displays a page to your users for them to approve your access.  It is a normal HTTP GET you can test it in any webbrowser.
The following works:
https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&response_type=code
This one adds your redirect uri, remember redirect uri should point to the page where you would like to handle authentication.
https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=http:// localhost:81/moviemuseui/public/login/checkLogin/Filename.php&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&response_type=code
I have a tutorial that explains how the calls should be put together: Google 3 legged oauth2 flow
Question: If you are using the Google-api-php-client why are you building this manually?
Your error Redirect_URI: must match the page where you would like to handle the authentication. For example:  http:// localhost/google-api-php-client-samples/oauth2.php
It should be set in the developer console, and used in your script.

A: Just check if the URI does not contains any spaces. I too had the same problem and was resolved by deleting the spaces at the end.


text:
Q: need help in asp.net content page Somebody please help me how to place the content page in  center of the page.I am trying to do using css class but content doesn't have css property.In my application when i am clicking on LOGIN DETAILS , that page should open in the center but opening under the menu item.
Here is my code:

A: As the other posters have said, you will need to use CSS to position the div in the center of the screen.
Here's some quick code to help you with this.
div#centered {
    background-color: #eee;
    border: 1px solid #ddd;
    position: absolute;
    left: 50%;
    top: 50%;
    width: 400px;
    height: 300px;
    margin-left: -200px;
    margin-top: -150px;
}

And it's usage:

A: The auto value on the left and right margins work to center the div horizontally.  Unfortunately this doesn't work vertically, so you may need to set this manually or detected the screen resolution dynamically.

..login form here


text:
Q: Magento 2: Bug or developer mode issue I am facing the issue with  Magento ver. 2.1.6. When I am login still showing me log in when I click on cart checkout button.
Refresh the browser solved the problem.

Did anyone face the smiler issue?

A: This is the common issue of magento 2.
You can check its in github link,
1. Logged-in user has to re-login before checkout.
2. Login Popup appears while clicking "Proceed to checkout" even after logged in
You can resolved issue by below tricks,

Please enable all cache from admin for developer mode.
Clear Var folder and clear cache.