text:
Q: Why this program is crashing? #include <stdio.h>
#include <stdlib.h>

int main()
{
    int i = 0, j = 0;
    int *p = (int *)malloc(1*4);
    for(;;)
    {
        scanf("%d", p+i);
        if(*(p+i) == 42)
        {
            break;
        }
        i++;
    }
    for(j = 0; j < i; j++)
    {
        printf("%dn", j);
    }
}

Since I knew that I have  created only one block of 4 bytes but since we get the base address stored in p then I could have explored the address under the loop as much as I want i.e. I would store the values in contiguous memory location until 42 is encountered, The problem is that the program is working fine for 5 inputs but the program is getting crashed if the inputs are exceeding more than five.
I found the solution for this to be Undefined behaviour as defiened by Alex Lop But further I want to know why this works????
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i=0,j=0;
    int *p=(int *)malloc(1*4);
    for(i=0;i<20;i++)
    {
        printf("%d\n",p+i);
    }
}

Here on printing the address outside the allocated bunch of memory it does not crashes, it finally prints the address which I have not allocated.

A: What yo actually do is called "undefined behavior".
You allocate 4 bytes and then store into that buffer integers. It works fine for the first integer (or maybe two if sizeof(int)==2 on your machine) but for the next integer the behavior becomes undefined. It may segfault immediately and it may take more similar stores until you crash. The number of inputs '5' here doesn't mean anything, it may behave differently on different machines and with different compilation flags.
According to what I see (or assume from the code), you want to accept inputs until you get "42". So actually you don't have to store the input values. Here is your code without the useless stuff:
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int in;

    for(;;)
    {
        scanf("%d",&in);
        printf("%d\n", in); // adding this line because it was explained to
                            // me that the input values should be printed and
                            //it is something I couldn't understand from the original code.
        if(in == 42)
        {
            break;
        }
    }

    return 0;
}

A: You need to realloc your dynamic array p in order to store all values (i values). In your code, you've space for only one integer (1*4).
Try this:
#include<stdio.h>
#include<stdlib.h>
int main() {
    int i=0,j=0;
    int *p=(int *)malloc(1*sizeof(int)); //You can use sizeof(int) instead of 4
    for(;;) {
        p = realloc(p, (i+1)*sizeof(int)); //p can now store i integers
        scanf("%d",p+i);
        if(*(p+i)==42) {
            break;
        }
        i++;
    }
    for(j=0;j<i;j++) {
        printf("%d\n",j);
    }
}

A: I don't know where to begin. Where did you even get the idea of doing this to yourself?
First, you have to specify that you want to allocate in blocks with sizeof(int). Because the actual value might change for different implementations (even if it usually is 4).
Your program is not working fine. You can't explore the address as much as you want because you're running into undefined behaviour. You have allocated 4 bytes but are accessing memory beyond what you've allocated. Doesn't matter how many iterations it takes to crash (could've been 1 or 2, or 100), it's just wrong.


text:
Q: Texture loaded and bound, but fragment shader doesn't render it I'm trying to draw a cube with an FBO texture. The texture is rendered to correctly (which I can see in gDebugger), but it doesn't render on the cube. I thought that this might be a problem with the FBO texture so I loaded an ordinary texture and tried it as well, but I get the same problem, just a black cube.
Stepping through the program in gDebugger, I can see that the texture is both loaded correctly and bound, but nothing is drawn. There also doesn't seem to be any problems with the texcoords. Note that I've also tried to output a solid color in the fragment shader which works correctly.
This is my vertex shader:
#version 420

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

layout(location = 0) in vec3 vertex;
layout(location = 1) in vec2 texcoord;

out vec2 f_texcoord;

void main() {
    gl_Position = projection * view * model * vec4(vertex, 1.0);
    f_texcoord = texcoord;
}

And this is my fragment shader:
#version 420

uniform sampler2D tex;

in vec2 f_texcoord;

out vec4 gl_FragColor;

void main() {
    gl_FragColor = texture2D(tex, f_texcoord);
}

And this is where I draw the cube:
ShaderManager::Get("world")->Use();
glBindVertexArray(cube_vao);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);

I must be blind, because I see no errors.
(Also, please note that I am using SFML and GLEW for context creation and extensions.)
EDIT:
I don't know if this will be helpful, but this is how I set up the cube VBO, uniforms, etc.:
glClearColor(1.0, 0.0, 0.0, 1.0);

glEnable(GL_DEPTH_TEST);

glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
sf::Image img;
img.LoadFromFile("test.png");
img.FlipVertically();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.GetWidth(), img.GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.GetPixelsPtr());
glBindTexture(GL_TEXTURE_2D, 0);

ShaderTime = 0.0;
camz = -4.0f;
rotation_y = 0.0f;

Shader* shader = ShaderManager::Load("shader", "fx.vert", "fx.frag");
Shader* world = ShaderManager::Load("world", "world.vert", "world.frag");
shader->Use();
glUniform1f(glGetUniformLocation(shader->GetId(), "time"), ShaderTime);
world->Use();
glm::mat4 proj = glm::perspective(60.0f, (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 0.1f, 1000.0f);
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, camz));
glm::mat4 model;
glUniformMatrix4fv(glGetUniformLocation(world->GetId(), "projection"), 1, GL_FALSE, glm::value_ptr(proj));
glUniformMatrix4fv(glGetUniformLocation(world->GetId(), "view"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(world->GetId(), "model"), 1, GL_FALSE, glm::value_ptr(model));
glUniform1i(glGetUniformLocation(world->GetId(), "tex"), 0);

glGenVertexArrays(1, &cube_vao);
glBindVertexArray(cube_vao);
glGenBuffers(1, &cube_vbo);
glBindBuffer(GL_ARRAY_BUFFER, cube_vbo);

GLfloat* data = new GLfloat[5 * 36] {
    // Front
    -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,     -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,      1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 1.0f, 1.0f,       1.0f, -1.0f, 1.0f, 1.0f, 0.0f,      -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,

    // Back
    -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,    -1.0f, 1.0f, -1.0f, 0.0f, 1.0f,     1.0f, 1.0f, -1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, -1.0f, 1.0f, 1.0f,      1.0f, -1.0f, -1.0f, 1.0f, 0.0f,     -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,

    // Top
    -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,      -1.0f, 1.0f, -1.0f, 0.0f, 1.0f,     1.0f, 1.0f, -1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, -1.0f, 1.0f, 1.0f,      1.0f, 1.0f, 1.0f, 1.0f, 1.0f,       -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,

    // Bottom
    -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,     -1.0f, -1.0f, -1.0f, 0.0f, 1.0f,        1.0f, -1.0f, -1.0f, 1.0f, 1.0f,
    1.0f, -1.0f, -1.0f, 1.0f, 1.0f,     1.0f, -1.0f, 1.0f, 1.0f, 1.0f,      -1.0f, -1.0f, 1.0f, 0.0f, 1.0f,

    // Left
    -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,    -1.0f, 1.0f, -1.0f, 0.0f, 1.0f,     -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
    -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,      -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,     -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,

    // Right
    1.0f, -1.0f, -1.0f, 0.0f, 0.0f,     1.0f, 1.0f, -1.0f, 0.0f, 1.0f,      1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 0.0f, 1.0f,       1.0f, -1.0f, 1.0f, 0.0f, 0.0f,      1.0f, -1.0f, -1.0f, 0.0f, 0.0f
};

glBufferData(GL_ARRAY_BUFFER, (5 * 36) * sizeof(GLfloat), data, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLvoid*)(0));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLvoid*)(sizeof(GLfloat) * 3));

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

A: ===EDIT===
It looks like you're missing the texture setup for the minification filter, which is a problem if you're not using a mipmapped texture. See here: http://www.opengl.org/wiki/Common_Mistakes#Creating_a_complete_texture

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format ggplot2 axis labels such that only numbers > 9999 have commas I'm trying to adhere to a publication style guide whereby only numbers with 5 or more digits have commas. Have searched this but not found a way to override the defaults when using 'labels=comma.' Below is an example:
 require(dplyr)
 require(ggplot2)
 require(scales)

 # create mock dataframe
 temp <- mpg %>% mutate(newvar=(hwy*300))

 ggplot(temp, aes(x=cyl, y=newvar)) + geom_point() +
 scale_y_continuous(labels=comma) +
 labs(title="When using 'labels=comma'...",
      subtitle="How format axis labels such that commas only appear for numbers > 9999?")

Using this example, would like the lowermost y-axis labels to read "4000", "6000" etc. Could achieve this manually but that's not worth the bother, as have many graphs with scales encompassing this range. Any suggestions?

A: We can use an anonymous function within scale_x_continuous:
library(scales)
library(ggplot2)

# generate dummy data
x <- 9998:10004
df <- data.frame(x, y = seq_along(x))

ggplot(df, aes(x = x, y = y))+
    geom_point()+
    scale_x_continuous(labels = function(l) ifelse(l <= 9999, l, comma(l)))


text:
Q: Table not sitting within the a div correctly There is a table on the bottom left of this screen which fits within each tab when you click on it.
It works ok in FF & IE but for some reason Safari pushes it out to the right.
http://www.yellostudio.co.uk/tm/#
Any ideas would be very much appreciated?

A: Just a suggestion, your HTML doesn't validate, especially with regard to <tr> elements, this could be your problem.
To be fair, even if it isn't the problem getting your HTML valid is generally a good thing :-)

A: Don't you just need to change this
div.panes div { display:none; width:208px;}

to this
div.panes div { display:none; width:208px; float:left; }


text:
Q: How can I update a DS.Model with response json from store.commit()? Given the models:
Blog.Post = DS.Model.extend({
    title: DS.attr('string'),
    tags:  DS.hasMany('Blog.Tag', { embedded: true })
});

Blog.Tag = DS.Model.extend({
    foo: DS.attr('string'),
    bar: DS.attr('string')
});

And the instance:
var myPost = Blog.Post.createRecord({ id: 45, title: 'Foo Bar' })

