text:
Q: Objects don't cast shadows on other objects I made a OpenGL program with GLEW and GLFW on Orwell Dev-C++ 5.4.0 which shows blocks. I added ambient, diffuse and specular light and now shadows, too. I used a depth texture. But now, the blocks don't cast shadows on other blocks, rather only on themselves!
This is the important part of my source code:
void createShadows()
{
    int error;

    glGenFramebuffers(1, &buffers.depthFbo);
    glBindFramebuffer(GL_FRAMEBUFFER, buffers.depthFbo);

    glGenTextures(1, &buffers.depthTbo);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, buffers.depthTbo);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, winInfo.winWidth, winInfo.winHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, buffers.depthTbo, 0);
    glDrawBuffer(GL_NONE);

    error = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(error != GL_FRAMEBUFFER_COMPLETE)
        printError("FramebufferError.txt", "Framebuffer", error);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void init()
{
    renderProg = compileShaders("openglSuperTutorials12.vss", "openglSuperTutorials12.fss", 0);
    renderProgDepth = compileShaders("openglSuperTutorials12_depth.vss", "openglSuperTutorials12_depth.fss", 0);

    glGenVertexArrays(1, &buffers.vao);
    glBindVertexArray(buffers.vao);

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    matrices.mMatrixDepth                    = glm::mat4(1.0f);
    matrices.pMatrixDepth                    = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, -10.0f, 20.0f);
    matrices.biasMatrixDepth                 = glm::mat4(0.5f, 0.0f, 0.0f, 0.0f,
                                                         0.0f, 0.5f, 0.0f, 0.0f,
                                                         0.0f, 0.0f, 0.5f, 0.0f,
                                                         0.5f, 0.5f, 0.5f, 1.0f);

    //Initialize light and material properties and give them to the "renderProg" (truncated)

    glfwGetWindowSize(window, &winInfo.winWidth, &winInfo.winHeight);
    glfwSetCursorPos(window, winInfo.winWidth/2.0, winInfo.winHeight/2.0);

    createTexture();
    createVertices();
    createBlocks();
    createShadows();
}

void setBlock(glm::vec3 position, int id, int depth)
{
    if(depth != 1)
    {
        matrices.mMatrix = glm::translate(glm::mat4(1.0f), position);
        matrices.mvpMatrixBiasDepth = matrices.biasMatrixDepth * matrices.mvpMatrixDepth;

        glUniformMatrix4fv(glGetUniformLocation(renderProg, "mMatrix"), 1, GL_FALSE, &matrices.mMatrix[0][0]);
        glUniformMatrix4fv(glGetUniformLocation(renderProg, "mvpMatrixBiasDepth"), 1, GL_FALSE, &matrices.mvpMatrixBiasDepth[0][0]);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, buffers.tbo);
        glUniform1i(glGetUniformLocation(renderProg, "texBlock"), 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, buffers.depthTbo);
        glUniform1i(glGetUniformLocation(renderProg, "shadowMap"), 1);

        glGenBuffers(1, &buffers.tcbo);
        glBindBuffer(GL_ARRAY_BUFFER, buffers.tcbo);
        glBufferData(GL_ARRAY_BUFFER, sizeof(blocks[id]), blocks[id], GL_DYNAMIC_DRAW);
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
        glEnableVertexAttribArray(1);
    }
    else
    {
        matrices.mvpMatrixDepth = matrices.pMatrixDepth * matrices.vMatrixDepth * matrices.mMatrixDepth;
        glUniformMatrix4fv(glGetUniformLocation(renderProgDepth, "mvpMatrixDepth"), 1, GL_FALSE, &matrices.mvpMatrixDepth[0][0]);
    }

    glDrawArrays(GL_TRIANGLES, 0, 36);

    if(depth != 1)
    {
        glDisableVertexAttribArray(1);
        glDeleteBuffers(1, &buffers.tcbo);
    }
}

void display()
{
    int x, y, z;

    GLfloat bgColor[] = { 0.0f, 0.73f, 1.0f, 1.0f };
    GLfloat depthOne = 1.0f;

    glBindFramebuffer(GL_FRAMEBUFFER, buffers.depthFbo);
    glClearBufferfv(GL_DEPTH, 0, &depthOne);
    glUseProgram(renderProgDepth);

    glEnableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);

    if(viewPos.lightSticky == 1)
    {
        lightProperties.lightPosition  = glm::vec3(viewPos.eyeX, viewPos.eyeY, viewPos.eyeZ);
        lightProperties.lightDirection = glm::vec3(viewPos.centerX, viewPos.centerY, viewPos.centerZ);
    }

    matrices.vMatrixDepth = glm::lookAt(
                    lightProperties.lightPosition,
                    lightProperties.lightDirection,
                    glm::vec3(viewPos.upX, viewPos.upY, viewPos.upZ));

    for(z=-5; z<=5; z++)
    {
        for(y=0; y<=6; y++)
        {
            for(x=-5; x<=5; x++)
            {
                if(blockMap[z+5][y][x+5].id != -1)
                    setBlock(blockMap[z+5][y][x+5].position, blockMap[z+5][y][x+5].id, 1);
            }
        }
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClearBufferfv(GL_COLOR, 0, bgColor);
    glClearBufferfv(GL_DEPTH, 0, &depthOne);
    glUseProgram(renderProg);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    lightProperties.cameraPosition = glm::vec3(viewPos.eyeX, viewPos.eyeY, viewPos.eyeZ);

    matrices.vMatrix = glm::lookAt(glm::vec3(viewPos.eyeX, viewPos.eyeY, viewPos.eyeZ),
                                   glm::vec3(viewPos.centerX, viewPos.centerY, viewPos.centerZ),
                                   glm::vec3(viewPos.upX, viewPos.upY, viewPos.upZ));
    matrices.pMatrix = glm::perspective(45.0f, (GLfloat)winInfo.winWidth/(GLfloat)winInfo.winHeight, 0.1f, 1000.0f);

    glUniformMatrix4fv(glGetUniformLocation(renderProg, "vMatrix"),                1, GL_FALSE, &matrices.vMatrix[0][0]);
    glUniformMatrix4fv(glGetUniformLocation(renderProg, "pMatrix"),                1, GL_FALSE, &matrices.pMatrix[0][0]);

    //Update light uniforms (truncated)

    for(z=-5; z<=5; z++)
    {
        for(y=0; y<=6; y++)
        {
            for(x=-5; x<=5; x++)
            {
                if(blockMap[z+5][y][x+5].id != -1)
                    setBlock(blockMap[z+5][y][x+5].position, blockMap[z+5][y][x+5].id, 0);
            }
        }
    }

    glfwSwapBuffers(window);
    winInfo.frames++;
}

The Vertex-Shader "openglSuperTutorials12.vss":
#version 430 core

layout (location = 0) in vec3 vPosition;
layout (location = 1) in vec2 vTexCoord;
layout (location = 2) in vec3 vNormal;

out vec3 fPosition;
out vec4 fShadowCoord;
out vec2 fTexCoord;
out vec3 fNormal;

uniform mat4 mMatrix;
uniform mat4 vMatrix;
uniform mat4 pMatrix;
uniform mat4 mvpMatrixBiasDepth;

void main()
{
    gl_Position = pMatrix * vMatrix * mMatrix * vec4(vPosition, 1.0);
    fPosition = vPosition;
    fShadowCoord = mvpMatrixBiasDepth * vec4(vPosition, 1.0);
    fTexCoord = vTexCoord;
    fNormal = normalize(transpose(inverse(mat3(mMatrix))) * vNormal);
}

The Fragment-Shader "openglSuperTutorials12.fss":
#version 430 core

in vec3 fPosition;
in vec4 fShadowCoord;
in vec2 fTexCoord;
in vec3 fNormal;

out vec4 outColor;

uniform sampler2D texBlock;
uniform sampler2D shadowMap;
uniform mat4 mMatrix;

uniform int   ambientLightEnabled;
uniform int   diffuseLightEnabled;
uniform int   specularLightEnabled;
uniform int   shadowsEnabled;
uniform vec3  ambientLightColor;
uniform vec3  diffuseLightColor;
uniform vec3  specularLightColor;
uniform vec3  lightPosition;
uniform vec3  cameraPosition;
uniform float lightAttenuation;
uniform vec3  spotlightConeDirection;
uniform float spotlightCosCutoff;
uniform float spotlightExponent;

uniform vec3  ambientMaterialColor;
uniform vec3  diffuseMaterialColor;
uniform vec3  specularMaterialColor;
uniform float shininess;
uniform float strength;

void main()
{
    vec3  shadowValue = vec3(textureProj(shadowMap, fShadowCoord));
    vec3  surfacePos = vec3(mMatrix * vec4(fPosition, 1.0));
    vec3  surfaceToLight = normalize(lightPosition - surfacePos);
    vec3  surfaceToCamera = normalize(cameraPosition - surfacePos);

    vec3  ambientColor = ambientMaterialColor * ambientLightColor;

    float diffuseIntensity = max(0.0, dot(fNormal, surfaceToLight));
    vec3  diffuseColor = diffuseIntensity * diffuseLightColor * diffuseMaterialColor;

    float specularIntensity;
    if(diffuseIntensity == 0.0)
        specularIntensity = 0.0;
    else
        specularIntensity = pow(max(0.0, dot(fNormal, normalize(surfaceToLight + surfaceToCamera))), shininess) * strength;
    vec3  specularColor = specularIntensity * specularLightColor * specularMaterialColor;

    float distanceToLight = length(surfacePos - lightPosition);
    float attenuation = 1.0 / (
                    lightAttenuation +
                    lightAttenuation * distanceToLight +
                    lightAttenuation * distanceToLight * distanceToLight);

    vec3  lightColorCombined = vec3(0.0);
    if(ambientLightEnabled == 1)
    {
        lightColorCombined += ambientColor;
    }
    if(diffuseLightEnabled == 1)
    {
        if(shadowsEnabled == 1)
            diffuseColor *= shadowValue;
        lightColorCombined += diffuseColor;
    }
    if(specularLightEnabled == 1)
    {
        if(shadowsEnabled == 1)
            specularColor *= shadowValue;
        lightColorCombined += attenuation * specularColor;
    }

    outColor = texture(texBlock, fTexCoord) * vec4(lightColorCombined, 1.0);
}

The other shaders ("openglSuperTutorials12_depth.vss" and "openglSuperTutorials12_depth.fss") are only simple pass-through shaders with the "mvpMatrixDepth".
A screenshot of the scene
What do I have to change to let the light cast shadows on other objects?


text:
Q: @Transactional not working with @EnableIntegration We have a spring data jpa application in which we are trying to replace a workflow   using "Spring Integration". We are using java configuration. As soon as we add a configuration which has @EnableIntegration, @Transactional stops working and we get errors like:
    org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.kronos.authz.impl.entity.Role.faps, could not initialize proxy - no Session

The application works fine if we remove @EnableIntegration from the configuration.The configuration we are adding is:
@Configuration
@ComponentScan("com.xyz.integration.endPoint")
@IntegrationComponentScan("com.xyz.tenantprovision.integration.endPoint")
@EnableIntegration

public class TenantProvisioningConfig {

@Bean
@Description("Entry to the messaging system through the gateway.")
public MessageChannel incomingProvisioningRequest() {
    return new PublishSubscribeChannel();
}

@Bean
@Description("Sends request messages to the web service outbound gateway")
public MessageChannel activatedChannel() {
    return new DirectChannel();
}

@Bean
@Description("Sends web service responses to both the client and a database")
public MessageChannel requestJsonChannel() {
    return new DirectChannel();
}

@Bean
@Description("Stores non filtered messages to the database")
public MessageChannel acknowledgementChannel() {
    return new DirectChannel();
}
}