When I do myPost.store.commit() (via ember-data's DS.RESTAdapter) my server returns a list of automatically generated tags that should be applied to myPost.  Example response json:
{
  posts: [
    {
      id: 45,
      title: 'Foo Bar',
      tags: [
        { id: 1, foo: 'bar1' },
        { id: 2, foo: 'bar2' }
      ]
    }
  ]
}

I'd expect that myPost would end up with the two tags as returned by the json, but I get this error instead:
Error: <DS.StateManager:ember448> could not respond to event invokeLifecycleCallbacks in state rootState.loaded.updated.uncommitted.

What am I doing wrong here?
Edit: clarified json to include ids per @MikeAski's comment. The example given is a simplified version of my actual case--the actual case does include tag ids.

A: First of all you need to 'mirror' relations between model's:
   Blog.Post = DS.Model.extend({
        title: DS.attr('string'),
        tags:  DS.hasMany('Blog.Tag', { embedded: always })
    });

    Blog.Tag = DS.Model.extend({
        foo: DS.attr('string'),
        bar: DS.attr('string'),
        post: DS.belongsTo('Blog.Post')
    });

Then you will need to add mappings to your adapter:
Blog.RESTSerializer = DS.RESTSerializer.extend({
  init: function() {
    this._super();

    this.map('Blog.Post',{
      tag:{embedded:'always'},
    });
  }
});

And add post_id to Tag in your JSON.


text:
Q: How are the words on review audits determined? I've gotten quite a few review audits while reviewing suggested edits lately, and I was wondering, How are the words used determined?
I know they're supposed to be easy to spot and obviously nonsense, but still I've seen many different words/phrases used. Is it completely random, or is there like a method to determine what's going to be used based on the tags/question?


text:
Q: How to update all users when admin login? I am preparing a MLM website in which I have to update all users single leg income, direct income and referral income when admin login. I was used same codes for individual updates I;e for each users.
For Eg: I am user and I am going to check my earnings, I have to login and check...So at the time of login I am updating all earnings of that user in database. So if user want to see updated earning,each time they have to singout and login again...simple. But in this case when user login...they passing a userid in session...through which I am synchronizing all incomes.
This is all about a particluar user...and may be their will be several users, and code for each as same.
But when we taking about admin, than??
They have to see earnings of all users in one page.  I want help in that...I think I have to run all codes, single leg income, direct income and refral income in while loop..So all users must selected one by one and all incomes updating.
By bit confused ...please help...I thought I explain best of my knowledge...
Codes here:
Direct Income:
<?php
$userid=$_SESSION['userid'];
$sql="SELECT * from personal where userid='$userid'";
$query=mysqli_query($conn, $sql);
while($row=mysqli_fetch_array($query))
{
     $id=$row['id'];
}
    $sql="SELECT * from personal where id>'$id' limit 10";
    $query=mysqli_query($conn,$sql);
    $a=0;
    while($row=mysqli_fetch_array($query))
    {

     $userid=$row['id'];
     $username=$row['userid'];
     $sponserid=$row['sponserid'];
     $amount=$row['amount'];
    if($row['amount']==2500)
    {
         $total1=2500;
    }
    else if($row['amount']==5000)
    {
    $total1=5000;
    }
    else if($row['amount']==10000)
    {
    $total1=10000;
    }
    else
    {
    $total1=0;
    }
    $i=array(0.05,0.02,0.01,0.005,0.0025,0.0025,0.0025,0.0025,0.0025,0.0025);

    $total[]=$total1*$i[$a];
    $a++;
    $level_income = array_sum($total);
    }
$qry="update personal set direct_income='$level_income' where userid='".$_SESSION['userid']."'";
    mysqli_query($conn,$qry);
$_SESSION['level_income']=$level_income;

?>

Referral Income Code
<?php
include('head.php');

$query = "SELECT userid,amount FROM personal WHERE sponserid='$_SESSION[userid]'";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result) or die(mysqli_error($conn)))

{
$total[]=$row['amount'];
$income=array_sum($total);
$_SESSION['refral_income']=$income * 0.05;
$qry="update personal set refral_income='$_SESSION[refral_income]' where userid='".$_SESSION['userid']."'";
}

?>

Single Leg Income Code:
<?php
include('head.php');
$sql="SELECT * from personal where userid ='$_SESSION[userid]'";
$query=mysqli_query($conn, $sql);

while($row=mysqli_fetch_array($query))
{
     $id=$row['id'];
}
$sql="SELECT * from personal where id>'$id'";
$query=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($query))
    {

     $userid=$row['id'];
     $username=$row['userid'];
     $fullname=$row['fullname'];
     $sponserid=$row['sponserid'];
     $amount=$row['amount'];
    if($row['amount']==2500)
    {
         $total1=10;
    }
    else if($row['amount']==5000)
    {
    $total1=20;
    }
    else if($row['amount']==10000)
    {
    $total1=40;
    }
    else
    {
    $total1=0;
    }

    $total[]=$total1;

        $single_leg_income=array_sum($total);

    }

    $_SESSION['income']=$single_leg_income;
    $qry="update personal set single_leg_income='$single_leg_income' where userid='".$_SESSION['userid']."'";
    mysqli_query($conn,$qry);

?>

I am using simple coding, and thinking to use PDO..But before that actually want to know...How I can do this in a single page for all users as a Admin.
Thanks.


text:
Q: How to consume a dotnet console application from a Nuget package? The scenario is as follows:
a) An arbitrary MyProject.csproj invokes MyConsoleApp.exe as part of a post build event.
b) MyConsoleApp.exe is packaged and consumed via Nuget with all its dependencies
I am not convinced this is the "dotnet core 2.0" way of doing things, I tried dotnet pack MyConsoleApp.csproj but that doesn't include the dependencies like the .exe file does. Should it include all references in a nupkg and publish the package at build time?
MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  ...
  <Target Name="GenerateSomeFiles" BeforeTargets="AfterBuild">
    <Exec Command="dotnet run MyConsoleApp.dll $(TargetDir)" />
  </Target>
</Project>

A: You should try running dotnet publish, then running dotnet pack against the publish folder that's created under bin/Release or bin/Debug.
If you still want an exe, you should either setup a target Runtime for x86/x64 in your csproj, or setup multi-targeting for a full framework version.


text:
Q: Running SSH commands and shell scripts from Jmeter Does anybody knows how to execute series of commands over SSH from Jmeter. I used SSH Sampler as mentioned on http://www.technix.in/execute-linux-command-shell-script-apache-jmeter/#comment-8456 and was able to login to remote server with my own user. However, I want to do few more steps.  Not sure how I can do

*

*Sudo to a different user – 'sudo su – report'

*Change to some directory

*Run some shell script which is already there

*The Shell script will produce some output file. I need to SFTP the output file from there to local Jmeter directory

*Write some tests to verify the output file. THis can be done later but how to do first 4 steps.
The main problem I am facing is that I am not able to understand how I can run series of commands in SSH Sampler. I tried using ; and it worked. However I am not able to do Sudo and run shell script from there.
Any help would be much appreciated.
Cheers!
Vivek

A: As per su command manual

  -c, --command=command
          Pass command to the shell with the -c option.

So you can substitute sudo with su and execute something like:
su -c "cd /some/directory && ./run_some_script" -s /bin/bash report

See How to Run External Commands and Programs Locally and Remotely from JMeter guide for more information.


text:
Q: Using acts_as_recommendable for a production site I was looking for ways to include recommendations in my application. I came to know about acts_as_recommendable plugin. I would like to know your experiences while using it in your application.
I would like to specifically know about

*

*Accuracy

*Pitfalls

and any other stuff you would like to point out
Thanks :)

A: I've used AAR for a while without problems; it'll be as accurate as that data that you can feed it, but for general recommendation engines I think it's great.
I recommend that you pre-calculate the recommended models; each day (or hour) run a rake task that calculates the recommended data for each of your models, store those, and that's what you display to the users. Otherwise it can be a drag on performance (but may not be if small datasets).


text:
Q: Php copy() is not working properly I'm trying to copy my uploaded file to another directory called img folder with following code. But it doesn't work properly. I don't know why ? can you help me plz ?
php Code:
if($image["name"] != "")
{
    //$path = PATH . DS . "uploads" . DS . "products" . DS . $id;
    $path = "../../uploads" . DS . "products" . DS . $id;

    $path2 = "img";

    if(!is_dir($path))
    {
        mkdir($path);
    }

    chmod($path, 0755);
     //move_uploaded_file($image["tmp_name"], $path . DS . $image["name"]);
    move_uploaded_file($image["tmp_name"], $path . DS .
    $uploadImage);//exit;

    copy($uploadImage, $path2);
}

Following error message show:
Warning: copy(249.jpg) [function.copy]: failed to open stream: No such file or directory in...

A: The copy() function needs the full file path for the source file; you're just passing the filename, not the path.
As things stand, it's looking in the current folder for the file, not finding it, and throwing the error as a result.
From the previous line of code, it looks like your full path should be $path . DS . $uploadImage, so the copy command should look like this:
copy($path . DS . $uploadImage, $path2);

hope that helps.

A: Your copy function is wrong...
 copy($uploadImage, $path2);

As Spudley answer says, you have to use the full path of the image. Also, $path2 is a directory. You have to give a name for the new copy of the image.
So, your copy function would be as follows:
 copy($path . DS . $uploadImage, $path2. DS . $uploadImage);

Try it and let us know.


text:
Q: Passing an int to a param of type ?float results in a PhpStorm warning If I have strict_types on, and I pass in an int to a function that's set to accept ?float as the param type, PhpStorm puts a warning, but the code still executes fine. Interestingly, PhpStorm doesn't put a warning if the param type is just float (without the ?).
For example:
<?
declare(strict_types=1);

function strictTypesTest (?float $float) {
    echo $float;
}

strictTypesTest(42);

The last line (strictTypesTest(42);) has a red underline and a warning saying Parameter is expected to be 'float|null', 'int' given:

The code executes fine, because on the PHP docs on strict types, there's one exception to the strict types rule:

The only exception to this rule is that an integer may be given to a function expecting a float.

If I only put float as the param type (instead of ?float), then PhpStorm doesn't put a warning.
Why is the warning only triggering when I add the ?

A: It seems to be a bug, I've filed it here: https://youtrack.jetbrains.com/issue/WI-38446