The main application configuration is:
@Configuration
@EnableJpaRepositories(basePackages = {"com.xyz"})
@PropertySource("classpath:application.properties")
@EnableTransactionManagement(mode=AdviceMode.PROXY,proxyTargetClass=true)
public class ConfigApplicationContext {
//datasource initialization code etc

}

The stacktrace is:
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [CXFServlet] in context with path [/tenantmanager] threw exception
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.xyz.authz.impl.entity.Role.faps, could not initialize proxy - no Session
        at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
        at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
        at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
        at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
        at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294)
        at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1798)
        at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
        at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
        at java.util.Iterator.forEachRemaining(Iterator.java:116)
        at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
        at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)

EDIT:
As mentioned by @ArtemBilan in comments, this appears to be an "early BeanFactory access syndrome". The flow is
org.springframework.integration.expression.IntegrationEvaluationContextAwareBeanPostProcessor#0 -> org.springframework.transaction.config.internalTransactionAdvisor -> org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration -> metaDataSourceAdvisor , interface org.springframework.aop.Advisor -> methodSecurityMetadataSource
methodSecurityMetadataSource now tries to create a bean in our application which is a configuration extending GlobalMethodSecurityConfiguration. It overrides MethodSecurityExpressionHandler createExpressionHandler(). From here it goes on to access services defined to provide user details. These services have @Transactional annotated methods. These methods when used later in the code give error for not being in Transaction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Textures and no textures at the same time in metal, with multiply blending I'm drawing 2 different vertex buffers in metal, one with a texture (ignoring vertex color data) and the other without a texture (drawing purely the vertex color data):
let commandBuffer = self.commandQueue.makeCommandBuffer()
let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: rpd)

//render first buffer with texture
commandEncoder.setRenderPipelineState(self.rps)
commandEncoder.setVertexBuffer(self.vertexBuffer1, offset: 0, at: 0)
commandEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1)
commandEncoder.setFragmentTexture(self.texture, at: 0)
commandEncoder.setFragmentSamplerState(self.samplerState, at: 0)
commandEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count1, instanceCount: 1)

//render second buffer without texture
commandEncoder.setRenderPipelineState(self.rps)
commandEncoder.setVertexBuffer(self.vertexBuffer2, offset: 0, at: 0)
commandEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1)
commandEncoder.setFragmentTexture(nil, at: 0)
commandEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count2, instanceCount: 1)

commandEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()

The shader looks like this:
#include <metal_stdlib>
using namespace metal;

struct Vertex {
    float4 position [[position]];
    float4 color;
    float4 texCoord;
};

struct Uniforms {
    float4x4 modelMatrix;
};

vertex Vertex vertex_func(constant Vertex *vertices [[buffer(0)]],
                          constant Uniforms &uniforms [[buffer(1)]],
                          uint vid [[vertex_id]])
{
    float4x4 matrix = uniforms.modelMatrix;
    Vertex in = vertices[vid];
    Vertex out;
    out.position = matrix * float4(in.position);
    out.color = in.color;
    out.texCoord = in.texCoord;
    return out;
}

fragment float4 fragment_func(Vertex vert [[stage_in]],
                               texture2d<float>  tex2D     [[ texture(0) ]],
                               sampler           sampler2D [[ sampler(0) ]]) {

    if (vert.color[0] == 0 && vert.color[1] == 0 && vert.color[2] == 0) {
        //texture color
        return tex2D.sample(sampler2D, float2(vert.texCoord[0],vert.texCoord[1]));
    }
    else {
        //color color
        return vert.color;
    }

}

Is this there a better way of doing this? Any vertex that i want to use the texture i'm setting to black, and the shader checks to see if the color is black, and if so then use the texture, otherwise use the color.
Also, is there a way to blend the colored polys and textured polys together using a multiply function if they overlap on the screen? It seems like MTLBlendOperation only has options for add/subtract/min/max, no multiply?

A: Another way to do this would be to have two different fragment functions, one that renders textured fragments and another one that deals with coloured vertices.
First you would need to create two different MTLRenderPipelineState at load time:
let desc = MTLRenderPipelineDescriptor()

/* ...load all other settings in the descriptor... */

// Load the common vertex function.
desc.vertexFunction = library.makeFunction(name: "vertex_func")

// First create the one associated to the textured fragment function.
desc.fragmentFunction = library.makeFunction(name: "fragment_func_textured")
let texturedRPS = try! device.makeRenderPipelineState(descriptor: desc)

// Then modify the descriptor to create the state associated with the untextured fragment function.
desc.fragmentFunction = library.makeFunction(name: "fragment_func_untextured")
let untexturedRPS = try! device.makeRenderPipelineState(descriptor: desc)

Then at render time, before encoding the draw commands of a textured object you set the textured state, and before encoding the draw commands of an untextured object you switch to the untextured one. Like this:
//render first buffer with texture
commandEncoder.setRenderPipelineState(texturedRPS) // Set the textured state
commandEncoder.setVertexBuffer(self.vertexBuffer1, offset: 0, at: 0)
commandEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1)
commandEncoder.setFragmentTexture(self.texture, at: 0)
commandEncoder.setFragmentSamplerState(self.samplerState, at: 0)
commandEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count1, instanceCount: 1)

//render second buffer without texture
commandEncoder.setRenderPipelineState(untexturedRPS) // Set the untextured state
commandEncoder.setVertexBuffer(self.vertexBuffer2, offset: 0, at: 0)
commandEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1)
// No need to set the fragment texture as we don't need it in the fragment function.
// commandEncoder.setFragmentTexture(nil, at: 0)
commandEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: count2, instanceCount: 1)

No change is required for the vertex function. While you need to split the fragment function into two:
fragment float4 fragment_func_textured(Vertex vert [[stage_in]],
                                       texture2d<float>  tex2D     [[ texture(0) ]],
                                       sampler           sampler2D [[ sampler(0) ]]) {
    //texture color
    return tex2D.sample(sampler2D, float2(vert.texCoord[0],vert.texCoord[1]));
}

fragment float4 fragment_func_untextured(Vertex vert [[stage_in]]) {
    //color color
    return vert.color;
}

You could even go ahead and have two different vertex functions that output two different vertex structures in order to save a few bytes. In fact the textured fragment function only needs the texCoord field and not the color, while the untextured function is the other way around.
EDIT: You can use this fragment function to use both the texture color and the vertex color:
fragment float4 fragment_func_blended(Vertex vert [[stage_in]],
                                      texture2d<float>  tex2D     [[ texture(0) ]],
                                      sampler           sampler2D [[ sampler(0) ]]) {
    // texture color
    float4 texture_sample = tex2D.sample(sampler2D, float2(vert.texCoord[0],vert.texCoord[1]));
    // vertex color
    float4 vertex_sample = vert.color;
    // Blend the two together
    float4 blended = texture_sample * vertex_sample;

    // Or use another blending operation.
    // float4 blended = mix(texture_sample, vertex_sample, mix_factor);
    // Where mix_factor is in the range 0.0 to 1.0.
    return blended;

}


text:
Q: C# - Redirect from email body if the link doesn't load within 10 seconds I am sending email from my software which has two ip addresses.
One is real ip and the other one is internal.
When I send the email the url looks something like this:
https://realipaddress/Memo/MemoApproval?att=accept&queryString=%24HASH%24V1%2410000%246wqGezIN1QB6kxmuB47deLWZk4AlBAE8eESVoNx7Bw%2F1%2Bet2
OR,
https://192.168.200.59/Memo/MemoApproval?att=accept&queryString=%24HASH%24V1%2410000%246wqGezIN1QB6kxmuB47deLWZk4AlBAE8eESVoNx7Bw%2F1%2Bet2
I am doing this because my internal wifi doesn't allow the real ip address.
So, whenever some user uses the internal wifi the link becomes the later one.
I want these addresses to be interchanged if the request exceeds 10 seconds.
The link is on email body
Can that be possible? If so, then how do I do that?


text:
Q: Specified platform toolset (v110) is not installed or invalid. Please make sure that a supported PlatformToolset value is selected I'm very new to Visual Studio. I have a project which needs v110 platform tools, so I installed Visual studio 2012, but while building project it throws the error saying:

Specified platform toolset (v110) is not installed or invalid

I even checked "C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\PlatformToolsets", But I found only v90 and v100 folder but not v110 folder.

A: Right Click projectSelect PropertiesSelect Configuration PropertiesPlatform Toolset
When you get to Platform Toolset, click on the v110 value which will be in the right column. You will see a drop down appear which will allow you to select v90, v100, orinherit. Of course, v100 is the correct answer. Once v100 is selected, I don't believe you can back to v110 from within VS 2010. You would have to once again open in in VS 2012 to move it back to v110.
Is the answer of another thread, but I don't know how to link it by mobile app.


text:
Q: Binding a Laravel service provider on specific routes Is there a way to register a service provider in Laravel just for certain routes/URLs? I would like to know if it's possible to bind a service only where you need it and if it helps reduce the strain while booting.

A: I'm not sure that it's possible to register a service provider only on particular routes, however you could defer it. Just set
protected $defer = true;

on your service provider then this will only be resolved when needed which should improve performance depending on your particular use case.
For more check out the official docs on this here but it might just be what you need.


text:
Q: Iterating over a vector of structs and dereferencing the iterator I'm iterating over a vector of structs, and then trying to dereference the iterator. I think I'm missing some bit of logic and doing it wrong, or just don't get the syntax right.
The code is as follows and contains a lot of debug output:
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    ifstream fin("gift1.in", ios::in);
    ofstream fout("gift1.out", ios::out);

    unsigned short NP;

    struct person
    {
        string name;
        unsigned int gave;
        unsigned int received;
    };

    vector<person> accounts;

    string tmp_name;

    fin >> NP;
    accounts.resize(NP);
    for (auto& i : accounts)
    {
        fin >> tmp_name;
        //fout << "Just read this name: " << tmp_name << "\n";
        i.name = tmp_name;
        i.gave = 0;
        i.received = 0;

    }

    fout << "\n";

    for (unsigned int j = 1; j <= NP; j++)
    {
        string giver_name;
        fin >> giver_name;
        fout << "Read a name #" << j << ": " << giver_name << "\n";

        auto vpit = find_if(accounts.begin(), accounts.end(), [&giver_name](const person& pers) -> bool {return pers.name != giver_name; });
        if (vpit == accounts.end())
        {
            fout << "Couldn't find this giver in accounts\n";
        }
        else
        {
            person& found = *vpit;  // the logic is probably wrong here
            fout << "\nDebug info: \n\t Giver#" << j << "; \n\t iterator->name ==" << vpit->name << "; \n\t iterator->gave == " << vpit->gave << "; \n\t iterator->received == " << vpit ->received << "\n";
            fout << "Found " << found.name << " in accounts; proceeding\n";
            //further code
    }

What might I be doing wrong?

A: If you want to find an element of the vector with the given value then you have to use the equality operator
auto vpit = find_if( accounts.begin(), accounts.end(),
                     [&giver_name] (const person& pers) { return pers.name == giver_name; } );

As for me then the second loop
for (unsigned int j = 1; j <= NP; j++)
{
    string giver_name;
    fin >> giver_name;
    //...

looks questionably.


text:
Q: Can i manipulate other applications using Java? I am trying to find a way to interact with a GUI using java, i want to write a script to open an application, enter username and password and click "login" and such things. is there any way to do it?

A: Maybe you are searching something like Java robot it is similar as Selenium but for system applications.
I used this to perform UI-Tests in the past http://alvinalexander.com/java/java-robot-class-example-mouse-keystroke
And to launch one System command from java you can use
Runtime.getRuntime().exec("System specific command line text here");

As well as
File file = new File("/absolute/path/to/yourExecutable");
Desktop.getDesktop().open(file);


text:
Q: Checking if a String is a number using switch I have to make a program which tells if a String that I type in my keyboard is a number, by using a switch. I know how to do it with try and catch, but I don't know how to do it with switch.
Any tips?

A: You would need to check each characer in the String. Something like this would probably work.
static boolean isNumber(String s) {
    if (s == null) {
        // Debatable.
        return false;
    }
    int decimalCount = 0;
    for (int i = 0; i < s.length(); i++) {
        switch (s.charAt(i)) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                // These are all allowed.
                break;
            case '.':
                if (i == 0 || decimalCount > 0) {
                    // Only allow one decimal in the number and not at the start.
                    return false;
                }
                decimalCount += 1;
                break;
            default:
                // Everything else not allowed.
                return false;
        }
    }
    return true;
}

A: Up to Java7 you can use switch(String) statement.

But here you have enough with switch(int) and a little workaround:
public static void main(String[] args) throws Exception {
    String a = "2";

    switch (Integer.parseInt(a)) {
    default:
        System.out.print("is a number");
        break;
    }
}

A: This is the solution I got asking to some classmates and thinking it quietly.
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner entry = new Scanner(System.in);
    String myNumber;
    int tf;
    myNumber = entry.next();

    try {
        Double.parseDouble(myNumber);
        tf = 1;
    }

    catch (Exception e) {
        tf = 0;
    }

    switch(tf) {

    case 1:
        System.out.println("Is a number");
    break;

    default:
        System.out.println("No es un número");
        break;

    }

}

Thanks to the community for being so nice!

A: I came up with a shorter code BUT it uses regular expressions, which if Halo is just starting with Java, he may have not seen that topic yet. But then it answers the question too so here it is:
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
String matches = new Boolean(expression.matches("\\d+")).toString();
switch (matches) {
case "true":
    System.out.println("IT'S a number");
    break;
case "false":
    System.out.println("NOT a number");
}
scanner.close();


text:
Q: Writing a program that computes the total weight of a cargo. C I'm trying to write a program that computes the total weight of a cargo. The user will enter the number of boxes and
the weight of a box for each type of boxes they have. My code keeps repeating the "Enter the number of boxes" twice when prompting the user to enter the weight. How do I fix that? Here is my code:
#include<stdio.h>
int main()
{
    int x,y,total=0; // variables

    {
        while(!(x==-1 || y==-1)){

            printf("Enter the number of boxes:");
            scanf("%d",&x);

            printf("Enter the weight(lbs):");
            scanf("&d",&y);

            total+=(x*y);
        }
        printf("\n");
    }

    if (x==-1 || y==-1) {  // when the user inputs -1, the next
                         line will execute

        printf("The total weight is:%d",total);
    }
    printf("\n");

    system("PAUSE");
    return 0;
}

A: I've edited your code following the comments other people wrote you:
#include <stdio.h>

int main()
{
    int x = 0,y = 0,total=0; // variables

    while(!(x==-1 || y==-1)){
        printf("Enter the number of boxes:");
        scanf("%d",&x);
        printf("Enter the weight(lbs):");
        scanf("%d",&y);
        total+=(x*y);
    }
    printf("\n");

    if (x==-1 || y==-1)
    {  // when the user inputs -1, the next  line will execute
        printf("The total weight is:%d",total);
    }
    printf("\n");

    return 0;
}

All I did was to write it more simply and nicely
Good luck with your homework

A: here is some fixed code, though you will need these new headers to get it to work
#include<stdio.h>
#include <string.h>
#include <stdlib.h>

so i think the problem you have is your input buffer is skipping the second value.
to combat this i have use fgets instead, as it is easier to work wit.
char input[3];
    int x = NULL;
    int y = NULL;
    int total = 0; // variables

    while (x == NULL || y == NULL)
    {
        printf("Enter the number of boxes:");
        fgets(input, 3, stdin);

        input[strlen(input) - 1] = 0;
        x = atoi(input);

        printf("Enter the weight(lbs):");
        fgets(input, 3, stdin);

        input[strlen(input) - 1] = 0;
        y = atoi(input);

        total += (x*y);
    }

the 3 in the input array needs to be equal to the amount of characters you wish to accept + 2 (to account for /n/0 termination)


text:
Q: Why do Rust programs use so much more memory than the C, Haskell and OCaml versions? I looked at how much RAM was used by Rust programs (RES column from top command) and I wonder why they use so much memory.
Here is an example:
use std::io;

fn main() {
    println!("What's your name?");
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    println!("Hello {}!", input);
}

I saw that 6 MB of memory was used before I input something.
Here is how I compiled and executed the program:
cargo build --release
./target/release/main

The equivalent C program:
#include <stdio.h>

int main(void) {
    printf("What's your name?\n");
    char input[100] = {0};
    scanf("%s", input);
    printf("Hello %s!\n", input);
    return 0;
}

only uses 0.6 MB. In this case, the Rust program uses 10 times more memory. In other cases, I saw that the Rust program uses 5 times more memory.
I also tested with other languages to compare.
The OCaml version:
let () =
    print_endline "What's your name?";
    let line = read_line () in
    print_string "Hello ";
    print_endline line

uses 1 MB.
The Haskell version:
main = do
    putStrLn "What's your name?"
    name <- getLine
    putStrLn ("Hello " ++ name ++ "!")

uses 3 MB.
The Python version:
print("What's your name?")
name = input()
print("Hello", name, "!")

uses 7 MB, almost the same as the Rust version!
Update
I'm running Linux (ArchLinux) with Rust 1.3 (I also tried the nightly with similar results).
Update 2
Here is more data from the htop command:
VIRT    RES     SHR     MEM%    Command
15572   2936    804     0.1     ocaml
21728   2732    2528    0.1     haskell
22540   7480    4308    0.2     python
4056    668     600     0.0     c
24180   6164    1928    0.2     rust

Update 3
I did more tests with massif to see the memory usage.
For every program, I ran massif twice, as following:
valgrind --tool=massif --time-unit=B ./program
valgrind --tool=massif  --pages-as-heap=yes --time-unit=B ./program

Here are the results with all the programs (as shown by ms_print):
C versions:
https://framabin.org/?dd243f8ec99155bc#Af5cPrcHnz3DsWiOStfwgW8Qq6BTVhogz/46L+sMuSs=
https://framabin.org/?261b9366c3749469#1ztDBkgVly9CanrrWWrJdh3yBFL5PEIW3OI5OLnze/Q=
Rust versions:
https://framabin.org/?0f1bac1c750e97bf#AXwlFYYPHeazq9LfsTOpRBaUTTkb1NfN9ExPorDJud0=
https://framabin.org/?c24b21b01af36782#OLFWdwLjVG2t7eoLqLFhe0Pp8Q8pA2S/oq4jdRRWPzI=
OCaml versions:
https://framabin.org/?060f05bea318109c#/OJQ8reHCU3CzzJ5NCOCLOYJQFnA1VgxqAIVjgQWX9I=
https://framabin.org/?8ff1ffb6d03cb37a#GN8bq3Wrm6tNWaINIhMAr4ieltLtOPjuZ4Ynof9bV4w=
Haskell versions:
https://framabin.org/?b204bd978b8c1fd8#DyQH862AM8NEPTKlzEcZgoapPaZLdlF9W3dRn47K5yU=
https://framabin.org/?ac1aa89fcaeb782c#TQ+uAiqerjHuuEEIhehVitjm63nc3wu5wfivAeBH5uI=
Python versions:
https://framabin.org/?197e8b90df5373ec#aOi0+tEj32Na5jW66Kl97q2lsjSZ2x7Cwl/pOt0lYIM=
https://framabin.org/?397efa22484e3992#1ylOrmjKaA9Hg7gw7H7rKGM0MyxuvKwPNN1J/jLEMrk=
Summary (ram usage):
|------------|----------|----------|----------|----------|----------|
|            |     C    | Haskell  |   OCaml  |   Rust   |  Python  |
|------------|----------|----------|----------|----------|----------|
| First run  |    1 B   | 63.12 KB | 5.993 MB |   816 B  | 1.321 MB |
|------------|----------|----------|----------|----------|----------|
| Second run | 6.031 MB | 24.20 MB | 17.14 MB | 25.60 MB | 27.43 MB |
|------------|----------|----------|----------|----------|----------|

The first run is without the --pages-as-heap=yes parameter.
I also ran massif with the --stacks=yes option for C and Rust.
C version:
https://framabin.org/?b3009d198ccfdee1#HxR6LPPAzt15K+wIFdaqlfSJjBrJvhV2ZHWdElg3ezc=
(3.141 KB)
Rust version:
https://framabin.org/?b446d8d76c279007#tHnGiOnRstTA2krhz6cgfvTjI+FclcZS3rqyZvquWdQ=
(8.602 KB)
What does explain such a huge difference between heap block allocation and page allocation in Rust?

A: Since this question is on top results from google, I would like to give an update for anybody looking at this in 2022. I ran the exact same program and measured rust RSS from htop. It shows 924KB. That is 0.92MB. Apparently rust has improved a lot in these years.

A: Because the standard library is statically linked.
You can overcome this by compiling with the -C prefer-dynamic option.
As to the reason behind having the standard library statically linked: it increases executable portability (ie: no need for the standard library to be installed in target system).

A: This article has a very good discussion  of the topic. Some of the largest and most common culprits are cargo's default to debug builds (not relevant in your case) and statically including libraries by default.


text:
Q: Win CE 6.0 ethernet read/write thread priorities I am using win CE 6.0 and need to edit the priorities of the threads that are responsible from reading and writing from ethernet. However I could not find any piece of code responsible for this purpose. Do you have an idea where I can find them?
Regards

A: The priorities of the interrupt service threads can be modified through the registry. See Real-Time Priority System Levels for information. Ethernet adapters fall under NDIS (Network Driver Interface Specification).


text:
Q: Navigate back and show snack I am thinking of this pattern for my application, and cannot find a proper way of doing it.
User is in list page, she clicks on an item and goes to edit page. She edits, and hits the save. Now I want the application to
- show spinning wheel, while saving the item
- after save pop the route to go back to list page, AND show a snackbar on the list page.
I don't seem to find a way to pass a parameter to the previous route to tell it about the state, which is to show the snackbar.

A: For showing progress on click of save button you can use something like this.
Firstly initialize a variable static bool isSaving = false; then in your scaffold use it like this.
child:Stack(
    children: <Widget>[
      isSaving
          ? new Container(
              child: new CircularProgressIndicator(
                value: null,
                strokeWidth: 2.0,
              ),
              alignment: Alignment.center,
            )
          : new Container(
              child: new RaisedButton(
                onPressed: () {
                  setState(() {
                    isSaving = true;
                    //Other Implementations here
                  });
                },
                child: new Text("Save"),
              ),
            ),
    ],
  ),

When the operation is complete again set state and make variable false.
Now when you get notified that operation has been done use Navigator to go back.
Navigator.pop(context);

For showing snackbar in your previous screen use a Global Key.
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();

Assign this key to your scaffold.
new Scaffold(
    key: scaffoldKey,
    ...
    )

As answered here show snackbar just after pop operation like this.
scaffoldKey.currentState
    .showSnackBar(new SnackBar(content: new Text("Saved Successfully")));