text:
Q: Interdependent conflicting packages in CentOS 6.5 I've been using CentOS 6.5 as my OS for quite a while. Usually I don't have many problems with Linux installations, but as they new CentOS 6.6 was released I found myself in a bit of a problem. There were hundred of updates to be done, but only one turned out to be problematic. If I input the command
yum update I get
Resolving Dependencies
--> Running transaction check
---> Package scl-utils.i686 0:20120927-8.el6 will be updated
---> Package scl-utils.i686 0:20120927-23.el6_6 will be an update
---> Package xcb-util.i686 0:0.3.6-1.el6 will be updated
--> Processing Dependency: libxcb-icccm.so.1 for package: qt5-qtbase-gui-5.3.2-1.el6.i686
--> Processing Dependency: libxcb-image.so.0 for package: qt5-qtbase-gui-5.3.2-1.el6.i686
--> Processing Dependency: libxcb-keysyms.so.1 for package: qt5-qtbase-gui-5.3.2-1.el6.i686
---> Package xcb-util.i686 0:0.3.6-5.el6 will be an update
--> Running transaction check
---> Package xcb-util.i686 0:0.3.6-1.el6 will be updated
--> Processing Dependency: libxcb-icccm.so.1 for package: qt5-qtbase-gui-5.3.2-1.el6.i686
---> Package xcb-util-image.i686 0:0.3.9-4.el6 will be installed
---> Package xcb-util-keysyms.i686 0:0.3.9-5.el6 will be installed
--> Finished Dependency Resolution
Error: Package: qt5-qtbase-gui-5.3.2-1.el6.i686 (@epel)
       Requires: libxcb-icccm.so.1
       Removing: xcb-util-0.3.6-1.el6.i686 (@anaconda-CentOS-201311271240.i386/6.5)
           libxcb-icccm.so.1
       Updated By: xcb-util-0.3.6-5.el6.i686 (base)
           Not found
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

Now, I know that often these sort of conflicts come from updates from different repos, but this is my current repo list

*

*adobe-linux-i386       Adobe Systems Incorporated

*base                   CentOS-6 - Base

*epel                   Extra Packages for Enterprise Linux 6 - i386

*extras                 CentOS-6 - Extras

*google-chrome          google-chrome

*spideroak-stable       SpiderOak Stable Distribution

*updates                CentOS-6 - Updates
And the weird thing is that it seems that the conflicting packages not only come from the same repository, but are actually dependencies!
xcb-util in fact asks me to install xcb-util-image and xcb-util-keysyms as dependencies..and then conflicts with them! The current version of xcb-util does not have these other two dependencies installed, and says that Source RPM: xcb-util-0.3.6-1.el6.sr.
This is a bit weird. Has anyone met this problem?
Many thanks, and I hope I provided enough information.

A: Problem is qt5 from epel, I removed it and upgrade without problem. There is already fixed qt5 in epel-testing: https://admin.fedoraproject.org/updates/FEDORA-EPEL-2014-3484/qt5-qtbase-5.3.2-3.el6

A: Enable only by default centos repo and disable other repo then run the commands

*

*yum clean all

*yum update all


text:
Q: Error while using SOAP API of cybersource I am trying to use SOAP based Cybersource payment gateway service. Currently I am trying to use Test environment that Cybersource provides for testing sample test credit card transactions.

*

*Created a project in SOAP UI using the WSDL : https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.80.wsdl

*SOAP UI generated the test method runTransaction.

*I copied the same SOAP message provided in Cybersource documentation in to SOAP UI as the SOAP message, which I have given below.

*When I send this request, I am getting the following error:
If anyone has worked on this before or faced this issue, please provide pointers. Thanks!
Ram
Response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext" xmlns:c="urn:schemas-cybersource-com:transaction-data-1.0">
         <faultcode>soap:Client</faultcode>
         <faultstring>Element ():requestMessage not supported.</faultstring>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

SOAP Message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header>
      <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/ wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:UsernameToken>
            <wsse:Username>username</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText">TQc3LSaKfGWfgccqYX3mGhXfhBqnjyVzf5g1aeP3mDPFoMlFDfyKrKnhrqt2bHm3QeXTF1l+Aku/v4sFwIctcGtMNkwZDTMjxAAvuqnmedTa/Q9YxCS8OlhdYWOpJOAQGdyvT6bb0496RuzWN07kQZsPExY8BQDBpll6jpLvdQ6qbBK7MFSnO/2YbFaAaZIaFd+EGqePJXN/mDVp4/eYM8WgyUUN/IqsqeGuq3ZsebdB5dMXWX4CS7+/iwXAhy1wa0w2TBkNMyPEAC+6qeZ51Nr9D1jEJLw6WF1hY6kk4BAZ3K9PptvTj3pG7NY3TuRBmw8TFjwFAMGmWXqOku91Dg==</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <urn:requestMessage xmlns="urn:schemas-cybersource-com:transaction-data-1.80">
         <urn:merchantID>username</urn:merchantID>
         <urn:merchantReferenceCode>MRC-123</urn:merchantReferenceCode>
         <urn:billTo>
            <urn:firstName>John</urn:firstName>
            <urn:lastName>Doe</urn:lastName>
            <urn:street1>1295 Charleston Road</urn:street1>
            <urn:city>Mountain View</urn:city>
            <urn:state>CA</urn:state>
            <urn:postalCode>94043</urn:postalCode>
            <urn:country>US</urn:country>
            <urn:email>null@cybersource.com</urn:email>
         </urn:billTo>
         <urn:item id="0">
            <urn:unitPrice>5.00</urn:unitPrice>
            <urn:quantity>1</urn:quantity>
         </urn:item>
         <urn:item id="1">
            <urn:unitPrice>10.00</urn:unitPrice>
            <urn:quantity>2</urn:quantity>
         </urn:item>
         <urn:purchaseTotals>
            <urn:currency>USD</urn:currency>
         </urn:purchaseTotals>
         <urn:card>
            <urn:accountNumber>4111111111111111</urn:accountNumber>
            <urn:expirationMonth>11</urn:expirationMonth>
            <urn:expirationYear>2020</urn:expirationYear>
         </urn:card>
         <urn:ccAuthService run="true"/>
      </urn:requestMessage>
   </soapenv:Body>
</soapenv:Envelope>

A: Check the time on the server. I recently ran into the exact same issue and turned out the server time was off by 15 minutes.

A: I ran into this same message.
Unfortunately it's not conclusive what the exact error might be, but I found that mine was due to a malformed Security header. (Which is not very intuitive from the error message.)
I don't see anything immediately wrong with your Security header, but you might double check your namespaces.

A: Did you add it as Service Reference or Web Reference, It should be Added as Web Reference. Also you need  to install WSE 3.0 Service from Microsoft to get the TransactionProcessorWse


text:
Q: Application layer references data layer directly In my experience the application layer should reference the business layer and the business layer should reference the data layer.  I want to make a change to an app so that the application layer references the data layer directly as shown below:
    Imports System.Data.SqlClient

Public Class ApplicationLayerClass

    Public Function ProcessAllPersons()
        Dim data As New DataLayerClass
        Dim list As List(Of Person) = data.getAllPersons()
        For Each person In list
            'Call this function from the application client.  Do some complex work on the person here.
        Next
    End Function
End Class

Public Class DataLayerClass
    Public Function getAllPersons() As List(Of Person)
        Dim list As List(Of Person) = New List(Of Person)
        Dim p As New Person
        Dim objCommand As New SqlCommand
        Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True"
        Dim objCon As New SqlConnection
        objCon.ConnectionString = strConString
        objCon.Open()
        objCommand.Connection = objCon
        objCommand.CommandText = "select * from person "
        Dim objDR As SqlDataReader = objCommand.ExecuteReader
        If objDR.HasRows Then
            Using objCon
                Do While objDR.Read
                    p.Name = objDR("Name")
                    p.age = objDR("Age")
                    list.Add(p)
                Loop
            End Using
        End If
        Return list
    End Function
End Class

Public Class Person
    Public Name As String
    Public age As String
End Class