Or can try a different approach as explained in this sample.
Hope it helps.

A: You can send data back through pop method. You can do something like that.
In your edit page:
bool saved = item.save();
Navigator.pop(context, saved);

In your list page:
var saved = await Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => EditRoute(item)),
);
if (saved) {
  // Show success snackbar
} else {
  // Show error snackbar
}


text:
Q: Excel Index - how to return a blank if the cells show 0 Excel snip

In column P I've entered a formala to return the name of the column with the lowest value J to N.
The formula is:
=INDEX($J$1:$N$1,MATCH(MIN(J2:N2),J2:N2,0))

For row 5 to 9 all the values are zero so I'd like P5 to P9 to return a blank cell. Instead it's returning the name of column J. The values in J to N are formulas multiplying D with (hidden) E to I.
I have tried using various IF functions but I can't get it to work without giving me an error popup

A: Perhaps you could try something along the lines of using an IF() logic

• Formula used in cell P2
=IF(O2=0,"",INDEX($J$1:$N$1,MATCH(O2,J2:N2,0)))

Alternatively, if you are an MS365 user then can try using BYROW()

• Formula used in cell P2
=BYROW(J2:N9,LAMBDA(m,IF(MIN(m)=0,"",XLOOKUP(SUM(m),m,$J$1:$N$1))))


text:
Q: Database Connection to live site I'm currently building an online booking form as a project and once the user hits the submit button it sends an email with the details to a specified email and stores everything in an database. Currently this is all working fine and well on a localhost set up.
I have a domain name with a current live website and when i upload this new website as an extra page it still preforms the sending of the email but won't load anything into my database.
I'm almost certain it's because my php script for the email/database is specifying localhost as the DB connection but how do i go about connecting it if i was to upload the webpage to my live domain.
Any help is appreciated :)

A:
Ask service provider for username and password and export sql file and upload then,ask them for run sql file and then try to connect database live.

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


text:
Q: Acceder con un spinner a una lista creada en Realm en Android Studio (Java) Os cuento: tengo un formulario con realm a través del cual puedo registrar elementos. Pues bien, ahora me gustaría poder acceder a dicha lista de elementos registrados para que me los muestre en un spinner, pero no tengo ni idea de como podría hacerlo. A ver si me podéis echar una mano.
Edito:
He conseguido acceder a la lista con el siguiente código:
    package com.isaac.appet;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.isaac.appet.HomeFragment.HomeFragment;
import com.isaac.appet.HomeFragment.Pets;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;

public class AlarmsFormActivity extends AppCompatActivity {

    Spinner spPetLst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarms_form);

        spPetLst = findViewById(R.id.spPetLst);

        Realm realm = Realm.getDefaultInstance();
        RealmResults<Pets> realmResults = realm.where(Pets.class).findAll();
        List<Pets> documents = realm.copyFromRealm(realmResults);
        ArrayAdapter<Pets> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, documents);
        spPetLst.setAdapter(adapter);

    }
}

Pero me muestra el nombre del paquete, con numero y tal, y quiero que me muestre solamente el nombre del elemento que le asigné en dicho campo. ¿Como puedo hacer esto?
Muchas gracias.
Un saludo.

A: El tercer parámetro del constructor de ArrayAdaper es T[], esto para realizarle un toString() a cada objecto del array y por eso es que te muestra el paquete en vez del valor que deseas. Normalmente se envia un array de String al constructor por lo que veo que tienes 2 opciones.
1- Conviertes los valores que quieres mostrar a String[] utilizando el valor que represente cada elemento del spinner. Suponiendo que tienes una propiedad name en la clase Pet, podrias hacer esto:
String[] petsName = new String[documents .size()];
for(int i = 0; i <= documents .size(); i++){
   petsName[i] = documents.get(i).getName();
}

 ArrayAdapter<Pets> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, petsName);
        spPetLst.setAdapter(adapter);

2 - O sobreescribes el metodo toString() de la clase Pet para que asi en vez de imprimir la localización de la clase, imprima el nombre del Pet:
public class Pet
{
   //...

   @Override
   public string toString(){ return getName(); }
}


text:
Q: Regular Expression to check if a string has HTML code can some one give me the Regular Expression that can check if a given string has any HTML code in it, and coming to think of it I would be bothered with something exactly.

A: Should be something like this
var pattern:RegExp = /<a\s.*?<\/a>/;
var index = str.search(pattern);
if (index != -1) // we have a match

A: If you mean by "I would be bothered" that it is enough for you if the regex can detect anchor tags, then
if (/<a\s.*<\/a>/i.test(subject)) {
    // Successful match
}

should suffice. This return True if an anchor tag can be matched anywhere in the string.


text:
Q: Memory Management (Allocating Pages/Frames to Logical Addresses) I am new to Operating Systems and I was following this handbook which I am reading to get a better grasp on how computers really work. However having stumbled upon Memory Management I found it somewhat confusing when allocating pages and frames using page tables to virtual memory locations.
Say Page/Frame size is 4K and the system is 32-bit (it handles addresses 4byte long and page entries are also 4byte long).
If the same Process references two different memory locations for its needs say Virtual_MemoryLocation_A is 222 and Virtual_MemoryLocation_B is 999 will these memory requests be pinned to the same Page 0 (first Page in the Page table) since both do not extend beyond the frane size scope of 4096 bytes and be granted memory by the OS to the same Frame X?

A: If you have a page size of 4096, then
page number = address DIV 4096
page offset = address MOD 4096

Those two values uniquely identify the logical memory location.
Two addresses can be in the same frame. If that were not the case, there would be no point in having pages. All memory locations from 0 .. 4095 are in the same, zeroth page.


text:
Q: Verify XPath is valid with developer tools in Internet Explorer 8 I'm writing Selenium tests, and I need to support Internet Explorer 8.
I want to use Developer Tools in Internet Explorer 8 to verify that Internet Explorer 8 can find certain elements by their XPath expressions. I can do this easily using Chrome of Firebug with Firefox, but I can't figure out how to do it with IE Developer Tools -- it feels very clunky, foreign, and unintuitive for someone coming from Chrome and and Firebug with Firefox.
I'm not trying to get an element's XPath expression with Developer Tools. (The web has plenty of links for how to do that.) I'm trying to verify that XPath expressions which I already have will work in Internet Explorer 8 using Developer Tools.
If I want to verify that an XPath expression finds an element in Chrome, I would:

*

*Navigate to the page I want to verify

*Press F12 to bring up Chrome debugger

*Press Ctrl + F to bring up find

*Type or paste in the XPath expression that I want to test

*See if the XPath expression found an element.

Here is an image of what it looks like in Chrome:

I would like to do the same thing in Internet Explorer 8.
How can I do this?
I have seen Equivalent of Firebug's "Copy Xpath" in Internet Explorer? which tries to get the XPath expression from the webelement. I'm trying to do the opposite: get the webelement from the XPath expression to verify the XPath expression is valid in Internet Explorer 8.

A: This isn't possible, or at least easily.
Internet Explorer (any version) doesn't have a native XPath engine. The way Selenium works around this is by using a JavaScript library to do it, called Wicked Good XPath.
https://code.google.com/p/wicked-good-xpath/
My only suggestion would be to inject WGX into your page and then use it directly in the console.
You can, however, still execute CSS selectors natively in the IE Developer Tools console - but this is little consolation for your XPath needs.


text:
Q: How to install r.mcda.electre on GRASS I have downloaded r.mcda.electre addon from the following link:
https://wingrass.fsv.cvut.cz/grass71/x86_64/addons/grass-7.1.svn/r.mcda.electre.zip
But I can not install it with the latest version of GRASS 7.3. When I click on the exe file I get the following message:
---------------------------
r.mcda.electre.exe - System Error
---------------------------
The program can't start because libgrass_gis.7.3.svn.dll is missing from your computer. Try reinstalling the program to fix this problem.
---------------------------
OK
---------------------------

I even tried to install the addon from the Grass GUI but I get the following message in GRASS 6.4.3:
ERROR: GRASS Addons <r.mcda.electre> not found

In GRASS 7.3 I get this error message:
Downloading precompiled GRASS Addons <r.mcda.electre>... Traceback (most recent call last):   File "C:\Program Files\GRASS GIS
7.3.svn/scripts/g.extension.py", line 1729, in <module>
    sys.exit(main())   File "C:\Program Files\GRASS GIS
7.3.svn/scripts/g.extension.py", line 1708, in main
    install_extension(source=source, url=url, xmlurl=xmlurl)   File "C:\Program Files\GRASS GIS
7.3.svn/scripts/g.extension.py", line 679, in install_extension
    ret += install_extension_win(module)   File "C:\Program Files\GRASS GIS
7.3.svn/scripts/g.extension.py", line 952, in install_extension_win
    outdev=outdev, directory=srcdir, tmpdir=TMPDIR)   File "C:\Program Files\GRASS GIS
7.3.svn/scripts/g.extension.py", line 1093, in download_source_code
    f, h = urlretrieve(url, zip_name)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\urllib.py", line 94, in urlretrieve
    return _urlopener.retrieve(url, filename, reporthook, data)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\urllib.py", line 240, in retrieve
    fp = self.open(url, data)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\urllib.py", line 208, in open
    return getattr(self, name)(url)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\urllib.py", line 345, in open_http
    h.endheaders(data)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\httplib.py", line 969, in endheaders
    self._send_output(message_body)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\httplib.py", line 829, in _send_output
    self.send(msg)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\httplib.py", line 791, in send
    self.connect()   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\httplib.py", line 772, in connect
    self.timeout, self.source_address)   File "C:\Program Files\GRASS GIS
7.3.svn\Python27\lib\socket.py", line 571, in create_connection
    raise err IOError: [Errno socket error] [Errno 10061] No connection could be made because the target machine actively refused it (Sat Jun 04 09:05:16 2016) Command finished (1 sec)

This is my first experience with Grass.

A: You should install addons with this command line inside of grass:
g.extension extension=r.mcda.electre svnurl=http://svn.osgeo.org/grass/grass-addons/grass7

To run the module, from GRASS GIS you have to write "r.mcda.electre", fill the fields and press run button.


text:
Q: Delete files older than X days from FTP server with PowerShell or batch file I have to write a script which accesses an FTP server, and then deletes all *.zip files which are older than X days.
As clarification: The script can't run on the FTP server.
This is what I have so far:
$ftpServer = "RandomFTPServer"
$ftpUser = "Username"
$ftpPassword = Read-Host "Password" -AsSecureString

$credentials = New-ObjectSystem.Net.NetworkCredential($ftpUser, $ftpPassword)

function Get-FtpRequest($ftpPath) {
    $ftpRequest = [System.Net.FtpWebRequest]::Create("$ftpServer/$ftpPath")
    $ftpRequest.Credentials = $credentials
    $ftpRequest.UseBinary = $true
    $ftpRequest.KeepAlive = $true
    $ftpRequest.UsePassive = $true
    return $ftpRequest
}

Any tips on what I need to do next?

A: You have to retrieve timestamps of remote files to select the old ones.
Unfortunately, there's no really reliable and efficient way to retrieve timestamps using features offered by .NET framework/PowerShell as it does not support FTP MLSD command.
So either you use:

*

*ListDirectoryDetails method (FTP LIST command) to retrieve details of all files in a directory and then you deal with FTP server specific format of the details (*nix format similar to ls *nix command is the most common, drawback is that the format may change over time, as for newer files "May  8 17:48" format is used and for older files "Oct 18  2009" format is used)