Alternatively I could create a class in the business layer that uses the adaptor pattern (http://en.wikipedia.org/wiki/Adapter_pattern) i.e. a function called BusinessLayerClass.ProcessAllPersons, which is called by ApplicationLayerClass.ProcessAllPersons and calls DataLayerClass.getAllPersons.  Which option is more appropriate? I suppose it depends to some extent on the problem domain.

A: If you have a valid reason for calling the data layer directly, then do it.  If you add a pass-through function in the business layer, then all you've done is added more code for no apparent benefit.
Now, if your business layer is exposed via an interface, IBusinessLayer for example, then adding a ProcessAllPersons() function to it and having it pass the call directly to the data layer makes more sense and consistency.  This is what I would recommend.

A:
the business layer should reference the data layer

This is one approach but arguably not the best if you're aiming at maximum decoupling between your modules and being able to change your data access layer easily without touching your business layer (this is called Persistence Ignorance).
Have a look at Onion Architecture and/or Hexagonal Architecture. These architectural styles emphasize on your business layer being at the core of the system and independent from any other layer.
Concretely, how it works is you define abstractions for data access objects in your business core, which will be implemented in peripheral modules and used by the application layer.
http://jeffreypalermo.com/blog/the-onion-architecture-part-1/
http://alistair.cockburn.us/Hexagonal+architecture
http://blog.kamil.dworakowski.name/2010/08/from-layers-to-hexagon-architecture.html

A: If you have no intention of changing your database provider and you have the ADO.net skills that a business layer would protect developers from, then you don't need a business layer.
However, where are you going to put your business logic?


text:
Q: How to check and fix PDF files that cannot be included correctly using pdfpages and Xe(La)TeX? I am currently writing my master's thesis and therefor I switched from pdfLaTex, which I was using earlier for my academic texts to XeTeX, because of the simplified workflow and unicode support. I am running MiKTeX under Windows and I am struggling with including one particular PDF. I am already including other PDF files without any problems, but the last one is driving me crazy. It's the statement of authorship, provided by my university. It can be found here. Note that including this PDF works fine when I build my project using pdfLaTeX. But when building using XeLaTeX, only blank pages are included.
So I started searching around the web for some useful information and I came up with some solutions, but none of them worked so far. So let me explain, what I have already tried.
First attempt: Rebuilding the PDF
First I tried to rebuild the PDF with GhostScript as described here. Basically I ran the following code:
pdf2ps auth_statement.pdf auth_statement.ps
ps2pdf auth_statement.ps auth_statement_new.pdf

This worked, however the font was totally messed up when including the newly generated PDF. Umlauts did not work at all. I also tried running ps2ps in between, as suggested in the linked answer, but this produced a 0 byte file.
Second attempt: pdfLaTeX + XeLaTeX
So I started writing a MWE and came over with the idea of including the PDF into a simple document, compiled with pdfLaTeX and use this output in my actual thesis. This works, but somehow affects the build of my thesis. Everything runs fine, I do not receive any errors, but the final PDF file is deleted immediately after the build process.
Now I am running out of ideas. Do you know how to check what causes the PDF to be included incorrectly? What else should/could I try?
Here's my MWE:
\documentclass[
    11pt,          % 11pt, 12pt
    a4paper,       % a4wide
]{scrreprt}

\usepackage{pdfpages}

\begin{document}
\includepdf{auth_statement.pdf}
\end{document}

Works fine when compiled with pdfLaTeX, but doesn't when compiled with XeLaTeX. I renamed the PDF linked above to auth_statement.pdf.
Thanks in advance!

A: I finally fixed the issue. The comment by @UlrikeFischer pointed me into the right direction. Indeed the PDF appeared to be encrypted somehow. I have no idea why pdfLaTeX did accept it without any problems and why there was no hint about the encryption in my log in the first place.
I found this answer, suggesting to repair the PDF with PDF ToolKit. I tried this with the original PDF, but failed due to the missing password. So I tried it with my resulting PDF from my second attempt and used this one as an input for my thesis. This finally worked.


text:
Q: Angular push key to array position I try to arrange my array. This is how it looks like:
0: Object { row: 0 }
1: Object { row: 1 }
2: Object { row: 2 }
3: Object { row: 3 }

I want to add a new key now to position 2. Should look like this:
0: Object { row: 0 }
1: Object { row: 1 }
2: Object { row: 2,newkey: 2 }
3: Object { row: 3 }

I found out how to put in right position, but not how to arrange array with new key?

A:
yourArray[2]['newKey'] = 2

yourArray[2].newKey like suggested in the comments may throw an error since the property newKey doesn't exist in the object.

A: To assign a new key:
yourArray[2].newkey = 2;
To delete a key:
delete yourArray[2].newkey;


text:
Q: Deselect selected options when tapped(selected) on last option in swift Need a little help from you, I am working on Table View where I have an Array which is received from server. The Array is nothing but Multiple Choice Options. It looks something like this
a. Table
b. Bottle
c. Hat
d. Bucket
e. None of the Above.
What I Want ?
I want to select multiple answers i.e Table , Bottle , Bucket and it is shown by checkbox marked. Which I have managed to do it well. And when last option i.e None of the Above is selected I want to deselect all the above checked mark options and just show the None option checked, even this is working.
Where I am stuck?
When "None of the Above" is in selected mode and I tap on any other option then "None" should be deselected. This is not working , I don't know whats wrong here. Please help. TIA
Here's my didSelect Method
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
        if selectedString == "None of the above" {

             selectedIndex = indexPath.row

             self.isNoneSelected = true

             for  index  in tableView.indexPathsForSelectedRows!

         {
             tableView.deselectRowAtIndexPath(index, animated: true)
         }

}

And my None option will always be at last position, so even array.lastobject will work I guess

A: Ok I can't be sure, but it looks like this code handles all selection events, right? If so, there appear to be several problems:
1) selectedIndex is only set if they select the last item. I suspect that is not what you want, but I cannot be sure.
2) same for self.isNoneSelected = true - I suspect you want to use this value in other methods to see if that is the selected item, but you don't seem to have any code to turn it off again.
3) you turn off the selection for all the other items, but don't turn on selection for "none" - but that might have already happened in the event, I don't see the rest of the code there.
So I think you want something like this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedIndex = indexPath.row
    if selectedString == "None of the above" {
         self.isNoneSelected = true
         for  index  in tableView.indexPathsForSelectedRows!
         {
             tableView.deselectRowAtIndexPath(index, animated: true)
         }
   } else {
         self.isNoneSelected = false
//NOTE I AM NOT AT MY MACHINE SO I DON'T KNOW THE EXACT SYNTAX HERE
//THE IDEA IS TO GET THE INDEX PATH OF THE LAST ITEM SO WE CAN TURN IT OFF
         tableView.deselectRowAtIndexPath(NSIndexPath.indexPathForRow(mydatasource.count-1, inSection:0), animated: true)
    }
}

A: You are making it too complicated here. All you need is an array of boolean to store the selected states, and reloadData() for the tableView, if you add an UIImageView to represent selected state.
It's not a good idea to call tableView.deselectRow() for every row directly
var selected = Array(repeating: false, count: 5)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
//let cell = whatever
   cell.checkMark.isHidden = !selected[indexPath.row]
//return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    selected[indexPath.row] = !selected[indexPath.row]

    if (indexPath.row == selected.count - 1 ) {//if 'None' is selected
        for i in 0..<selected.count-2 {
            selected[i] = false
        }
    } else { //all other rows will deselect the 'None' row
        selected[selected.count - 1 ] = false
    }
    tableView.reloadData()
}


text:
Q: How to remove border after inset shadow box How do i remove the border in the image ? Adding both a background color and a box shadow to .box-wrap cause this border around the div. I want the colors to match.

.right-column {
    float: left;
    width: 600px;
    height: 531px;
    position: relative;
}

.box-wrap {
    width: 390px;
    height: 370px;
    margin: 77px auto 0;
    margin-top: 77px;
    margin-right: auto;
    margin-bottom: 0px;
    margin-left: auto;
    position: relative;
    box-shadow: rgb(0, 84, 68) 0px 24px 13px 42px inset;
    background-color: white;
}

Code snippet

A: It is now working as intended with the overlay.

div {
    margin:10px;
    width: 100px;
    height: 100px;
    background-color: transparent;
    box-shadow: 0 0 15px 20px #005444 inset;
    border: 100px solid #005444;
}
div.overlay {
    margin-top:-310px;
}

I've found the solution here: box-shadow and border rendering bug


text:
Q: How to add ZipEntry using XZ for Java I'm zipping some json files using the standard ZipOutputStream
ObjectMapper objectMapper = new ObjectMapper();
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(outputFile + ".zip"))) {
    out.putNextEntry(new ZipEntry(jsonFileName + ".json"));
    objectMapper.writeValue(out, jsonDataList);
}

Output:
outputFile.zip\jsonFileName.json => jsonDataList contents

I want to change it from .zip to .7z or .xz
I'm currently tring out XZ for Java (https://tukaani.org/xz/java.html)
ObjectMapper objectMapper = new ObjectMapper();
try (XZOutputStream out = new XZOutputStream(Files.newOutputStream(outputFile + ".xz"), new LZMA2Options())) {
    objectMapper.writeValue(out, jsonDataList);
    out.finish();
}

Output:
outputFile.xz\DataTypeOfJsonDataList => jsonDataList contents

It works in that there are no errors, a .xz file is created, and it does contain one .json file (although the file name is just the data type of "jsonDataList" minus the ".json" extension)
How do I specify the file name of the content?
XZOutputStream doesn't seem to have a way to add a ZipEntry.

A: xz is not 7z. 7z is a compressed archive format, which means it can contain multiple files as well as a directory structure. xz is a single-file compression format. It can be used in combination with the uncompressed tar archive format to make a different compressed archive format, .tar.xz.

A: Thanks to Boris the Spider and Mark Adler for putting me on the right track.
I was able to add an entry into a 7z archive using the org.apache.commons.compress.archivers.sevenz package
SevenZOutputFile sevenZOutput = new SevenZOutputFile(outputFile + ".7z");
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(jsonFile, jsonFileName + ".json");
sevenZOutput.putArchiveEntry(entry);
sevenZOutput.write(objectMapper.writeValueAsBytes(data));
sevenZOutput.closeArchiveEntry();
sevenZOutput.close();


text:
Q: Present tense Used for Past event I saw a news headline that reads: he admits accident was caused by drunk driving.
My question is why they use present tense (admits) instead of past tense (admitted). The news was written after the confession.
Shouldn't it be: he admitted that accident was caused by drunk driving

A: Putting it in present tense conveys the sense that it is happening now, as if the man was telling you the reader in this moment. It can also read as secretive, like you've just been let in on a secret. Both impressions serve to capture readers' attention and compel them to read the article.

A: This usage is called the historic present.

In linguistics and rhetoric, the historical present or historic present, also called dramatic present or narrative present, is the employment of the present tense when narrating past events.
- Wikipedia

It works because English tenses are referenced to a somewhat arbitrary 'now'

A: This is known as the vivid present in grammatical terms. The idea is that the use of a present tense creates immediacy and drama. This vivid present helps emphasise the action happening, rather than its completion.


text:
Q: Reordering MySQL I have probably a very simple question.
I have a MySQL database called "alldata", which contains various variables. The first column called LogDateTime contains date and time. Now the thing is that I want the db to be sorted from the oldest to the newest - in other words by column 1.
I know how to do a MySQL query using ORDER BY Logdatetime etc. But what I would like to do is to reorder tha data in the actual database and save it ordered. Right now there are some dates a bit messed up. Then I would not have to use the ORDER BY statement in all my queries because the database would already be sorted.
Could anyone please just give me the SQL command I should use to reorder the entire database?

A: You cannot setup a relational database table to return results ordered by a specific column of your choosing.  You need to use ORDER BY.  You could work around this by using views.
The view definition would include an ORDER BY.  You could select from the view and it would show results in your desired order.
CREATE OR REPLACE VIEW `mytable_view` AS SELECT * FROM `my_table` ORDER BY `my_date_column`

Then you can select the data:
SELECT * FROM `mytable_view`

Results are shown in desired order.


text:
Q: Conditional statement in Pug I have the following use case, In my project I have two different footers.
Thanks to the suggestion from @sean I tried out a case statement.
This is my template:
//- layout.pug
include head

body
    block nav
        include nav

    block content

    block footer

        case chooseFooter
            when 1
                include footer1
            when 2
                include footer2

    block scripts
        script(src='js/index.js')

This is the first footer:
li
  .footer_contact1

li
  .footer_contact1

 This is the second footer:
ul.boxes
      li
      .footer_contact2

    li
      .footer_contact2

And this is the index page calling upon the template:
extend includes/layout

append content
    .promo

    ul.boxes
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper

prepend footer
        - let chooseFooter = 1

The problem accords if I choose footer1, I get the following output:

some text

So the li:s in the first footer get outside the ul, and they should be inside the closing ul.
If I don't use the case code and just do a normal include and insert it after the last li item in the index file and use the following:
li
   .boxes__text-wrapper

include includes/footer

then the footer1 li items are embedded before the closing ul tag. But then I can't naturally only use one footer.
I hope I am making more sense this time.
Thanks :)

A: Try this approach. Set up a conditional or case statement in your template block that checks the value of a variable.
layout.pug
html
  head
    block head

  body
    nav
    block content
    block footer
      footer
        case whichFooter
          when 1
            p Some footer content
          when 2
            p Some other footer content
          default
            p Some other default footer content
    block scripts
      script(src='/my.js')
      script(src='/pets.js')

Then define that variable in your page, and prepend it to the appropriate block in the template.
page.pug
extends layout

append head
  title Page A

append content
  p My page content...

prepend footer
  - let whichFooter = 1

That way, you're effectively defining the variable before pug needs it to check the conditional or case statement.
(Also don't forget to nest that nav inside the the body instead of beside it.)


text:
Q: Wi-Fi to steal your passwords FULL (complete) access to your victim's machine or device how do I create a fake update on your victim's device(remotely)  and spoof (dns spoof) the url the target program uses to check for updates and get it redirect to our machine.

A: I'm not sure what you want but...

*

*generate a powershell (you can use unicorn)

*start a web server and move the powershell in it and set up
metasploit handler

*set-up MITMf (for Man int the middle attacks )


text:
Q: Haskell: Interact use causing error I'm trying to use the interact function, but I'm having an issue with the following code:
main::IO()
main = interact test

test :: String -> String
test [] = show 0
test a = show 3

I'm using EclipseFP and taking one input it seems like there is an error. Trying to run main again leads to a:
*** Exception: <stdin>: hGetContents: illegal operation (handle is closed)

I'm not sure why this is not working, the type of test is String -> String and show is Show a => a -> String, so it seems like it should be a valid input for interact.
EDIT/UPDATE
I've tried the following and it works fine. How does the use of unlines and lines cause interact to work as expected?
main::IO()
main = interact respondPalindromes

respondPalindromes :: String -> String
respondPalindromes =
    unlines .
    map (\xs -> if isPal xs then "palindrome" else "not a palindrome") .
    lines

isPal :: String -> Bool
isPal xs = xs == reverse xs

A: GHCi and Unsafe I/O
You can reduce this problem (the exception) to:
main = getContents >> return ()

(interact calls getContents)
The problem is that stdin (getContents is really hGetContents stdin) remains evaluated in GHCi in-between calls to main. If you look up stdin, it's implemented as:
stdin :: Handle
stdin = unsafePerformIO $ ...

To see why this is a problem, you could load this into GHCi:
import System.IO.Unsafe

f :: ()
f = unsafePerformIO $ putStrLn "Hi!"

Then, in GHCi:
*Main> f
Hi!
()
*Main> f
()

Since we've used unsafePerformIO and told the compiler that f is a pure function, it thinks it doesn't need to evaluate it a second time. In the case of stdin, all of the initialization on the handle isn't run a second time and it's still in a semi-closed state (which hGetContents puts it in), which causes the exception. So I think that GHCi is "correct" in this case and the problem lies in the definition of stdin which is a practical convenience for compiled programs that will just evaluate stdin once.
Interact and Lazy I/O
As for why interact quits after a single line of input while the unlines . lines version continues, let's try reducing that as well:
main :: IO ()
main = interact (const "response\n")

If you test the above version, interact won't even wait for input before printing response. Why? Here's the source for interact (in GHC):
interact f = do s <- getContents
                putStr (f s)

getContents is lazy I/O, and since f in this case doesn't need s, nothing is read from stdin.
If you change your test program to:
main :: IO ()
main = interact test

test :: String -> String
test [] = show 0
test a = show a

you should notice different behavior. And that suggests that in your original version (test a = show 3), the compiler is smart enough to realize that it only needs enough input to determine if the string read is empty or not (because if it's not empty, it doesn't need to know what a is, it just needs to print "3"). Since the input is presumably line-buffered on a terminal, it reads up until you press the return key.


text:
Q: Creating a new rails database record from an external script? I'm trying to send a POST request from an external Ruby script to a Rails app via HTTP#post_form. The request is made to the create action (i.e. the URI is http://server/controller).
If I encode a single parameter into the request, everything is fine:
HTTP::post_form(uri, { :my_param => "value" })

Though I do have to explicitly pull out my_param from params manually, in the controller. This seems inefficient, and breaks creating a new record from within the app itself (because that parameter is not there). I'm consequently trying to make my script pose as Rails itself, passing the appropriate data as the controller would expect it, e.g.
HTTP::post_form(uri, { :object => { :my_param => "value" } })

However, this doesn't work. post_form seems to be escaping my hash into something different, i.e.
{ "object" => [\"my_param\", \"value\"] }

Which obviously doesn't do the same thing. Am I missing something obvious in the way I'm passing the data? Or can I not achieve what I'm after (creating a new record from outside the app)?

A: One straightforward way might be to simply imitate how Rails formats its parameters, like this:
params = { :my_param => "value", ... }
params = Hash[params.map { |key,value| ["object[#{key}]",value] } ]

HTTP::post_form(uri, params)

Edit: Well, look at that, I looked around a bit and found that Rails actually gives you a method to do the same thing using their own mechanism:
require 'active_support/core_ext'
...
HTTP::post(uri, parameters.to_param)

The to_param method will treat Arrays correctly, and everything else too. Notice that in this case you want to use HTTP::post, not post_form, since the parameters are already converted to a string.

A: I don't know much about post_form but the natural solution for me would be to use an ActiveResource object.
ActiveResource is available to ruby as well as to Rails. you use it just like you use a model only it posts and gets using XML
There is a Railscast on how this works here
http://railscasts.com/episodes/94-activeresource-basics
http://railscasts.com/episodes/95-more-on-activeresource
I think you'll find that this is a better fit for your requirements than post_form but as I say, I'm not familiar with post_form.


text:
Q: se podrea minificar esto

function vocal(letra) {
  letra === "a" || letra === "e" || letra === "i" || letra === "o" || letra === "u" ?   console.log("es vocal") :  console.log("es consonante")
}
vocal("b")

mejorar el codigo ? para hacerlo mas legible o mas pequeño

A: Esto que buscas es posible hacerlo gracias al método match con una expresión regular:

const tieneVocal = e => {
  return e.match(/[aeiou]/) ? console.log('Es vocal') : console.log('Es consonante')
}

tieneVocal('e')

Podrías añadir más letras y te dirá si hay alguna vocal en todas ellas.

A: Utilizando expresiones regulares y arrow function se simplificaría.
let vocal = letra => letra === /[aeiou]/i ? console.log("es vocal") : console.log("es consonante");
vocal(2);


text:
Q: selenium python stop element during test on chrome I am able to run selenium tests but during one of the test when I click on edit button it's suppose to open page in edit mode, but instead of that I see loading icon and I can see page loading in back. But since loading icon is in front I can't click on any of the items in back. I see element as below, can I stop it?

Loading ...

On top of this element there is script as below not sure if that's related


text:
Q: Populate a list with Modules and display it in a Dialogbox in DOORS I need a DXL script that fill a DialogBox with returned Module names'. I have several modules within a project.
Below is my current progress. My idea is to put all Module names in a List and then display the list in a DialogBox.
Can you help me write ´´´fillModulelist()´´´
// This DXL script iterates through all formal modules of the folder
DB      dbMain        = null
DBE     dbeModuleList   = null
DBE     dbeExport     = null
DBE     dbeExportPath = null

Folder  currFolder    = null

string startFolder="/Project/Folder";
int moduleCount=0;

void forAllModulesInFolder(Folder f)
{
  Item itemRef;
  string shType;
  string sItemNameFull;
  string sItemName;
  Module moduleReference;

  for itemRef in f do
  {
    shType = type(itemRef);
    print shType "\t";

    sItemNameFull = fullName(itemRef);
    print sItemNameFull "\t";

    sItemName = name(itemRef);
    print sItemName "\n";

  if(shType=="Folder")
  {
    string selectedFolder = sItemNameFull;
    Folder f = folder selectedFolder;
    forAllModulesInFolder(f);
  }

  if(shType=="Formal")
  {
    moduleReference = read(sItemNameFull,false,true);
    filtering off;
    // do s.th. with the moduleReference
    close(moduleReference);
    moduleCount++;
  }
}}

void fillModuleList()
{
    //........... HELP NEEDED........

}

// Main-Method
void main(void)
{
  string selectedFolder = startFolder;
  Folder f = folder selectedFolder;
  forAllModulesInFolder(f);
  print "Affected Modules: " moduleCount "\n";
}

main();

Any help provided I would be very thankful.

A: As the list of modules is for displaying it to the user (and perhaps let them select from that list), it is best to display the full name of the modules, thus I would not store the module reference. You can open the module later, when the user has selected/double clicked the module (supposing that this is what you want). Thus, I fill a Skip list with sItemNameFull, sItemNameFull, but if it suits your script better, you can also fill it with moduleReference, sItemNameFull (use create instead of createString in this case). The changes to your script are marked with //->> and //<<-
// This DXL script iterates through all formal modules of the folder
DB      dbMain        = null
DBE     dbeModuleList   = null
DBE     dbeExport     = null
DBE     dbeExportPath = null

Folder  currFolder    = null

string startFolder="/testtrunk";
int moduleCount=0;

//->>
Skip skModules = createString()
//<<-

void forAllModulesInFolder(Folder f)
{
  Item itemRef;
  string shType;
  string sItemNameFull;
  string sItemName;
  Module moduleReference;

  for itemRef in f do
  {
    shType = type(itemRef);
    print shType "\t";

    sItemNameFull = fullName(itemRef);
    print sItemNameFull "\t";

    sItemName = name(itemRef);
    print sItemName "\n";

  if(shType=="Folder")
  {
    string selectedFolder = sItemNameFull;
    Folder f = folder selectedFolder;
    forAllModulesInFolder(f);
  }

  if(shType=="Formal")
  {
    //->>
    put (skModules, sItemNameFull, sItemNameFull)
    //moduleReference = read(sItemNameFull,false,true);
    //filtering off;
    // do s.th. with the moduleReference
    //close(moduleReference);
    //<<-
    moduleCount++;
  }
}}

//->>
void fillModuleList(Skip skContent, DBE dbeList)
{
    empty dbeList
    int cnt=0
    string sLine
    for sLine in skContent do {
        insert (dbeList, cnt, sLine)
        cnt++
    }
}
//<<-

//->>
void DoSomethingWithDoubleClickedModule (DBE x) {
    string sModName = get(x)
    print "doing something with " sModName "<---\n"
}

void canvasDummyCB( DBE dummy ) { }
void doNothing(DBE x) {}
void prepareGui()
{
    const string sArEmpty[] = {}

    dbMain = create ("mytitle", styleCentered)

    DBE spaceLeft = canvas(dbMain, 0, 0, canvasDummyCB)
    spaceLeft->"top"->"form"; spaceLeft->"left"->"form"
    spaceLeft->"right"->"unattached"; spaceLeft->"bottom"->"unattached"

    DBE spaceRight = canvas(dbMain, 0, 0, canvasDummyCB)
    spaceRight->"top"->"form"; spaceRight->"right"->"form"
    spaceRight->"left"->"unattached"; spaceRight->"bottom"->"unattached"

    DBE dInfoTextLabel = label(dbMain, "choose a module")
    dInfoTextLabel->"top"->"form"
    dInfoTextLabel->"left"->"flush"->spaceLeft
    dInfoTextLabel->"right"->"flush"->spaceRight

    dbeModuleList = list( dbMain, "Modules", 200, 15, sArEmpty)
    dbeModuleList->"top"->"flush"->dInfoTextLabel
    dbeModuleList->"left"->"flush"->spaceLeft
    dbeModuleList->"right"->"flush"->spaceRight

    realize dbMain

    set( dbeModuleList, doNothing, DoSomethingWithDoubleClickedModule)

}
//<<-

// Main-Method
void main(void)
{
  //->>
  prepareGui()
  //<<-

  string selectedFolder = startFolder;
  Folder f = folder selectedFolder;
  setempty(skModules)
  forAllModulesInFolder(f);
  //->>
  fillModuleList (skModules, dbeModuleList)
  //<<-
  print "Affected Modules: " moduleCount "\n";
}

main();


text:
Q: EasyNetQ / RabbitMQ consuming events in Web API I have created Web API which allows messages to be sent to the Queue. My Web API is designed with CQRS and DDD in mind. I want my message consumer to always be waiting for any messages on the queue to receive. Currently the way its done, this will only read messages if I make a request to the API to hit the method.
Is there a way of either using console application or something that will always be running to consume messages at anytime given without having to make a request from the Web Api. So more of a automation task ?
If so, how do I go about with it i.e. if its console app how would I keep it always running (IIS ?) and is there way to use Dependency Injection as I need to consume the message then send to my repository which lives on separate solution. ?
or a way to make EasyNetQ run at start up ?

A: The best way to handle this situation in your case is to subscribe to bus events using AMPQ through EasyNetQ library. The recommended way of hosting it is by writing a windows service using topshelf library and subscribe to bus events inside that service on start.
IIS processes and threads are not reliable for such tasks as they are designed to be recycled on a regular basis which may cause some instabilities and inconsistencies in your application.

and is there way to use Dependency Injection as I need to consume the message then send to my repository which lives on separate solution.

It is better to create a separate question for this, as it is obviously off-topic. Also, it requires a further elaboration as it is not clear what specifically you are struggling with.


text:
Q: After creating JAR using "maven-jar-plugin" along with "*.Properties"(files), methods from JAR are failing as "*.properties" path is changed create JAR from maven project, along with all dependable properties files to reuse methods/class from another maven project.

*

*properties files are located into src/main/resource under folder-> ConfigFolder

*When JAR is created the path of ConfigFolder changed and below line of code is failing System.getProperty("user.dir")+/src/test/resource/ConfigFolder/Configfilename.Properties

In maven project - *.Properties is being read by below line of code
new FileInputStream(System.getProperty("user.dir")+/src/test/resource/ConfigFolder/Configfilename.Properties")
When Project is converted into Jar using maven-jar-plugin, the hierarchy of Configfilename.Properties changes hence all my methods are failing.
Before converting JAR Folder Hierarchy
ProjectName(maven project)
|-src/main/java
|-src/test/java
|-src/test/resource
|-ConfigFolder
|-Configfilename.Properties
|-testSuites
|-testng.xml
After converting the into JAR
JARNAME-test.jar
|-ConfigFolder
|-Configfilename.Properties
|-testSuties
|-testng.xml
As you see after converting the jar the hierarchy got changed and new **FileInputStream(System.getProperty("user.dir")+/src/test/resource/ConfigFolder/Config.Properties") **returns null
requirement is to convert first maven project into JAR and use it into second maven project as first maven project contains n number of reusable methods/class project.


text:
Q: How to load anotherTableView for every cell that is selected? I am new to Objective-C/iOS programming so please bear with me for stupid mistakes. I have a Flight Sim app that I am making, that has one tab "Checklists". In the first tblView are the aircraft (eg. B737, A320). Depending on the aircraft pressed, another tblView will load, with different data for each aircraft.

Here is my project --> https://www.dropbox.com/s/xpysl5or954laep/FS%20Companion.zip

I cannot seem to work out how to load the different data. I tried to make an int aircraftNumber, then make an object for each aircraft file. Then do a switch statement using aircraftNumber, and in the switch do a pushViewController. I couldn't seem to create the objects and the indexPath.row successfully.

I hope somebody can help, and that you understood my problem.

Thanks,

Luke

A: You can do this in the select method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Create a DVC Object
    switch ([indexPath row]) {
        case 0:
        {
            ChecklistsA320Controller * A320Contoller = [[ChecklistsA320Controller alloc] initWithNibName:@"ChecklistsA320Controller" bundle:nil];
            [self.navigationController pushViewController:A320Contoller animated:YES];
        }
            break;

        case 2:
        {
            Checklists737Controller * B737Controller = [[Checklists737Controller alloc] initWithNibName:@"Checklists737Controller" bundle:nil];
            [self.navigationController pushViewController:B737Controller animated:YES];
        }
            break;

        default:
            break;
    }
}

But in your case, I think you could improve your architecture. Create only one class "A" with a UITableView which displays data. Then create a class "B" which will create instances of your class "A" and manage your different data.


text:
Q: Javascript Calculator does not work properly I have this calculator
http://jsfiddle.net/DPqXE/
HTML

With numbers →
<input id="mli" name="mli" style="width:50px;" type="text" /> ml.

With numbers → <input id="sprying" name="sprying" style="width:50px;" type="text" /> time/s

How often→ <select id="week" name="week"><option value="4.3">1</option><option value="8.6">2</option><option value="12.9">3</option><option value="17.2">4</option><option value="21.5">5</option><option value="24.8">6</option><option value="30.1">7</option></select>

Total: •• months

JS
$(document).ready(function() {
$('#sprying').keyup(function(ev){
    var total = Math.round((
    ($('#mli').val() * 14.7) / ($('#sprying').val() * $( "#week option:selected" ).val() )));
    $('#total').html(total);
});
});

But I have an issue:
When I type some numbers in to the input fields
total is calculated, but when I chose from the select fields nothing hapens.
And after that if i edit the first two fields the result is calculated properly.
Many thanks

A: Why would it, you only listen to keyup.
bind both keyup and change, something like:
$(document).ready(function() {
    $('#sprying').keyup(updateTotals);
    $('#week').change(updateTotals);
    function updateTotals(){
        var total = Math.round((
        ($('#mli').val() * 14.7) / ($('#sprying').val() * $( "#week option:selected" ).val() )));
        $('#total').html(total);
    }
});

demo: http://jsfiddle.net/DPqXE/1/

A: You are assigned .keyup() only, also asign to .change()
Add it in your $(document).ready(function() {..}
$('#week').change(function(ev){
    //....
});


text:
Q: How to throttle "actions" (updates) to take on a changed source on a page I searched a lot for a solution to this certainly-not-unique problem, but I have not found anything that will work in my context of an HTML page.
I have an input text that contains some kind of source-code that generates something, and I can show a preview of that something on the same HTML page (by updating the background image, for example). Note that the source could be a LaTeX file, an email, a Java program, a ray-trace code, etc. The "action" to generate the preview has a certain cost to it, so I don't want to generate this preview at each modification to the source. But I'd like the preview to auto-update (the action to fire) without the user having to explicitly request it.
Another way to phrase the problem is to keep a source and sink synchronized with a certain reasonable frequency.
Here's my solution that's too greedy (updates at every change):
$('#source-text').keyup(function(){
    updatePreview(); // update on a change
  });

I tried throttling this by using a timestamp:
$('#source-text').keyup(function(){
    if (nextTime "before" Now) { // pseudocode
       updatePreview(); // update on a change
    } else {
       nextTime = Now + some delay // pseudocode
    }
  });

It's better, but it can miss the last updates once a user stops typing in the source-text field.
I thought of a "polling loop" for updates that runs at some reasonable interval and looks for changes or a flag meaning an update is needed. But I wasn't sure if that's a good model for an HTML page (or even how to do it in javascript).

A: Use setTimeout, but store the reference so you can prevent it from executing if further editing has occurred. Basically, only update the preview once 5 seconds past the last keystroke has passed (at least in the below example).
// maintain out of the scope of the event
var to;

$('#source-text').on('keyup',function(){
  // if it exists, clear it and prevent it from occuring
  if (to) clearTimeout(to);

  // reassign it a new timeout that will expire (assuming user doesn't
  // type before it's timed out)
  to = setTimeout(function(){
    updatePreview();
  }, 5e3 /* 5 seconds or whatever */);
});

References:

*

*clearTimeout

*setTimeout
And not to self-bump, but here's another [related] answer: How to trigger an event in input text after I stop typing/writing?

A: I tweaked @bradchristie's answer, which wasn't quite the behavior I wanted (only one update occurs after the user stops typing - I want them to occur during typing, but at a throttled rate).
Here's the solution (demo at http://jsfiddle.net/p4u2mhb9/3/):
// maintain out of the scope of the event
var to;
var updateCount = 0;
var timerInProgress = false;

$('#source-text').on('keyup', function () {
    // reassign a new timeout that will expire
    if (!timerInProgress) {
        timerInProgress = true;
        to = setTimeout(function () {
            timerInProgress = false;
            updatePreview();
        }, 1e3 /* 1 second */ );
    }
});


text:
Q: Минимизация CSS Всем, Здравствуйте!
Как минимизировать CSS, как здесь? - http://sidigital.co/public/css/compiled.css
A: Воспользуйтесь онлайн сервисами для оптимизации CSS. Вот только некоторые из них:

*

*
cssdrive.com CSS Compressor — работает в 2 режимах: обычный и продвинутый. Вы можете выбрать один из трех уровней сжатия. Режим "Normal" должен хорошо работать в большинстве случаев, создавая оптимальный баланс между ними.

*
http://www.cleancss.com – CSS форматирование и оптимизатор на основе csstidy доступна на английском, немецком и французском языках.

*
CSS Compressor  - можно выбрать 4 уровня сжатия.

*
CSS Optimizer  - Оптимизация CSS указав URL адрес css-файла, загрузив файл с локального компьютера или непосредственно введя CSS код в форму.

*
codebeautifier.com  - CSS Compressor  на основе CSSTidy

*
askapache.com  - данный сервис использует часть порта JavaScript из YUI Compressor, и часть W3 CSS Validator. Вы можете загрузить CSS файл, указать URL CSS-файла, или просто вставить CSS код в форму.

*
iceyboard.no-ip.org CSS Compressor - Вы можете загрузить файл, указать URL CSS-файла или вставить CSS код. Хорошие варианты сжатия.

*
ebiene.de – сервис для сжатия JavaScript и CSS файлов. Вы можете выбрать между базовым сжатием и сильным.

*
pagecolumn.com – Сжатие CSS, возможность поиска и удаления неиспользуемых классов и ID в CSS (опционально).

*
Pingates.com -  Вы можете указать URL CSS файла или вставить CSS код.


text:
Q: 12 V pulse circuit to operate a double coil latching relay uses no power unless switching
I have a double coil latching relay and I need a circuit that will provide a pulse to switch it on. After the pulse I don't want it to use any power.
There are two sides to the circuit, one to turn the latching relay on, and another to turn it off.
I'm using the latching relay as a high-voltage disconnect for a 12 V LiFePO4 battery.
My BMS has a small 1 A, 12 V relay with NO and NC which will provide the power to the pulse circuit that would latch and unlatch the relay.

A: Here's the pulse generator schematic.

(1NO + 2NC) contacts would be required from the BMS relay K1.

A:
My BMS

DO NOT USE A LATCHING RELAY with a BMS!
Latching relays / contactors are not fail safe.
You MUST use a regular relay, contactor, solid state relay, or MOSFET. Anything that goes off when the power goes away.
(I am in the business, and I've had more than one customer who killed their Li-ion battery by using a latching relay.)
The problem is that, if something goes wrong with the system (a loose connection, a broken wire, no power to the BMS, the microcontroller resets, etc.) the latching contactor remains on, when it should be turned off.
If you need low stand-by power, switch to a protector BMS with MOSFETs. They now make BMSs for 48 V for up to 300 A.


text:
Q: Freebase MQL query for non-self of mediator (sibling, spouse, etc.) Is there some way to do an MQL query for the other object in a symmetric relationship defined through a mediator type (e.g. /people/sibling_relationship)?
For example, suppose I wanted a list of people who have a sister.  The following query returns everyone with a sister, but also includes women who have brothers but no sisters (since they are linked to a sibling relationship containing a female sibling—themselves).
[{
  "type": "/people/person",
  "name": null,
  "gender": null,
  "sibling_s": [{
    "sibling": [{
      "name": null,
      "gender": "female"
    }]
  }]
}]

A: No, there isn't a way to deal with the general case.  In your example, you could finesse it by querying women with sisters as sibling relationships where both siblings are female, but generally there's no way to do self-referential stuff in MQL (e.g. an ID not equal to the ID returned in this other part of the query).


text:
Q: Read HTML file to generate data using javascript I got to read a number of HTML files, get its tags content and generate a report using these contents (e.g day1.html has Simon, I need to read day1.html file, and get 'author' div content  which is 'Simon' and generate my own report using this data). How can I do it using Javascript?
any help is highly appreciated.
Many thanks.
An

A: If you're not adverse to using jQuery you can use get() to load and parse an HTML document via JavaScript:
jQuery.get('day1.html', function(html)) {
  var author_div_text_content = jQuery('DIV#author', html).text();
}

A sample working on the jsFiddle web site:
http://jsfiddle.net/KCxDp/


text:
Q: Cannot get sample CustomLoginModule to work I imported the project from the zip file on worklight getting started page. build android, run as android and got the error below when I click 'call protected adadpter proc'

07-03 09:21:29.400: E/NONE(822):
  [http://'':10080/CustomLoginModule/apps/services/api/CustomLoginModule/android/query]
  failure. state: 500, response: FWLSE0009W: User identity is null.
  Check your application's authentication requirements. These settings
  must match to the deployed application [project CustomLoginModule]

A: Try to get the project running by cleaning the Worklight project.
In Eclipse, click on the Project menubar option and choose Clean....
Next, re-deploy the adapter and application using the Run As menus.

A: I was getting a similar error but the Clean did not work for me.   I had to remove the project from the server and then redeploy it in order to resolve the problem.


text:
Q: Can't store TagName positions in an array I have a page which displays a story, with buttons at the button to go from page 1 to page 2 and 3 and vise versa, the story is in a one array position which i've sliced using a character length to fill out each page. The text which im appending to the paragraphs on each page contains  tags. Im trying to add tooltips for each bit of i've placed in bold tags. I'm trying to get all  on the page, log the x and y position and then create an element with the text which is needed for each  element. Here's an example of what my code looks like
 pageItemsArray = [
      ['The car is a round tree.']
      ['make: rennault', 'name: oak']
 ]

note: tooltip="make: rennault" and tooltip="name: oak" is only there for people trying to solve this with css, and is not there for people trying to solve this with javascript, however it doensn't need to be removed
html :

javascript:
 for(i=0; i<document.getElementsByTagName("b").length; i++) {
     /*run code for all tooltips here*/

 element = document.createElement("SPAN");
 element.innerHTML = pageItemsArray[1][i].toString();
 element.setAttribute("class", "tooltip");
 document.body.appendChild(element);

 x = document.getElementsByTagName("b")[i].offsetLeft;
 y = document.getElementsByTagName("b")[i].offsetTop;

 element.setAttribute("left", x);
 element.setAttribute("top", y);

 }

However, the spans are positioned at the bottom of the page, and not anywhere near where they are meant to be.
Update: Still not answered :(
heres css for people trying to solve via css
 b:hover[tooltip]:before {
     content: attr(tooltip);
     position: absolute;
     z-index: 1;
     top: 0rem;
     left: 0rem;
     padding: 5px;
     background-color: black;
     color: white;
     border-radius: 5px;

 .insertStoryPageHere {
     position: relative;
     font-family: Proxima;
     font-size: 16px;
     line-height: 2em;
     height: 311px;
 }

The problem with the css solution is that the tooltips are moving the paragraph text on hover...
What it looks like, the with the css

A: Here is a quick and dirty CSS only solution. I simply added a tooltip attribute to  with some text (slightly different from your array, though). This should give you some direction. No need for a complicated construction with remembering positions and what all not. Keep things simple and save the headache for the really hard stuff.

body { margin: 0; padding: 5rem } /* some spacing */

p { position: relative } /* creat a stacking context */

b:hover[tooltip]:before {
    content: attr(tooltip);
    position: absolute;
    /* position within parent stacking context (the
, default is ) */

    top: -2.5rem;
    padding: 0.5rem;
    background-color: black; color: white;
}

this is a text about Renault and how you can keep it running for years


text:
Q: Coping with a label/class imbalance in DESeq2 I'm trying to do differential expression on label imbalanced data; my case:control ratio is 2:1.
I know that regressions are at the core of DESeq2 machinery and I know regressions have internal machinery for coping with such imbalances.
Specifically, you can down-weight observations from the over-represented group to force an equal contribution to the learning. Is observation weighting available to the user in DESeq2?
Group a over-represented in learning:
glm( gene_i ~ effect , data[,c('a','a','a','a','b','b')] )

Group a and b equal representation in learning:
glm( gene_i ~ effect , data[,c('a','a','a','a','b','b')] , weight=c(.5,.5,.5,.5,1,1) )


text:
Q: Arangodb not connecting using localhost but accessible using external IP I installed arangodb on single node ubuntu server, followed this
below is my arangod.conf file:
endpoint = tcp://127.0.0.1:8529
endpoint = tcp://<internalserverIP>:8529

I did enable both of them.
Now i am able to access arango using below on my local system
curl --dump - http://<externalserverIP>:8529/_api/version

so far so good.
now when i try to access same on installed ubuntu server using:
curl --dump - http://127.0.0.1:8529/_api/version

i am getting below error:

Access to the page:
  ... has been denied for the following reason:
Blocked by Content Checking.
Categories:
Proxies

what am i missing here.

A: It worked by resetting the proxy to its default by using the below command.
export http_proxy=


text:
Q: Sync FIFO simulation does not work as expected I don't know what is wrong in my code.  Refer to the /* status */ comment near the full and empty logic.
I have write pointer wrapping around catching up with read pointer, then wr_addr[3] == ~rd_addr[3] and wr_addr[2:0] == rd_addr[2:0], I have a full condition.
I have read pointer catching up with write pointer, then wr_addr[3:0] == rd_addr[3:0], I have empty.
Please check my code and give me some advice.
I also provide the code on edaplayground (for those of you who have an account there).
module fifo(input clk, rst,
            input wr, rd,
            input [3:0] din,
            output logic [3:0] dout,
            output fifo_full, fifo_empty
);

logic [3:0] w_ptr, r_ptr;
logic w_en, r_en;

status_pointer ptr(clk, rst, wr, rd, w_en, r_en, w_ptr, r_ptr, fifo_full, fifo_empty);
memory mem(clk, w_en, r_en, w_ptr, r_ptr, din, dout);

endmodule

module memory(input clk, we, oe,
          input [3:0] w_ptr, r_ptr,
              input [3:0] din,
              output logic [3:0] dout
);

logic [3:0] mem [7:0];

always_ff @(posedge clk) begin
    if(we & (~ oe)) begin
        mem[w_ptr[2:0]] <= din;
    end

    else if((~ we) & oe) begin
        dout <= mem[r_ptr[2:0]];
    end

    else if(we & oe) begin
      mem[w_ptr[3:0]] <= din;
      dout <= mem[r_ptr[2:0]];
    end

end

endmodule

module status_pointer(input clk, rst,
                input wr, rd,
                output w_en, r_en,
                output logic [3:0] w_ptr, r_ptr,
                output logic fifo_full, fifo_empty
);

/* status */
always @(posedge clk) begin
        if(rst) begin
            fifo_full <= 0;
            fifo_empty <= 0;
        end

        else begin
            if(w_ptr[2:0] == r_ptr[2:0]) begin
                if(w_ptr[3] == r_ptr[3])
                    fifo_empty <= 1;
                else
                    fifo_full <= 1;
            end

            else begin
                fifo_full <= fifo_full;
                fifo_empty <= 0;
            end
        end
end

/* pointer */
assign w_en = (fifo_full == 0) & wr;
assign r_en = (fifo_empty == 0) & rd;

always_ff @(posedge clk, posedge rst) begin
        if(rst) begin
            w_ptr <= 4'b0;
            r_ptr <= 4'b0;
        end

        else if(w_en & (!r_en)) begin
            w_ptr <= w_ptr + 4'b001;
        end

        else if(r_en & (!w_en)) begin
            r_ptr <= r_ptr + 4'b001;
        end

        else if(w_en & r_en) begin
            w_ptr <= w_ptr + 4'b001;
            r_ptr <= r_ptr + 4'b001;
        end

        else begin
            w_ptr <= w_ptr;
            r_ptr <= r_ptr;
        end
end

endmodule

//// test bench ////
module tb_fifo();

logic clk, rst, wr, rd;
logic [3:0] din, dout;
logic fifo_full, fifo_empty;
logic [4:0] counter;

fifo dut_fifo(clk, rst, wr, rd, din, dout, fifo_full, fifo_empty);

always begin
    clk = 1; #4;
    clk = 0; #4;
end

initial begin
    counter = 5'b00000;
    rst = 0; #240; rst = 1;
end

always @(posedge clk) begin
    if(~ rst) begin
        counter <= counter + 5'b00001;

            if(counter == 5'b00000) begin
                wr = 1; rd = 0; din = counter[3:0];
            end

            else if(counter == 5'b00001) begin
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b00010) begin
                wr = 0; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b00011) begin
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b00100) begin        // [3]
                wr = 1; rd = 0; din = counter[3:0];
            end

            else if(counter == 5'b00101) begin        // [3]
                wr = 1; rd = 0; din = counter[3:0];
            end

            else if(counter == 5'b00110) begin        // [3]
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b00111) begin        // [3]
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01000) begin        // [3]
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01001) begin        // [3]
                wr = 0; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01010) begin        // [3]
                wr = 0; rd = 1; din = counter[4:1];
            end

            else if(counter == 5'b01011) begin        // [3]
                wr = 1; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01100) begin        // [3]
                wr = 1; rd = 1; din = counter[4:1];
            end

            else if(counter == 5'b01101) begin        // [3]
                wr = 0; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01110) begin        // [3]
                wr = 0; rd = 1; din = counter[3:0];
            end

            else if(counter == 5'b01111) begin        // [3]
                wr = 1; rd = 0; din = counter[3:0];
            end

            else if(counter == 5'b11111) begin
                $stop;
            end

            else begin
                wr = 0; rd = 0;
            end
    end

    else begin
        counter <= 5'b00000;
        wr = 0; rd = 0;
    end
end
endmodule

A: There is a problem in your testbench.  Your design expects an active-high reset.  You need to drive rst high starting at time 0 to reset the design, then drop it low after a delay.  Just invert how you drive rst.  Change:
rst = 0; #240; rst = 1;

to:
rst = 1; #240; rst = 0;


text:
Q: Upload and display image form I store the images in folder.
So how should I ask the user to upload images in the form?
I mean the user will upload the image using the upload button. Then after filling the form,
the user will submit it.
So when I am showing the contents of form again, how do I check which photo was related to which form .
Also how to position the image in a textarea?
Should I ask the user to put code <img src="example.com/images/name_of_image"/> in the textarea where he wants to display the image?
Is it safe to expose the image path to user?

A: You may upload images into a directory or folder and give it a unique name / number (like PHP uniqid). Store this number to the database along with the form data, so that the image ID can be retrieved from the database and shown. In this way, one table row in your database will contain details about a single form only.

A: Anyway I am answering form what I get your problem is. It is always better to write the complete programming part by the programmer and it is always better if the user enters only plain English. In my opinion if you are taking input form a user then use this technique.I am considering that you have a database and you are confortable using it.
1. Take input form a user and ask them to upload the image
2. Make a PHP script to store the image in the webserver
3. Create a table:
+----+------------+-------------+
|slno|username|imagename|
+----+------------+-------------+
4. Now store the image name using $_FILES["file"]["name"]
5. You can show your image form the user just by using a simple SELECT command.
6. Make sure you have your unique id.
Ref:Nice tutorial form w3schools.

A: To track the images you can have some primary key associated with the name of the image while storing it.
When you are going to display the easiest work around would be to use one picturebox on the form. Initially visible false and while displaying set it to true.


text:
Q: dropdown list always sets modelstate invalid Whats wrong with this?
@Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select --")
@Html.ValidationMessageFor(x => x.Post.CategoryId)

When I submit the form the modelstate is invalid and this dropdown list gets flagged as an error, even though i select a value from the dropdown list.
(btw CategoryId is an FK in my Post Table)
I haved added this "buddy" class as a partial
[MetadataType(typeof(Post_Validation))]
public partial class Post
{

}

class Post_Validation
{

    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }

}

controller:
// GET: /News/Add
        [Authorize]
        public ActionResult Add()
        {
            var model = new AddPostViewModel() { Categories = categoryRepository.GetAllCategories(), Post = new Post(), IsEditMode=false };
            return View(model);
        }

            //
            // POST: /News/Add
            [Authorize]
            [HttpPost]
            public ActionResult Add(AddPostViewModel model)
            {
              if (!ModelState.IsValid)
              {
              ..etc
              }
            }

A: There is nothing wrong with this particular code you have posted. What might be wrong is the model you are expecting in the controller action which is being posted to. For example if this model is not the same as the model used to render this view:
[HttpPost]
public ActionResult Index(Post post) { ... }

instead of:
[HttpPost]
public ActionResult Index(ModelContainingPostConmtainingCategoryId post) { ... }

The name of the dropdownlist generated will be the following: name="Post.CategoryId" and if your controller action doesn't take a model having a property called Post with a property called CategoryId and this CategoryId property is marked with Required you will get the behavior you are describing.
Other possible reasons is that you have additional properties which are required and which you haven't included in your request. The way to find this out is to analyze the model you are getting back in your controller action and see what's missing. Also looking at the ModelState property itself in debug mode will tell you which properties have validation errors.

UPDATE:
Here's a full working example that could be used as base:
Model:
[MetadataType(typeof(Post_Validation))]
public class Post
{
    public int CategoryId { get; set; }
}

class Post_Validation
{
    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }
}

public class AddPostViewModel
{
    public IEnumerable<SelectListItem> Categories { get; set; }
    public Post Post { get; set; }
}

Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new AddPostViewModel()
        {
            Categories = Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "category " + x
            }),
            Post = new Post()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(AddPostViewModel model)
    {
        if (!ModelState.IsValid)
        {
            ...
        }
        ...
    }
}

View:
@model AppName.Models.AddPostViewModel
@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "Value", "Text"), "-- Please select --")
    @Html.ValidationMessageFor(x => x.Post.CategoryId)
    <input type="submit" value="OK" />
}

A: Your model state will always be invalid for your dropdowns if your selected variable type is not a string.


text:
Q: phpmyadmin column using php function Can i make a column that automatically creates its content from other column and do a function on it?
for example a function to lowercase the title in same row
function tt(row['title']){
    strtolower(row['title']);
}

[id     title     content     function tt()]
[1   Awesome PHP   Lorem       row['title']]

//becomes//

[id     title     content     function tt()]
[1   Awesome PHP   Lorem       awesome php ]

is that possible? Or do i have to make it is supposed to be while inserting the database?

A: yes you can use triggers to achieve this.


text:
Q: "Verb1 preposition1 and verb2 preposition2" VS. "Verb1 and verv2 preposition2"? When we have two verbs followed by a preposition separately, should we omit the first one?

*

*I am addicted to and pleased with the new drug.

*I am addicted and pleased with the new drug.

In what cases do we omit the first preposition and what cases we keep them both?

A: No, your second sentence is not idiomatic, as it means you are saying "addicted with" which (as you know) is not the normal collocation.  If you need two different prepositions, then you have to apply the proper preposition to each.  Example:

In order to find the treasure, you must gather up and bind together all of the parts of the map which I have scattered around the garden.

Still, your first sentence is a little odd, mostly  because of the unlikely juxtaposition of "addicted to" and "pleased with".  Phrasing it this way suggests you consider the addiction to also be a positive consequence.
In cases like this where you're stuck between an awkward phrasing and an incomplete phrasing, it may be best to rephrase it as a longer sentence, to accurately convey your meaning.  For example:

Although I am pleased with the new drug, I am addicted to it.


text:
Q: Spring MVC - POST a list of files with max count limit import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@PostMapping(value = "/upload",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseBody ResponseBody uploadAttachments(
        @RequestParam(value = "comment", required = true) String comment,
        @RequestPart(value = "files", required = false) List<MultipartFile> files
) {
    /* do magic */
}

I'm using this mapping to process a form with attachments. It consumes multipart/form-data.
How can I limit the maximum number of attached files to 10?

A: as indicated in this answer Spring Web MVC - validate individual request params
use @Size(max = ?) annotation on your parameter to limit the input size