*GetDateTimestamp method (FTP MDTM command) to individually retrieve timestamps for each file. Advantage is that the response is standardized by RFC 3659 to YYYYMMDDHHMMSS[.sss]. Disadvantage is that you have to send a separate request for each file, what can be quite inefficient.

Some references:

*

*C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response

*Parsing FtpWebRequest ListDirectoryDetails line

*Retrieving creation date of file (FTP)

*PowerShell FTP download files and subfolders

*C# Download all files and subdirectories through FTP
Though Microsoft does not recommend FtpWebRequest for a new development anyway.

Alternatively you can use a 3rd party FTP client implementation that supports the modern MLSD command and/or has built-in support for parsing different formats of the LIST command.
For example, WinSCP .NET assembly supports both.
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "username"
    Password = "password"
}

try
{
    # Connect
    $session = New-Object WinSCP.Session
    $session.Open($sessionOptions)

    # List files
    $remotePath = "/remote/path"
    $directoryInfo = $session.ListDirectory($remotePath)

    # Find old files
    $limit = (Get-Date).AddDays(-15)

    $oldFiles =
        $directoryInfo.Files |
        Where-Object { -Not $_.IsDirectory } |
        Where-Object { $_.LastWriteTime -lt $limit }

    # Delete them
    foreach ($oldFileInfo in $oldFiles)
    {
        $session.RemoveFile($oldFileInfo.FullName).Check()
    }

    Write-Host "Done"
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

If you can do with a plain batch file, it's actually even easier with WinSCP scripting:
winscp.com /ini=nul /log=delete.log /command ^
    "open ftp://username:password@ftp.example.com/" ^
    "rm /remote/path/*<15D" ^
    "exit"

See file masks with time constraints.
(I'm the author of WinSCP)

Note that WinSCP does not require any installation. So you can just have its binaries copied around with your batch file or PowerShell script.

A: I'm currently doing this using FTPUSE, a freeware command-line tool which maps a FTP folder to a windows drive letter, together with a batch file in the following way:
: delete files older than 7 days from ftp://my.ftpsite.net/folder/subfolder
ftpuse F: my.ftpsite.net password /USER:username
timeout /t 5
forfiles -p "F:\folder\subfolder" -s -m *.* -d -7 -c "cmd /C DEL @File /Q"
ftpuse F: /DELETE

The software is compatible with all major versions of windows: Windows XP, Vista, 7, Server 2003, Server 2008, Windows 8, Server 2012 and Windows 10 (32-bit, 64-bit).
For further info, you can also read this post I wrote about FTPUSE (I'm not the author in any way, I just find it very useful for these kind of tasks).


text:
Q: SQL STORED PROCEDURE SAVING INTO VARIABLE Can anybody spot the problem with this stored procedure?  mysql is reporting the following error:
1048 Column 'categoryID' cannot be null
DELIMITER $$
CREATE PROCEDURE catalogue_assign_product_to_subcategory(
    IN inProductId INT,
    IN insubCategoryId INT)

     BEGIN

     DECLARE catID INT;

     SELECT subcategoryParent FROM tblSubcategory
         WHERE subcategoryID =  insubCategoryId INTO catID;

    INSERT INTO tblProdCat (productID, categoryID)
       VALUES (inProductId, 'catID');

  END

A: 'catID' should be without the singlequotes in the INSERT statement.
I guess the field is defined as INT, you now try to insert a STRING
   INSERT INTO tblProdCat (productID, categoryID)
   VALUES (inProductId, catID);


text:
Q: TortiouseSVN connection to github.com using SSH I am trying to access my github.com repository using TortiouseSVN via SSH.  Using HTTPS works fine, but the repository has grown so large that I am getting timeouts when doing updates.

I have created the private/public key using git bash, registered it to github, and converted it to a private/public putty key.

I added the key to Pageant Key list for automatic login.

Putty configuration:
Session Category:
host name: git@github.com
port: 22  (SSH)
SessionName: github

Connection/Data Category:
Auto-login username:
SSH/Auth
Private key file is the putty converted .ppk file

TortoiseSVN settings:
Network:
SSH Client:
"C:\Program Files\TortoiseSVN\bin\TortoisePlink.exe"

Connecting via putty connects and gives me this:
Using username "git".
Authenticating with public key "" from agent
Server refused to allocate pty
Hi !  You've successfully authenticated, but GitHub does not provide shell access.
However, when try to "SVN Checkout" using TortiouseSVN in a folder. I get the following:
URL Format:       svn+ssh:///repo/repo.git/
URL:              svn+ssh://github/myname/online.git/

Here are the results:
Tortiouse SVN:
Error: Unable to connect to a repository at url
Error: svn+ssh://github//myname/online.git/
Error: To better debug SSH connection problems, remove the -q option from 'ssh' in the
Error: [tunnels] section of your Subversion configuration file.
Error: Network connection closed unexpectedly

Putty Log:
Event Log: Looking up host "github.com" for SSH connection
Event Log: Connecting to 140.82.113.3 port 22
Event Log: We claim version: SSH-2.0-PuTTYTortoisePlink_Release_0.72
Event Log: Remote version: SSH-2.0-babeld-78794f53
Event Log: Using SSH protocol version 2
Event Log: No GSSAPI security context available
Event Log: Doing ECDH key exchange with curve Curve25519 and hash SHA-256 (unaccelerated)
Event Log: Server also has ssh-dss host key, but we don't know it
Event Log: Host key fingerprint is:
Event Log: ssh-rsa 2048
Event Log: Initialised AES-256 SDCTR (AES-NI accelerated) outbound encryption
Event Log: Initialised HMAC-SHA-256 (unaccelerated) outbound MAC algorithm
Event Log: Initialised AES-256 SDCTR (AES-NI accelerated) inbound encryption
Event Log: Initialised HMAC-SHA-256 (unaccelerated) inbound MAC algorithm
Event Log: Reading key file "path to .ppk file"
Event Log: Pageant is running. Requesting keys.
Event Log: Pageant has 1 SSH-2 keys
Event Log: Pageant key #0 matches configured key file
Event Log: Trying Pageant key #0
Event Log: Sending Pageant's response
Event Log: Access granted
Event Log: Opening main session channel
Event Log: Opened main channel
Incoming packet #0x8, type 99 / 0x63 (SSH2_MSG_CHANNEL_SUCCESS)
00000000  00 00 01 00                                      ....
Incoming packet #0x9, type 95 / 0x5f (SSH2_MSG_CHANNEL_EXTENDED_DATA)
00000000  00 00 01 00 00 00 00 01 00 00 00 be 49 6e 76 61  ............Inva
00000010  6c 69 64 20 63 6f 6d 6d 61 6e 64 3a 20 27 73 76  lid command: 'sv
00000020  6e 73 65 72 76 65 20 2d 74 27 0a 20 20 59 6f 75  nserve -t'.  You
00000030  20 61 70 70 65 61 72 20 74 6f 20 62 65 20 75 73  appear to be us
00000040  69 6e 67 20 73 73 68 20 74 6f 20 63 6c 6f 6e 65  ing ssh to clone
00000050  20 61 20 67 69 74 3a 2f 2f 20 55 52 4c 2e 0a 20  a git:// URL..
00000060  20 4d 61 6b 65 20 73 75 72 65 20 79 6f 75 72 20  Make sure your
00000070  63 6f 72 65 2e 67 69 74 50 72 6f 78 79 20 63 6f  core.gitProxy co
00000080  6e 66 69 67 20 6f 70 74 69 6f 6e 20 61 6e 64 20  nfig option and
00000090  74 68 65 0a 20 20 47 49 54 5f 50 52 4f 58 59 5f  the.  GIT_PROXY_
000000a0  43 4f 4d 4d 41 4e 44 20 65 6e 76 69 72 6f 6e 6d  COMMAND environm
000000b0  65 6e 74 20 76 61 72 69 61 62 6c 65 20 61 72 65  ent variable are
000000c0  20 4e 4f 54 20 73 65 74 2e 0a                    NOT set..
Incoming packet #0xa, type 98 / 0x62 (SSH2_MSG_CHANNEL_REQUEST)
00000000  00 00 01 00 00 00 00 0b 65 78 69 74 2d 73 74 61  ........exit-sta
00000010  74 75 73 00 00 00 00 01                          tus.....
Event Log: Started a shell/command
Event Log: Session sent command exit status 1
Event Log: Main session channel closed

Thanks in advance

A: GitHub does not offer Subversion access over SSH.  If you want to use a GitHub repository with Subversion, you need to use HTTPS.  Otherwise, you can access the repository as a Git repository with either HTTPS or SSH.


text:
Q: How to use static variable as value for named-native-query inside JPA? I want to use static variable as a query for a named-native-query inside JPA (persistence.xml) file.
I'm using Spring boot 2.1.9 and hibernate 5.3.12.
I have an interface :
public interface SqlQueryFacture {
    String MEMOIRES_TABLE_BY_FACTURE = "SELECT ......";
}

and I want to use MEMOIRES_TABLE_BY_FACTURE as value in persistence.xml file like this

<entity-mappings version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
    http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd">

    <entity class="fr.pp.entities.factures.Facture">
        <named-native-query name="Facture.getMemoiresTableByFactureId" result-set-mapping="MemoireTableRowDtoMapping">
            <query>SqlQueryFacture.MEMOIRES_TABLE_BY_FACTURE</query>
        </named-native-query>
    </entity>

</entity-mappings>

Can I do that without use @NamedNativeQuery inside the entity class ?

A: I'm guessing that you are trying for dynamic queries through JPA. Unfortunately, JPA doesn't provide support for dynamic queries.
You can't do in JPA (persistence.xml) :
<query>SqlQueryFacture.MEMOIRES_TABLE_BY_FACTURE</query>

For example :
<!-- Query takes HQL (Hibernate Query Language) directly -->
<query>SELECT p from Product p</query>

This is allowed.


text:
Q: Radius of convergence in power series $\sum_{n=0}^{\infty}(-1)^nx^{2^n}$
Given the series $$\sum_{n=0}^{\infty}(-1)^nx^{2^n}$$
  determine the radius of convergence, and what can we say when $x=R$ and $-R$?

*

*Is it a power series? Power series should have the form of $$\sum_{n=0}^{\infty}a_nx^n$$
but the given series does not match this form.  If not a power series, why can we say about its radius of convergence?

*By the ratio test, I get that this series converges when $|x|<1$, diverges when $|x|>1$, so $R=1$, is that right?

*When $x=1$ or $-1$, series both becomes $$\sum_{n=0}^{\infty}(-1)^n,$$
then obviously, series diverges. Right?

A: (1): see the comments.
(2): the radius of convergence  $\rho$ of $\sum a_nx^n$ is defined to be:
$$ \rho:=\frac{1}{\alpha} $$
where
$$ \alpha = \lim_{n\rightarrow \infty} \sup \sqrt[n]{|a_n|} $$.
Here we have:
$|a_n| = 1$ if $n$ is a power of 2, $|a_n|=0$ otherwise. Thus $\rho=1$.


text:
Q: copyfile is copying into VirtualStore folder? I have created one application on Vista, that is running with admin privileges.
I am trying to copy one file to ProgramData\Application\ folder.
But instead to copying there its copying at location c:\Users\XXX\AppData\Local\VirtualStore\ProgramData\Application\
I dont want this file to get copied into Virtul store.
Any suggestion , how can I overcome this issue?
I am using CopyFile API.

A: Add a Vista manifest to your application to disable the FS virtualization


text:
Q: How do you add a header to wav file? I am sending audio data stored as a blob to my backend (node/express). When I save the file as .wav and attempt to use in the SpeechRecogition package in python it throws an error saying the "file does not start with RIFF id".  So how can I add the headers to my blob file before I save it so that it is a correctly formatted .wav file? I can provide the code if necessary.
node.js file
var multer = require('multer');
var fs = require('fs'); //use the file system so we can save files
var uniqid = require('uniqid');
var spawn = require('child_process').spawn;
const storage = multer.memoryStorage()
var upload = multer({ storage: storage });

router.post('/api/test', upload.single('upl'), function (req, res) {

   console.log(req.file);
   console.log(req.file.buffer);

   var id = uniqid();
   fs.writeFileSync(id+".wav", Buffer.from(new Uint8Array(req.file.buffer))); //write file to server as .wav file

   const scriptPath = 'handleAudio.py'
   const process = spawn('python3', [__dirname+"/../"+scriptPath, "/home/bitnami/projects/sample/"+id+".wav", req.file.originalname, 'True']); //throws error about header in .wav

});

Also I had this same example working with a php endpoint that just saved the blob to a file with .wav extension and the python file accepted it. What could be different in the move_uploaded_file in php and what I am doing above with node?

A: Every .wav file needs a header specified by the WAVE file format, available here. While it's fine for you to build the header yourself, it's much easier to just use a proper lib to do the work for you.
One example is node-wav, which has a nice API to write WAVE files from raw PCM data (what you have at the moment). Example code is provided by the node-wav documentation.


text:
Q: Access JDBC Connection from jOOQ transaction Is is possible to access the underlying JDBC connection from within a jOOQ TransactionRunnable or TransactionCallable?
I'd like to be able to access the PostgreSQL large object API which you get from the connection:
final LargeObjectManager manager = connection.unwrap(PGConnection.class).getLargeObjectAPI();
Afaict you only get access to the ConnectionProvider which if I call aquire() on, doesn't look like I'm going to end up with the same connection for my LOBs as for my statements.

A: In jOOQ 3.7, #4552 was implemented to allow for accessing a Configuration's Connection via a ConnectionRunnable. For example:
DSL.using(configuration)
   .transaction((Configuration c) -> {
       DSL.using(c).connection(connection -> {
           LargeObjectManager manager = connection.unwrap(PGConnection.class).getLargeObjectAPI();
           // ...
       });
   });

This API will internally call acquire() and release(), for convenience, so the following solution is equivalent but more verbose:
DSL.using(configuration)
   .transaction((Configuration c) -> {
       Connection connection = c.connectionProvider().acquire();
       try {
           LargeObjectManager manager = connection.unwrap(PGConnection.class).getLargeObjectAPI();
           // ...
       }
       finally {
           c.connectionProvider().release(connection);
       }
   });

As the Connection is obtained from the "transacted" Configuration c, you can be sure that you will access the right Connection. Even if you access it several times, it will always be the same as jOOQ internally replaces your own ConnectionProvider by a DefaultConnectionProvider acting upon the transacted Connection


text:
Q: Conflict Between Libraries I know this question has been asked few number of times but after searching for a day I still cannot resolve it. I am trying to use the POCO C++ LIBRARIES and ubuntu 16.0.4 LTS comes with POCO 1.3 installed. I downloaded the latest version of POCO and built and installed it to /home/{username}/poco-1.9.0-all. But when I build my project using eclipse I get the following error:
Building target: AuthorizationServer
Invoking: GCC C++ Linker
g++ -L/home/{username}/poco-1.9.0-all/lib -o "AuthorizationServer"  ./src/entity/ResourceOwner.o  ./src/database/MySQL.o  ./main.o   -lPocoFoundation -lPocoData -lPocoMySQL
/usr/bin/ld: warning: libPocoData.so.9, needed by /usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libPocoMySQL.so, may conflict with libPocoData.so.60
/usr/bin/ld: warning: libPocoFoundation.so.9, needed by /usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libPocoMySQL.so, may conflict with libPocoFoundation.so.60
Finished building target: AuthorizationServer

But following the instructions from link1 I can see that my project has been properly configured and uses -L/home/{username}/poco-1.9.0-all/lib. Can anyone help me with this issue. Thanks in advance.
My eclipse project properties is as follow:
C/C++ Build->Settings->Tool Settings->GCC C++ Compiler->Includes->Include paths(-I) contains /home/{username}/poco-1.9.0-all/include
C/C++ Build->Settings->Tool Settings->GCC C++ Linker->Libraries->Libraries (-l) contains PocoFoundation, PocoData, PocoMySQL
C/C++ Build->Settings->Tool Settings->GCC C++ Linker->Libraries->Library search path(-L) contains /home/{username}/poco-1.9.0-all/lib

A: The error message says that -lPocoMySQL comes from /usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libPocoMySQL.so, not from /home/{username}/poco-1.9.0-all/lib.
Make sure that:

*

*you have built libPocoMySQL.so, and

*/home/{username}/poco-1.9.0-all is a valid path (it does not look like one).


text:
Q: Should I use an article when I'm talking about general facts in comparative structures? Should I use an article in the following case when I'm talking about a general facts in comparative sentence structure, like the following?
For example:
Choice 1: Elephant is bigger than fox.  Watermelon is bigger than grape.
Choice 2: An elephant is bigger than a fox. A watermelon is bigger than a grape.

A: Choice 1: Elephant is bigger than fox. Watermelon is bigger than grape.
This is wrong. It is grammatically incorrect.
Choice 2: An elephant is bigger than a fox. A watermelon is bigger than a grape.
Very good for general facts.
Choice 3: The elephant is bigger than the fox. The watermelon is bigger than the grape.
Not about general facts. This is about a specific elephant and a specific fox.
Choice 4: Elephants are bigger than foxes. Watermelons are bigger than grapes.
Very good for general facts.


text:
Q: How to fix this form fields to be perfect? I want this form fields just like the red line in this picture https://i.stack.imgur.com/gbvDs.png

input,
select,
textarea {
  width: 20%;
  padding: 12px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-left: 20px;
}

label {
  padding: 12px 12px 12px 0;
  display: inline-block;
}

.container {
  /* the form is inside this container */
  padding: 20px;
  margin: 20px;
  overflow: auto;
  text-align: center;
}

  <form method="post" enctype="multipart/form-data" id="form">
    profile picture
    <input type="file" name="image1" accept="image/*" required id="id_image1" />
    cover picture
    <input type="file" name="image2" accept="image/*" required id="id_image2" />

    Name: <input type="text" name="tag" maxlength="50" required id="id_tag" />
    <button type="submit" class="button">Upload</button>
  </form>

A: You can accomplish this with CSS Grid and a little padding.

.wrap,
.field-container {
  display: inline-grid;
}

.field-container {
  grid-template-columns: 1fr auto;
  padding-bottom: 0.5rem;
}

.field-container label {
  padding-right: 2rem;
  text-align: right;
}

    Profile picture
    <input type="text" id="profilePic">

    Cover picture
    <input type="text" id="coverPic">

    Name
    <input type="text" id="name">

jsFiddle

A: I changed your code this way, please check if it is suits what you desire:

   <form method="post" enctype="multipart/form-data" id="form">

            profile picture
            <input type="file" name="image1" accept="image/*" required id="id_image1" />

            cover picture
            <input type="file" name="image2" accept="image/*" required id="id_image2" />

            Name: <input type="text" name="tag" maxlength="50" required id="id_tag" />
            <button type="submit" class="button">Upload</button>

   </form>


text:
Q: Modelica "Resolve error : no match for overloaded binary operator " I'm using Dymola 2014 (Modelica) and trying to write the code of a model.
I am not able to "check" the model, Dymola gives me the following message.
Someone using Dymola told me that it may be a problem coming from a missing "else" but I don't see anything missing.
The conditions xxx.activePort at the beginning of every "if" come from a stateGraph loop in the code.
Please note that not all the code is here but I can post it if needed.
The check only returns that part of the code, so I assume that the problem is here.
You may also note that the entire code contains both equation and algorithm sections.
The code below is a part of the equation section.
I'm quite a noob with Modelica so it may be simple but I did not find anything to solve my problem on the internet.
Thank you !
Romain
Check of CHP.Composants.Stirling:

Resolve error: No match for overloaded binary operator
in the equation
if (PR1.activePort or PR2.activePort or PR3.activePort) then
 if (PR1.activePort) then
  Q_HX = 0;
  P_brut = 0;
  P_net = P_brut-P_auxiliaires-P_electronique;
 elseif (PR2.activePort) then
  Q_HX = Q_HX_nom*(1-exp( -(time-tps_debut_PR2)/Tau_PR_Q));
  P_brut = 0;
  P_net = P_brut-P_auxiliaires-P_electronique;
 elseif (PR3.activePort) then
  Q_HX = Q_HX_nom*(1-exp( -(time-tps_debut_PR2)/Tau_PR_Q));
  P_net = P_net_nom*(1-exp( -(time-tps_debut_PR3)/Tau_PR_P));
  P_brut = P_net+P_auxiliaires+P_electronique;
 else
  Q_HX = 0;
  P_net = 0;
  P_brut = 0;
 end if;
 mdot_comb = P_comb_nom/PCS_J_kg;
 mdot_condensats_max = mdot_comb*H2O_kg;
 V_H2O_exh = V_H2O*(1-mdot_condensats/mdot_condensats_max);
 DH_N2_exh = (H_Texh[1, 5]-H_T0[1, 5])*pc_N2_exh_w;
 DH_CO2_exh = (H_Texh[1, 6]-H_T0[1, 6])*pc_CO2_exh_w;
 DH_O2_exh = (H_Texh[1, 9]-H_T0[1, 9])*pc_O2_exh_w;
 DH_H2O_exh = (H_Texh[1, 10]-H_T0[1, 10])*pc_H2O_exh_w;
 dH_exh_sens = (DH_N2_exh+DH_CO2_exh+DH_O2_exh+DH_H2O_exh)/Mm_exh*1000;
 mdot_air = mdot_comb*V_a_kg*(1+exces_air);
 mdot_exh = mdot_comb+mdot_air;
 P_comb = mdot_comb*PCS_J_kg;
 Hdot_comb = mdot_comb*dH_comb;
 Hdot_air = mdot_air*cp_air*(T_air-T_0);
 Hdot_exh_sen = mdot_exh*dH_exh_sens;
 Hdot_exh_lat = L_v_H2O*(mdot_condensats_max-mdot_condensats);
 mdot_CO2 = mdot_comb*i_CO2_comb;
elseif (Fct_normal.activePort) then
 Q_HX = Q_HX_nom+C_charge*g+(T_cwi-T_cwi_nom)*c1+(T_cwi-T_cwi_nom)^2*c2+( mdot_cw-mdot_cw_nom)*d1+(mdot_cw-mdot_cw_nom)^2*d2;
 P_net = P_net_nom+C_charge*h+(T_cwi-T_cwi_nom)*e1+(T_cwi-T_cwi_nom)^2*e2+( mdot_cw-mdot_cw_nom)*f1+(mdot_cw-mdot_cw_nom)^2*f2;
 P_comb = P_comb_nom+C_charge*j+(T_cwi-T_cwi_nom)*a1+(T_cwi-T_cwi_nom)^2*a2+( mdot_cw-mdot_cw_nom)*b1+(mdot_cw-mdot_cw_nom)^2*b2;
 P_brut = P_net+P_auxiliaires+P_electronique;
 mdot_comb = P_comb/PCS_J_kg;
 mdot_condensats_max = mdot_comb*H2O_kg;
 V_H2O_exh = V_H2O*(1-mdot_condensats/mdot_condensats_max);
 DH_N2_exh = (H_Texh[1, 5]-H_T0[1, 5])*pc_N2_exh_w;
 DH_CO2_exh = (H_Texh[1, 6]-H_T0[1, 6])*pc_CO2_exh_w;
 DH_O2_exh = (H_Texh[1, 9]-H_T0[1, 9])*pc_O2_exh_w;
 DH_H2O_exh = (H_Texh[1, 10]-H_T0[1, 10])*pc_H2O_exh_w;
 dH_exh_sens = (DH_N2_exh+DH_CO2_exh+DH_O2_exh+DH_H2O_exh)/Mm_exh*1000;
 mdot_air = mdot_comb*V_a_kg*(1+exces_air);
 mdot_exh = mdot_comb+mdot_air-mdot_condensats;
 Hdot_comb = mdot_comb*dH_comb;
 Hdot_air = mdot_air*cp_air*(T_air-T_0);
 Hdot_exh_sen = mdot_exh*dH_exh_sens;
 Hdot_exh_lat = L_v_H2O*(mdot_condensats_max-mdot_condensats);
 mdot_CO2 = mdot_comb*i_CO2_comb;
elseif (RF.activePort) then
 Q_HX = Q_HX_nom*exp( -(time-tps_debut_RF)/Tau_RF);
 P_brut = E_elec_RF/t_fin_RF;
 P_net = P_brut-P_auxiliaires-P_electronique;
 mdot_comb = 0;
 mdot_air = P_comb_nom/PCS_J_kg*V_a_kg*(1+exces_air);
 mdot_exh = mdot_air;
 P_comb = 0;
 Hdot_comb = 0;
 Hdot_air = mdot_air*cp_air*(T_air-T_0);
 Hdot_exh_sen = mdot_exh*cp_air*(T_exh-T_0);
 Hdot_exh_lat = 0;
 mdot_CO2 = 0;
 mdot_condensats_max = 0;
 V_H2O_exh = 0;
 DH_N2_exh = 0;
 DH_CO2_exh = 0;
 DH_O2_exh = 0;
 DH_H2O_exh = 0;
 dH_exh_sens = (DH_N2_exh+DH_CO2_exh+DH_O2_exh+DH_H2O_exh)/Mm_exh*1000;
elseif (Arret.activePort) then
 Q_HX = 0;
 P_brut = 0;
 P_net = P_brut-P_electronique;
 mdot_comb = 0;
 mdot_air = 0;
 mdot_exh = 0;
 P_comb = 0;
 Hdot_comb = 0;
 Hdot_air = 0;
 Hdot_exh_sen = 0;
 Hdot_exh_lat = 0;
 mdot_CO2 = 0;
 mdot_condensats_max = 0;
 V_H2O_exh = 0;
 DH_N2_exh = 0;
 DH_CO2_exh = 0;
 DH_O2_exh = 0;
 DH_H2O_exh = 0;
 dH_exh_sens = (DH_N2_exh+DH_CO2_exh+DH_O2_exh+DH_H2O_exh)/Mm_exh*1000;
else
 Q_HX = 0;
 P_brut = 0;
 P_net = P_brut-P_electronique;
 mdot_comb = 0;
 mdot_air = 0;
 mdot_exh = 0;
 P_comb = 0;
 Hdot_comb = 0;
 Hdot_air = 0;
 Hdot_exh_sen = 0;
 Hdot_exh_lat = 0;
 mdot_CO2 = 0;
 mdot_condensats_max = 0;
 V_H2O_exh = 0;
 DH_N2_exh = 0;
 DH_CO2_exh = 0;
 DH_O2_exh = 0;
 DH_H2O_exh = 0;
 dH_exh_sens = (DH_N2_exh+DH_CO2_exh+DH_O2_exh+DH_H2O_exh)/Mm_exh*1000;
end if;

Missing declarations.

Check aborted.

ERROR: 1 error was found

A: I finally solved this problem.
The problem was due to a wrong declaration, in the code the coefficient "j" was declared as an array while here a scalar was needed.


text:
Q: Elasticsearch, how to make a query that matches strings with spaces I am in learning process of ElasticSearch and having hard time matching certain cases.
For example I have product name: "SkyProdigy 130" and I am trying to write a query that will match this product name when someone types "sky prodigy". Also, another example for the manufacturer "Magpul" I would like to be able to match even if someone type "mag pul", etc.
I have managed to make this work with fuzzy query, but I am looking for a more organic way to achieve this through analyzers and correct mappings.
Can someone recommend the best approach for this case?


text:
Q: Ambiguous reference to member jsonobject with options Error with Parse Cloud Code Response When i doing Parse Cloud function with Parse iOS SDK Swift 3
PFCloud.callFunction(inBackground: "callFromApp", withParameters: ["Hello" : "Boy"]) { (obj:Any?, error:Error?)->Void in
            let jsonObject = JSONSerialization.jsonObject(with: obj! as! JSONObject, options: .allowFragments)
}

Im getting error Ambiguous reference to member jsonObject with options.


text:
Q: scatter plot with different colors and labels I have a pandas dataframe.  It looks like this:
Im trying to create scatter plot with different colors for each point.  I tried:
df.plot.scatter(x='x',y='y',c=df.colors.tolist(), legend=True)

I get the scatter plot allright.  But im not able to show label that "Financials" is associated with color '#4ce068'.
How do i do that here?  Thanks
I tried:
df.plot.scatter(x='x',y='y',c=df.colors.tolist(),label=df.key.unique.tolist())

This almost works but the fact there there are too many labels and the colors associate with the label is hard to see.
I would like to have the key shows with associated color preferably on top of the chart i.e next to title.  Is that possible?
My dataframe in dictionary format:

{'key': {0: 'Financials',
1: 'Consumer Discretionary',
2: 'Industrials',
3: 'Communication Services',
4: 'Communication Services',
5: 'Consumer Discretionary',
6: 'Health Care',
7: 'Information Technology',
8: 'Consumer Discretionary',
9: 'Information Technology'},
'x': {0: 1630000.0,
 1: 495800000.0,
 2: 562790000.0,
 3: 690910000.0,
 4: 690910000.0,
 5: 753090000.0,
 6: 947680000.0,
 7: 1010000000.0,
 8: 1090830000.0,
 9: 1193600000.0},
 'y': {0: 0.02549175,
 1: 0.0383163,
 2: -0.09842154,
 3: 0.03876266,
 4: 0.03596279,
 5: 0.01897367,
 6: 0.06159238,
 7: 0.0291209,
 8: 0.003931255,
 9: -0.007134976},
'colors': {0: '#4ce068',
 1: '#ecef4a',
 2: '#ff3c83',
 3: '#ff4d52',
 4: '#ff4d52',
 5: '#ecef4a',
 6: '#00f1d1',
 7: '#d9d9d9',
 8: '#ecef4a',
 9: '#d9d9d9'}}

A: If you don't mind using plotly you can try
import pandas as pd
import plotly.express as px

px.scatter(df, 'x', 'y', color="key", color_discrete_sequence=df["colors"].tolist())

But given your choice of colors just px.scatter(df, 'x', 'y', color="key") will look better

A: Here's one way to do it:
fig, ax = plt.subplots()
for i in df.colors.unique():
    df_color = df[df.colors==i]
    df_color.plot.scatter(x='x',y='y', ax=ax, c=i, label=df_color.key.iloc[0])

ax.legend(loc='best')

You'll get


text:
Q: Path is drawn again after submit, how to clear previous path? fellow newbie in google maps API and stackoverflow.
I am creating an app where I can draw multiple routes on the map. At first, there's only one textbox and if I type an address and click the "calculate" button, it works fine.
However, if I click it again the path is drawn again. (The path is dark blue, meaning there's a blue route on top of another)
Is there a way to somehow refresh the map or clear the path that was previously drawn?
My code is something like this. I wrote it in such a way that the textboxes' values are added to an array and this array is what I'll use to calculate the route.
form.onsubmit = function () {
        //var okay = true;
        var userAddressArray = [];
        $("input.address").each(function( index ) {
        userAddressArray.push($(this).val());

        });
        num = 1;
        for(var i=0; i < userAddressArray.length; i++){
            directionsVisible = false;
            destination = userAddressArray[i];
            calcRoute(destination, num);
            num = num + 1;

        }

        return false;
    }

Here's my calcRoute function:
   function calcRoute(inputAddress, number) {
        if (!geocoder) {
            geocoder = new google.maps.Geocoder();
        }

        var geocoderRequest = {
            address: inputAddress
        }

        geocoder.geocode(geocoderRequest, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);

                destinationLoc = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                //var dest = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());

             // compare this to an array of pre-loaded points
                getClosestPath(destinationLoc);
             //drawing the path
               requestDirections(closest, destinationLoc, inputAddress, destinationLoc, number);

            }

        });

    }

requestDirections function:
var directionsService = new google.maps.DirectionsService();

function requestDirections(start, end, address, number) {
clearOverlays();

directionsService.route({
    origin: start,
    destination: end,
    avoidTolls: true,
    travelMode: google.maps.TravelMode.WALKING
}, function (result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        renderDirections(result, address, number);
    }

    if (status == google.maps.DirectionsStatus.NOT_FOUND) {
        alert("One of the locations you entered could not be geocoded.");
    }

    if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
        alert("Invalid address entered, please enter a valid address.");
    }
});

}
renderDirections function:
function renderDirections(result, address, number) {

var myRoute = result.routes[0].legs[0];

for (var i = 0; i < myRoute.steps.length; i++) {
}
    var marker = new google.maps.Marker({
    position: myRoute.steps[i - 1].end_point,
    map: map,
    icon: "https://maps.gstatic.com/mapfiles/ms2/micons/green-dot.png"

});

  var directionsRenderer = new google.maps.DirectionsRenderer({
        map: map,
        suppressMarkers: true,
        draggable: true
    });
  markersArray.push(marker);

  directionsRenderer.setMap(map);
  //polylineOpts.setMap(map);
  directionsRenderer.setDirections(result);

}

I hope this is detailed enough, otherwise, let me know. I hope you can help me with this one!

A: Make your directionsRenderer global (your original code creates a new one for every directions request):
var directionsRenderer = null;
function renderDirections(result, address, number) {

var myRoute = result.routes[0].legs[0];

for (var i = 0; i < myRoute.steps.length; i++) {
}
    var marker = new google.maps.Marker({
    position: myRoute.steps[i - 1].end_point,
    map: map,
    icon: "https://maps.gstatic.com/mapfiles/ms2/micons/green-dot.png"

});

  directionsRenderer = new google.maps.DirectionsRenderer({
        map: map,
        suppressMarkers: true,
        draggable: true
    });
  markersArray.push(marker);

  directionsRenderer.setMap(map);
  //polylineOpts.setMap(map);
  directionsRenderer.setDirections(result);

}


text:
Q: Keycloak behind ingress with non-standard port I successfully installed a keycloak with the bitnami helm chart.
the ingress settings are:
          ingress:
            enabled: true
            hostname: "kc-test.local"

My ingress is listening on port 18000 (locally). If I now call
http://kc-test.local:18000 it works, but all links contain the url without port, e.g.:
http://kc-test.local/admin
The setting:
          extraEnvVars:
            - name: KC_HOSTNAME_URL
              value: "http://kc-test.local:18000"

Any ideas, how to make my ingress (nginx) pass the requested port to keycloak?
EDIT
Following annotations on nginx ingress do not help:
            annotations:
              nginx.ingress.kubernetes.io/server-snippet: |
                proxy_set_header X-Forwarded-Port $server_port;
                proxy_set_header X-Forwarded-Proto http;

A: Maybe remplace or add KEYCLOAK_FRONTEND_URL en var.
Source docker hub documentation
https://hub.docker.com/r/jboss/keycloak/


text:
Q: How can I write script to check CSV file for blank cells from existing csv? How can I script loop an existing csv and output to a new file in the output similar below to blankfruits.csv still keeping the header title but capturing the null cells there after and stop once all found.
# fruitbowl.csv

fruit bowl A
- - - - -
apples
bananas
pears
coconuts

fruit bowl B
- - - - -
apples
bananas
pears
coconuts

fruit bowl C
- - - - -

fruit bowl D
- - - - -
apples
bananas
pears
coconuts

fruit bowl E
- - - - -

fruit bowl F
- - - - -

The idea will be for the bash script or maybe python to read the existing CSV and output to new file with
# blankfruits.csv

fruit bowl C
- - - - -

fruit bowl E
- - - - -

fruit bowl F
- - - - -

A: here is a quick one-liner: (based on your example)
$ awk -v RS="" '{a=gsub(ORS,ORS);if(a==1)print $0 ORS}' YourInput
fruit bowl C
- - - - -

fruit bowl E
- - - - -

fruit bowl F
- - - - -


text:
Q: How to fetch distinct values from multiple rows of select query? I have used query as
string getPlayers = " Select Player1,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' ";

It gives result as multiple rows that fulfills the condition.
But I want to store values of distinct Player1,Player2,Player3,Player4,Player5 in variables  returned from select query, so that i can use these values for further case.
How can i do this ?
Please help me. I am very confused.
EDITED :
I got the result of select query as -
(1,2,2,4,5)
(2,3,1,4,5)
(4,3,5,1,2)

Where 1,2,3,4,5 are userids(players).
I want store these userids in variables as -
p1=1 , p2=2 , p3=3 ,p4=4, p5=5

A: string getPlayer1 = (" select var1 from (" Select distinct Player1 as var1 ,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' "));

var1 will have a value of player1. Repeat this for all other players. Hope this is what you want.


text: Q: How is DefineSection(...) used in an ASP.NET Core view? In an ASP.NET Core 3.1 view, I want to know if (and how) the DefineSection(...) can be used to implement a section, preferably by passing in the section name as a parameter, instead of using @section.


text:
Q: When to use proper version of singleton thread-safe implementation? I have a stateless helper-like class which I want to make as a singleton. This class will be shared across different threads.
Am I correct that in this case (instance does not require huge memory allocation size and thus can be loaded several times without resources and performance impact) there is no need in implementing such a singleton with proper multi-threading lazy initialization strategy (Double Checked Locking & volatile, On Demand Holder idiom, Enum Singleton, Synchronized Accessor)?
Is it right to implement such a singleton with a simple non-multi-threading lazy initialization version strategy (like in the code below) in order to have less amount of boilerplate code?
public class Singleton {
    private static Singleton INSTANCE;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
}

And only in case when state of the singleton class shared across different threads it is required to add proper multi-threading version of a singleton initialization?

A: If your class is entirely stateless - make it a util class with only static functions.
If you have state and want a semi-singleton I would say that what you have done is misleading since there is no way for the reader to know if you were aware of the fact that you can get multiple instances or not. If you decide to stick with your posted code - rename it multiton or document the behaviour carefully. But don't do it just to reduce boilerplate though - you are in fact creating more problems for the reader than you are removing.
In my opinion the "Initialization on Demand Holder" idiom is the nicest singleton pattern. But I would recommend against Singletons in general. You would be better off passing a reference to a shared instance to your thread when you start it.

A: To answer your question... No, it's not correct.
You say it's OK for it to be loaded several times, but in that case then it's not a singleton. The defining characteristic of a singleton is that there can only ever be one instance.
If it's OK for there to be several, then why make it a singleton at all?
If it's just stateless util methods then why not just make the static?


text:
Q: Monte-Carlo simulation of repeated-measures ANOVA I want to conduct a Monte-Carlo simulation of a repeated-measures ANOVA. The random numbers used for the simulation need to have specified mean values, standard deviations and correlations between the levels of the repeated-measures variable.
Generating random numbers with a specified correlation matrix is not the problem. I do this using a Cholesky decomposition of the correlation matrix with which the (normally distributed) random numbers are multiplied.
A problem occurs if there are both between-subjects and within-subject variables, e.g.,
AB
CD
with the columns (AC and BD) being the levels of a within-subject variable and the rows (AB and CD) being levels of a between-subjects variable. The columns must have a specified correlation (e.g., 0.5), but the mean values and standard deviations of A, C, B, and D must be different. If I start generating normally distributed random numbers for column AC and BD and then multiply the two columns with a Cholesky-decomposed correlation matrix, the correlation between both columns is correct (0.5). However, as soon as I add different expectation values to A and C or B and D the correlation changes.
So my question is: How can I generate random numbers that have a specified correlation between columns and have different mean values/standard deviations between different rows?


text:
Q: Insert a value into a reversed ArrayList in Java I am trying to insert a value given by the user into an ArrayList in Java. The values should be in descending order so that if the user provides e.g. 6, 2, 19 the output should be 19, 6, 2. My idea was to insert the first element and then all other inputs would be compared to the other elements and inserted accordingly.
getScore() receives a value from another class and rank() places one value at a time.
private ArrayList<Integer> sortedInts = new ArrayList<>();

private String rank() {
    if(sortedInts.isEmpty()){
        sortedInts.add(0, getScore());
    } else {
        for (int i = 0; i <= sortedInts.size(); i++) {
            if(getScore() >= sortedInts.get(i) && getScore() <= sortedInts.get(i+1))
                sortedInts.add(i, getScore());
        }
    }
    int position = sortedInts.indexOf(getScore());
    if(position % 10 == 0) {
        if(position == 0)
            return "1st";
        else
            return position + "st";
    }
    else if(position % 10 == 1){
        if(position == 1)
            return "2nd";
        else
            return position + "nd";
    }
    else if(position % 10 == 2) {
        if(position == 2)
            return "3rd";
        else
            return position + "rd";
    }
    else
        return position + "th";
}


text:
Q: Nested if and countif in google sheets I am trying to use the following formula:
=if(A16="1",(COUNTIF('responses'!AF:AG,B16))>0,"Yes",if(A16="2",(COUNTIF('responses 1'!AF:AG,B16)))>0,"Yes",COUNTIF(' responses'!D:E,B16)>0,"Yes","No")

Basically I'm getting a message back saying there are too many arguments. This is the first time I have tried to use if nested if and countif functions and I'm really struggling. Any help greatly appreciated.

A: try:
=IF(A16="1",
 IF(COUNTIF('responses'!AF:AG, B16)>0, "Yes",
 IF(A16="2",
 IF(COUNTIF('responses 1'!AF:AG, B16)>0, "Yes",
 IF(COUNTIF(' responses'!D:E, B16)>0, "Yes", "No")

A: would this work?
=if(A16="1",COUNTIF('responses'!AF:AG,B16))>0,"Yes", "No", (if(A16="2",(COUNTIF('responses 1'!AF:AG,B16)))>0,"Yes", "No"),COUNTIF(' responses'!D:E,B16)>0,"Yes","No"


text:
Q: SQL query retorna valor duplicados e com erro Tenho a seguinte query mas está a retornar resultados duplicados e errados. No Arthur deveria aparecer 0 e não 30.

A: Ja cheguei a conclusão de como faz:
SELECT Player_name, Subscription_id,Date_subscription,Amount_paid,Attendance_id,Training_date
FROM PLAYER p,SUBSCRIPTION s, Attendance a
WHERE p.SUBSCRIPTION_SUBSCRIPTION_ID = s.SUBSCRIPTION_ID and a.PLAYER_PLAYER_ID = p.PLAYER_ID;


text:
Q: open paper-dialog from another component I'm using polymer 2 and the paper-dialog component.
I have another custom web component which when a button is clicked it needs to display a paper-dialog which is in another component.
From the below test components you can see that:
The click event calls:
showDialog()
{
    var testDialog = new TestDialog();
    testDialog.open();
}

Which then calls:
open()
{
    this.$.dialog.open();
}

The error I get is that this.$ is undefined.
Now this does make some sense as I assume that $ isn't populated until the template is rendered.
So I guess the question is how do I get the dialog template to render so that I can then open it?
Calling component:
    <link href="../../../bower_components/polymer/polymer.html" rel="import">
<link rel="import" href="test-dialog.html">

<dom-module id="time-display-test">
    <template>
        <style include="shared-styles">

        </style>

<button id="time" >Show</button>
</template>

    <script>
        class TimeDisplay extends Polymer.Element {
            static get is() {
                return 'time-display-test';
            }

            static get properties() {
             return {
                };
            }

            connectedCallback()
            {
                super.connectedCallback();

                this.$.time.onclick = ()=>{ this.showDialog(); };
            }

            showDialog()
            {
                var testDialog = new TestDialog();
                testDialog.open();
            }

        }
        customElements.define(TimeDisplay.is, TimeDisplay);
    </script>
</dom-module>

The paper dialog component:
    <link rel="import"     href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/paper-dialog/paper-dialog.html">

<dom-module id="test-dialog">
    <template>
        <style include="shared-styles">
        </style>
        <!-- backdrop autoCloseDisable -->
        <paper-dialog id="dialog">
            <paper-dialog-scrollable>
                    Hello World
            </paper-dialog-scrollable>
        </paper-dialog>
    </template>

    <script>
        class TestDialog extends Polymer.Element {

            static get is() {
                return 'test-dialog';
            }

            static get properties() {
                return {

                };
            }

            open()
            {
                this.$.dialog.open();
            }

        }
        customElements.define(TestDialog.is, TestDialog);

    </script>
    </dom-module>

A: You must first append the new component to the dom to access it´s dom. this.$.* will only be initialized when the component was appended to the dom.
showDialog()
{
    var testDialog = new TestDialog();
    this.appendChild(testDialog);
    testDialog.open();
}


text:
Q: Clear Gridview each time click a button My code populate 1st row inside the grid view. After page loads and type 1st row data I can populate 10 rows by click the copyButton. but when I change 1st row data and click again it shows 20 rows. But I need only 10 rows that has only updated data which is new entry. How can I update grid view when i click second time by deleting the old record and populated by 1st new entered values?
Example:
ID  Explanation  teacher
--- ----         --------
0   hello        45
1   hello        45
2   hello        45
.   .            .
.   .            .
.   .            .
10  hello        45

=======================================

A: Insert this line immediately before the for loop to clear the collection of rows in the DataGridView:
dataGridView1.Rows.Clear();

Then you can probably remove this line (if I'm understanding what you're trying to do):
dataGridView1.Rows.RemoveAt(0);

Also, you said you want 10 rows, but you're inserting 16 in your loop. Might want to double-check that.

A: Please note that, dataGridView1.Rows.Clear(); only clears Rows in DataGridView. If you want to clear whole Table (Rows and Columns) and dataGridView1.DataSource = null doesn't work (If your Data is not bound by Table) try this:
dataGridView1.Columns.Clear();


text:
Q: oauth 1.0 for wp api and ionic framework For the Oauth 1.0 , i am already get the access token from the server.
access_token is 'Kdsfauidf343daasdfasewr', but on ionic framework, how do i use access_token?
i try following code on ionic framework
$http({method: 'GET', headers: {'Authorization' : 'Token Kdsfauidf343daasdfasewr '}
})

it return 403 Forbidden error.

A: Only set an access token is not sufficient. You'll have to use a signature for each request to the WP API. Especially you can read this part of WP API Oauth documentation on github:
Otherwise a more detailed article I found on Nic Raboy's blog: