text:
Q: Pure Component renders when no change is there? I have a pure Component like this?
interface Props {
 checkBoxTitleStyle?: any
  checkBoxBackgroundColor?: any
  onPressCheckBox?: (id, isChecked, selectedArray , options?: CheckBoxOptions) => void
  itemKey?: any
  mainContainerStyle?: any
}

class CheckBoxComponent extends PureComponent<Props> {
constructor()
render()
}

Now when i use this pureComponents in my otherComponent
   <CheckBoxComponent
          checkBoxKey={checkBoxKey}
          itemKey={get(item , 'id')}
          itemTitle={get(item , 'label', '')}
          isCheckBoxSelected={get(item , 'isChecked' , '')}
          checkBoxBackgroundColor={colors.DuckBlue}
        />

If i don't pass the prop mainContainerStyle then it works fine, it renders only when there is some change.
But if i pass mainContainerStyle in props then it renders everytime even if no change. Each render makes the performance slower . Is there is any way to fix it or why it is occuring so.

A: Make sure you don't pass to prop literal object like mainContainerStyle={{...other stuff...}} and save state of it instead.
Example

const { PureComponent, useState, useEffect } = React;

class CheckBoxComponent extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    console.log('render');
    return
{JSON.stringify(this.props)}

  }
}

const App = () => {
  const [mainContainerStyle, setStyle] = useState({position: 'absolute'});
  const [count, setCount] = useState(0);
  const checkBoxKey = 1;
  const item = {
    id: 1,
    label: 'label',
    isChecked: true,
    options: {}
  }
  const [options, setOptions] = useState(options);
  const [itemState, setItemState] = useState(item);
  const colors = {
    DuckBlue: ''
  }
  const get = (item, prop) => {
    return item[prop]
  }

return

    <CheckBoxComponent
       checkBoxKey={checkBoxKey}
        itemKey={get(item , 'id')}
        itemTitle={get(item , 'label', '')}
        isCheckBoxSelected={get(item , 'isChecked' , '')}
        checkBoxBackgroundColor={colors.DuckBlue}
        //mainContainerStyle={{}} // causes re-render
        mainContainerStyle={mainContainerStyle} // state
        //options={get(item , 'options')} // causes re-render
        //options={itemState.options} // or
        options={options}
    />
    <button onClick={() => setCount(count => count + 1)}>Change Style</button>

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );


text:
Q: Regular expression to replace digits after first 4 digits I am trying to write a Regular Expression that replaces all the digits of a number with *'s after first 4 digits.
For example
var number = 123456789

it should be replaced with 1234*****

A: In Javascript:
var maskedNumber = String(number).substr(0,4) + Array(String(number).length - 3).join('*');

In PHP:
$maskedNumber = str_pad(substr($number, 0, 4), strlen($number), "*");

A: In PHP:
function replaceDigit_callback($matches) {
    return $matches[1] . str_repeat('*', strlen($matches[2]));
}
$text = '1234567890';
echo $text, "\n";
$text = preg_replace_callback('#(\d{4})(\d+)#', 'replaceDigit_callback', $text);
echo $text, "\n";

Output:
1234567890
1234******

In JS:
var number = 1234567890;
var output = number.toString().replace(/(\d{4})(\d*)/, function (str, p1, p2) { return p1 + p2.replace(/./g, '*') });

A: You Can set your PHP coding..I provide you logic....
using System;
using System.Text.RegularExpressions;

class RegexSubstitution
{
   public static void Main()
   {
      string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
      Regex testRegex1 = new Regex( @"\d" );

      Console.WriteLine( "Original string: " + testString1 );
      Console.WriteLine( "Replace first 3 digits by \"digit\": " + testRegex1.Replace( testString1, "digit", 3 ) );
   }
}

A: Without regex:
var number = '123456789';
var output = '';

output = number.substr(0,4);
for ( var i = 0; i < number.length - 4; ++i )
{
    output += '*';
}

Input number has to be string !
Conversion
var number = 1234567890;

to string looks just like:
var number = 1234567890 + '';

or
var number = parseString(1234567890);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding diagonal borders to bottom/top of div element? I'm looking for the best way to add a diagonal border to the bottom of a div element. Preferably in a way so it would also work responsively.
This image is an example of how I would want it to look:

The dark part is the header of my website and the white part is where the content will start. So the diagonal lines will act like a seperator.
I made a little example but it's not really working yet: http://jsfiddle.net/ckknu2tr/
I'm using 2 different divs with a border, one for the left and one for the right side, code example:
.borderright {
    line-height: 0%;
    width: 0;
    border-top: 50px solid transparent;
    border-right: 400px solid white;
    position: absolute;
    bottom: 0;
    right: 0;
}

A: You could use SVG for this. Below is a short example, which can probably be simplified, I use SVG very rarely and am not that proficient with it.

body {
  background-image: url(http://i.imgur.com/XxGffrU.jpg);
  background-size: cover;
  background-position: center bottom;
  margin: 0;
}
#your_div {
  position: relative;
  top: 100px;
  margin-top: 100px;
  width: 100%;
  height: 100px;
  background: white;
}
#back {
  position: relative;
  top: -99px;
  width: 100%;
  height: 100px;
}
<div id="your_div">
  <svg id="back" viewBox="0 0 100 10" preserveAspectRatio="none">
    <path d="M 0,4 L 45,8 50,5 55,8 100,4 100,10 0,10 z" style="fill: white;"></path>
    <path d="M 0,0 L 45,8 55,8 100,0 100,10 0,10 z" style="fill: rgba(255,255,255,0.5)"></path>
  </svg>
</div>


text:
Q: Row matrix and move in row matrix I want to write a method that will move the zero in all 4 directions And update the map by moving the zero in the console, how do I do this?
    public static void main(String args[]) {
        String[][] map = {
                {".",".","."},
                {".","0","."},
                {".",".","."}
        };
        for(int i=0;i<map.length;i++){
            for(int j=0;j<map[i].length;j++){
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }

    }

there are no restrictions or anything, I just want to figure out how to move the zero, by any means.

A: The code you've written will just attempt the printing of your matrix. If you want to move the "0" element around your matrix, you first need to define an enum to establish the direction and then a method move() that given a direction d and a matrix m will move the "0" element accordingly.
The element movement is just a rotation that increments or decrements the respective index by taking care of the edge cases (the row and column's bounds).
public class Main {

    public enum Direction {
        UP, DOWN, LEFT, RIGHT
    }

    public static void move(Direction move, String[][] matrix) {
        int row = -1, col = -1, newRow, newCol;
        String temp;

        //Finding the position of the "0" element
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j].equals("0")) {
                    row = i;
                    col = j;
                    break;
                }
            }
            if (row != -1) break;
        }

        //If not 0 element is found then the method is terminated
        if (row < 0 || col < 0) {
            return;
        }

        switch (move) {
            case UP:
                newRow = row - 1 < 0 ? matrix.length - 1 : row - 1;
                temp = matrix[newRow][col];
                matrix[newRow][col] = matrix[row][col];
                matrix[row][col] = temp;
                break;
            case DOWN:
                newRow = (row + 1) % matrix.length;
                temp = matrix[newRow][col];
                matrix[newRow][col] = matrix[row][col];
                matrix[row][col] = temp;
                break;
            case LEFT:
                newCol = col - 1 < 0 ? matrix[row].length - 1 : col - 1;
                temp = matrix[row][newCol];
                matrix[row][newCol] = matrix[row][col];
                matrix[row][col] = temp;
                break;
            case RIGHT:
                newCol = (col + 1) % matrix[row].length;
                temp = matrix[row][newCol];
                matrix[row][newCol] = matrix[row][col];
                matrix[row][col] = temp;
                break;
        }
    }

Here is a link testing a possible implementation
https://www.jdoodle.com/iembed/v0/s63


text:
Q: Why can't the global variable delta be used in method of class? I'm a beginner of C++. In this sample, I want to use the global variable delta in method update_v() of class neuron. But it can't be used. Could you tell me why if you know?
#include<iostream>
#include<cmath>
using namespace std;

unsigned long nextt=1;
long clock=0;
long delta=0;

class neuron{
    public:
        double a,b,c,d;
        double current_v,current_u;
        double previous_v,previous_u;
        double accumulate;

        void update_v(){
            current_v=previous_v+delta(0.04*pow(previous_v,2)+previous_v)+accumulate;
        }
        void update_u(){
            current_u=previous_u+delta*a*(b*previous_v-previous_u);
        }
};

A: In void update_v(){, you do delta(0.04*pow(previous_v,2)+previous_v), so it makes the compiler thinks that you are calling a function named delta. But there's none, so it throws a error.
It looks like you forget to use the * operator:
void update_v(){
    current_v = previous_v + delta * (0.04 * pow(previous_v,2) + previous_v) + accumulate;
}


text:
Q: AWS s3 sync, cp recursive throw error if object does not exist I was using aws s3 sync and aws cp --recursive to copy a directory in s3 to local.
However I noticed that if a directory does not exist, the command does not throw an error at all.
aws s3 sync s3://path/to/a/directory/that/does/not/exist localpath
I expect the above command to throw an error, but that does not happen. Instead it creates an empty directory called localpath. How do I make it throw an error if the object does not exist in s3.


text:
Q: Passing JS function to Emscripten-generated code I have a piece of C++ code converted to JavaScript via Emscripten. I would like the converted C++ code to call back to the JavaScript code that calls it. Something like:
JavaScript:
function callback(message) {
    alert(message);
}

ccall("my_c_function", ..., callback);

C++:
void my_c_function(whatever_type_t *callback) {
    callback("Hello World!");
}

Is this possible somehow?

A: I believe the accepted answer is a bit outdated.
Please refer to this bullet point in the "Interacting with code" emscripten tutorial.
E.g.
C:

void invoke_function_pointer(void(*f)(void)) {
  (*f)();
}

JS:

var pointer = Runtime.addFunction(function() {
  console.log('I was called from C world!');
});
Module.ccall('invoke_function_pointer', 'number', ['number'], [pointer]);
Runtime.removeFunction(pointer);

This way the C-code does not need to be aware of that it is transpiled to JS and any bridges required can purely be controlled from JS.
(code hacked into message composer; may contain errors)

A: There is a new way of achieving your requirement which is via embind.
Consider the following piece of C++ code.
#include <emscripten/bind.h>
using namespace emscripten;

void cbTest(emscripten::val cb)
{
    cb();
}

EMSCRIPTEN_BINDINGS(my_module) {
    function("cbTest", &cbTest);
}

The cbTest C++ function takes in a emscripten::val. This can be an object of any kind. For us this is a function object.
This is how you will call it from JS
var cbFunc = function() {
    console.log("Hi, this is a cb");
}

Module.cbTest(cbFunc);

P.S This api is still under construction.

A: A thing that is frequently done in Emscripten is to map strong types to simple ones.
JS:
function callback(message) {
    alert(message);
}

var func_map = {
    0: callback
};

// C/C++ functions get a _ prefix added
function _invoke_callback(callback_id, text_ptr) {
    func_map[callback_id](Pointer_stringify(text_ptr));
}

ccall("my_c_function", ..., 0);

C++:
// In C/C++ you only need to declare the func signature and
// make sure C is used to prevent name mangling
extern "C" void invoke_callback(int callback_id, const char* text);

void my_c_function(int callback_id) {
    invoke_callback( callback_id, "Hello World!" );
}

And of course, you can add some glue code, so this gets very seamless.

A: I needed to write something very similar to what is described in the question. My code ended up looking like this:
C:

void call(void (*back)(char*)){
    back("Hello!");
}

JS:

function back(text){
    alert(Pointer_stringify(text));
}
var pointer = Runtime.addFunction(back);
var call = Module.cwrap('call', 'void', ['pointer']);
call(pointer);
Runtime.removeFunction(pointer);

Note that the pointer returned to the callback has to be dereferenced with Pointer_stringify.
You can find example code like this on GitHub.

A: Here's what I have gathered from several posts and by looking at Emscripten bundled code:
In C++:
#include <iostream>
#include <functional>

extern "C" {
  void registerCallback(void(*back)(const char*));
  void triggerCallback(char* message); // for invoking it from JS, just for this example
}

// global
std::function<void(const char*)> gCallback;

void registerCallback(void(*back)(const char*)){
    gCallback = back;
}

void triggerCallback(char* message){
  if (gCallback) {
    gCallback(message);
  } else {
    std::cerr << "Cannot pass '"<< message <<"' to undefined callback\n";
  }
}

An important thing, which was missing in other posts, is to compile C++ with RESERVED_FUNCTION_POINTERS=... flag, e.g.:
em++ -std=c++11 -s RESERVED_FUNCTION_POINTERS=20 source.cpp -s EXPORTED_FUNCTIONS="['_registerCallback','_triggerCallback']" -o try.html

After loading try.html into a browser, you can execute the following JS code in its console:
// Register a callback function
function callback(text){ alert("In JS: "+Pointer_stringify(text)); }
var cb = Runtime.addFunction(callback);
_registerCallback(cb);

// Invoke it with some "C string"
var jsStr = "XOXOXO";
var cStr = allocate(intArrayFromString(jsStr), 'i8', ALLOC_NORMAL)
_triggerCallback(cStr);

// Free Emscripten heap and release the function pointer
_free(cStr);
Runtime.removeFunction(cb);

You should see an alert with "In JS: XOXOXO".


text:
Q: htaccess redirect with wildcard when switching CMS Switching from ExpressionEngine to Wordpress and need to set up redirects in htaccess.
The paths to the articles will change from mysite.com/section/read/article-name
to mysite.com/article-name/. The section part of the path has six variants.
Unsure whether to look at redirectmatch or rewrite rule being a toatl novice with htaccess.
Thanks

A: Either would work, so I'll use RedirectMatch. To be specific about the section name, it would be:
RedirectMatch 301 "/(?:section|another-section|third-section)/read/(.+)$" /$1

Replacing your section names in there, separated by pipes.
Or for anything in a directory called read in a top level directory:
RedirectMatch 301 "/[^/]+/read/(.+)$" /$1

A: Since it is a one to one mapping and just the final part to be preserved, you don't need RedirectMatch. Redirect is sufficient
Redirect /section/read /

When it works as expected, you may set the status code to 301.
Redirect 301 /section/read /

If you want to use mod_rewrite instead, this would be
RewriteRule ^section/read/(.*)$ /$1 [R,L]

When everything works as it should, you may replace R with R=301. Never test with R=301.


text:
Q: (UndefinedFunctionError) undefined function List.Chars.to_charlist/1 I start a phoenix application server by: iex -S mix phoenix.server and get the following error:
[error] GenServer #PID<0.10289.0> terminating
** (UndefinedFunctionError) undefined function List.Chars.to_charlist/1
(elixir) List.Chars.to_charlist("localhost")
(postgrex) lib/postgrex/protocol.ex:46: Postgrex.Protocol.connect/1
(db_connection) lib/db_connection/connection.ex:134:      DBConnection.Connection.connect/2
(connection) lib/connection.ex:622: Connection.enter_connect/5
(stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol

I think it may caused by my config.exs:
config :bCareServer, BCareServer.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "bcareserver_dev",
  hostname: "localhost",
  pool_size: 10

The database has not been setup. When I run `mix ecto.setup, it gets the same error.
Postgresql works well:
[root@Makercas001 bCareDev]#su - postgres
[postgres@Makercas001 ~]$psql
psql (9.5.3)
Type "help" for help.

postgres=#

And it works fine on my MacBook, and only fails on CentOS.
Environment: CentOS6.5, Erlang/OTP 18, Elixir 1.2.6.

A: List.Chars.to_charlist was new in 1.3. Changelog.
Before, it was List.Chars.to_char_list

A: OH, I used a higher version of elixir and when reinstall elixir 1.2, I forgot to run mix do deps.get, compile again, forgive me ...


text:
Q: A simple question about delegate instantiation I am trying to read some code on the internet, but still cannot figure it out.
The code is:
private delegate string GetAString();

static void Main()
{
    int x = 40;

    GetAString firstStringMethod = new GetAString(x.ToString);

    Console.WriteLine(firstStringMethod());
}

My question is "delegate string GetAString()" does not need parameters, but when it is instantiated, it has the x.ToString parameter.
Why? Can anyone explain this?
Thanks.

A: A delegate is a special type of variable that can hold a reference to a method (not the result of the method but the method itself), allowing it to be passed around and invoked in places where you perhaps don't have access to the object the method belongs to.
From the docs:

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.

Your code:
GetAString firstStringMethod = new GetAString(x.ToString);

Note the lack of () at the end of x.ToString. We're not calling x.ToString() here. We're creating a GetAString and passing x.ToString (which is a method that satisfies the signature required by the delegate).
This means that when we call firstStringMethod() it will call x.ToString() and proxy the result to you.
Consider another example:
public delegate int Operation(int a, int b);

We could define multiple methods:
public int Sum(int a, int b)
{
    return a + b;
}

public int Multiply(int a, int b)
{
    return a * b;
}

And then switch according to user input:
Operation o;
switch (Console.ReadLine())
{
    case "+":
        o = new Operation(Sum);
        break;
    case "*":
        o = new Operation(Multiply);
        break;
    default:
        Console.WriteLine("invalid operation");
        return;
}

Console.WriteLine(o(4, 3));

If the user inputs "+" then the result will be 7, while inputting "*" will result in "12".
You can see from this example that we're not passing the arguments of Sum or Multiply when we instantiate o. We're simply passing the method. We then use the delegate to supply the arguments and get the result.
Example if user input is +
Example if user input is *


text:
Q: Pandas - Keep format as hours throughout column I have a dataframe that has several "total hours" columns. My problem is when these accumulate over a 24 hours it starts formatting the data as 1900-XX-XX 00:00:00 to account for years, months, and days. I just want it to display total hours, even if it's in the thousands of hours. How can I do this? Below is a sample of the df currently where you can see line 5 has the issue:
    DATE        HOURS RUN               ACCUMULATED HOURS (PER JOB)     TOTAL ACCUMULATED HOURS
0   2019-11-19  04:30:00                04:30:00                        04:30:00
1   2019-11-20  04:00:00                08:30:00                        08:30:00
2   2019-11-21  05:00:00                05:00:00                        13:30:00
3   2019-11-22  03:00:00                03:00:00                        16:30:00
4   2019-11-19  1900-02-19 00:00:00     1900-02-19 03:00:00             1900-02-19 16:30:00
0   2019-11-13  01:15:00                01:15:00                        01:15:00
1   2019-11-14  01:40:00                02:55:00                        02:55:00

The expected output for line 5 is:
    DATE        HOURS RUN               ACCUMULATED HOURS (PER JOB)   TOTAL ACCUMULATED HOURS
4   2019-11-19  1200:00:00              1203:00:00                    1216:30:00

A: I would use pd.to_datetime() to make sure everything is read as a datetime object and then you can use .strftime() within a lambda to get the desired format. In your case, it seems to be "%H:%M:%S" EDIT based on your edited expected output, we can simply add a condition in the lambda and force the "12" at the beginning, since as far as I know there's no datetime format the specifically matches your expected output:
import pandas as pd
import numpy as np
data = {'date':['2019-11-19','2019-11-20'],'hours run':['04:30:00','1900-02-19 02:30:00'],'acc hours':['04:30:00','1900-02-19 01:45:30']}
df = pd.DataFrame(data)
df['hours run'] = pd.to_datetime(df['hours run'])
df['acc hours'] = pd.to_datetime(df['acc hours'])
print(df)
cols = ['hours run','acc hours']
for i in cols:
    df[i] = df[i].apply(lambda x: str(((x - pd.to_datetime('1900-01-01')).days+1)*24+int(str(x.strftime("%H:%M:%S"))[0:2]))+str(x.strftime("%H:%M:%S"))[2:] if x.year < 2000 else x.strftime("%H:%M:%S"))
print(df)

Original dataframe I'm working with (after applying pd.to_datetime()):
         date           hours run           acc hours
0  2019-11-19 2019-11-20 04:30:00 2019-11-20 04:30:00
1  2019-11-20 1900-02-19 02:30:00 1900-02-19 01:45:30

After applying the lambda:
         date   hours run   acc hours
0  2019-11-19    04:30:00    04:30:00
1  2019-11-20  1202:30:00  1201:45:30

A: My test data:
df=pd.DataFrame({"date": [2019-11-19","2019-11-20","2019-11-21"],"runs":["04:30:00","14:00:00","15:30:00"]})

date     runs
0 2019-11-19 04:30:00
1 2019-11-20 14:00:00
2 2019-11-21 15:30:00

I convert the hours into timedelta and apply cumsum() as demo:
def tdconv(td):
     h,s= np.divmod(td.total_seconds(),3600)
     m,s= np.divmod(s,60)
     return f"{int(h)}:{int(m):02}:{int(s):02}"

df["cumsum"]=pd.to_timedelta(df.runs).cumsum().map(tdconv)

date     runs    cumsum
0 2019-11-19 04:30:00   4:30:00
1 2019-11-20 14:00:00  18:30:00
2 2019-11-21 15:30:00  34:00:00

A: just do that below for your hour columns
columns = df.columns.values
for col in columns:
    df[col] = df[col].apply(lambda x : str(x)[-8 : ])
print df


text:
Q: Display an image from a Byte Array from SQL into an ASPX page that is currently routed I have the most convoluted and headache of a way to attempt to load am image on a page. I am using VB.Net, my page is routed from a Routes.XML document, I have a SQL database with images stored as varbinary(MAX) fields, I need to load said images from the page into an  control, and everything that i use to use will not work with the routing.
If you need to see code examples let me know, but I was wondering if anyone knew of a way to display an image from bytes in this fashion.

A: use this  code:
Dim Ph As Byte()
Ph = DirectCast(YourImageFromDB), Byte())
               Dim img As Image = Nothing
    Dim stream = New MemoryStream(Ph)

    img = Image.FromStream(stream)

A: Ended up having a friend show me how he routed with images. What basically happens is that I needed to create an ASHX file to create the image, and put the full path from the image.ashx that I create as the URL I need. Worked like a charm. First time ever working with a handler file so i had no idea how to use it at first.


text:
Q: wpengine, wordpress multi-site not showing post content when used as varnish backend In order to achieve the magic of http://someserver.com/blog/ pointing to  myserver.wpengine.com/blog/ I had to create a multisite in wpengine.
From there I was able to point to the backend successfully with a basic varnish rewrite.
So, now the page shows up at someserver-dot-com/blog/ and appears to write post links to someserver-dot-com/blog/some-post when I set 'home' to 'http:/someserver-dot-com/blog'.
But, when I navigate to those posts, I get an internal WP "page not found".  It's not actually a 404, because if I go to http://someserver.com/blog/some-post it returns the page properly, which means the multi-site and references are working properly.  WTF!?!
I've checked the database, and everything appears to be proper in the DB tables.
To me, this is something inside some wordpress php function, cache or something within wpengine.  I've definitely purged the cache of all the things from the network login in the wordpress admin plugin for wpengine. Has anyone experienced this problem?
It's been a few days of debugging, and I've read every man page in existence, and tried setting paths via wp-config, and all that does is increase complexity of writes, and it doesn't seem like it works either.

A: Astonishingly,
This works:
In functions.php, right after php tags, add this line:
update_option('home','http://someblog.com/blog/');
Obviously, this should just add that to the 'home' keypair in the wp_2_options table, but actually it does something else.  It fires this at some point:
   $notoptions = wp_cache_get( 'notoptions', 'options' );
      if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
           unset( $notoptions[$option] );
           wp_cache_set( 'notoptions', $notoptions, 'options' );
    }

I believe this deletes option cache, and currently either wordpress or wpengine has an issue with some cache, and the plain vanilla 'home' keypair should have worked right in the first place, leaving 'site' as 'someblog.wpengine.com' and leaving all wp_config as the plain vanilla multi-site/root configs that wpengine will set-up.


text:
Q: Select last inserted data from table First  I tried to look for the answer on here(stackoverflow) as well as other sites like a microsoft forum, but couldn't find anything that answered my question. Or I just couldn't understand.
I'm working on a (school)project I got from a company, they gave me acces to their database. In here is a table with data from a sensor that registers stuff every once in a while.
Now  my question is: I want to get the last data inserted into the table and show just one row (echo or print, I dont really mind how, I just want it to work and to understand it.)
The table looks as followed:
Tablename= container_1
I want to show the last inserted data in COL 3.
Is there a way to do this with the table the company provided me with?

A: Using phpmyadmin you can:
Select * from your_table order by col1 desc Limit 1;

This way you'll only have the last entry


text:
Q: Fill null rows with last non-null value in R I have a data frame in R that contains an unusual format of data. I want to convert this to a regular format. Below is an example of the input -
Brand | Product | Store | Sales
A                         35
        Prod1             10
                  Store1  2
                  Store2  3
                  Store3  5
        Prod2             25
                  Store1  10
                  Store2  15

Basically, the file contains data at the store level, and then it's aggregated in "outer" rows at the product and brand level as well.
The output I'm looking for is -
Brand | Product | Store | Sales
A       Prod1     Store1  2
A       Prod1     Store2  3
A       Prod1     Store3  5
A       Prod2     Store1  10
A       Prod2     Store2  15

How can I transform this in R?

A: You can use tidyr::fill: https://tidyr.tidyverse.org/reference/fill.html
and finally filter out empty rows in Store.
df %>%
   fill(Brand) %>%
   fill(Product) %>%
   filter(drop_na(Store))


text:
Q: How to enable CORS in my Ajax code or Varnish configuration? I am getting
XMLHttpRequest cannot load http://example.com/system/applications. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my-ownServer.com:8081' is therefore not allowed access.

I am using Varnish as my reverse proxy and NGINX as application server which has configured on same server.
I have configured Varnish as reverse proxy and also handle CORS in below configuration but its not working
backend default {
  .host = "localhost";
  .port = "8080";
}
backend master {
  .host = "192.168.23.1";
  .port = "80";
}

 sub vcl_recv {
 if (req.url ~ "^/platform" ||
      req.url ~ "^/videos") {
       set req.backend = master;  } }
}
 sub vcl_deliver {
        if (req.request ~ "OPTIONS"){
  set resp.http.Access-Control-Allow-Origin = "*";
  set resp.http.Access-Control-Allow-Credentials = "true";
  set resp.http.Access-Control-Allow-Methods = "GET, POST, PUT, DELETE, OPTIONS";
        set resp.http.Access-Control-Allow-Headers = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token";
                set resp.status = 200;
                set resp.response = "OK";
        }
  if (obj.hits >= 0)
  {
    set resp.http.X-Cache = "HIT";
  }
    else
  {
    set resp.http.X-Cache = "MISS";
  }

  if (req.request ~ "GET"){
  set resp.status = 200;
  set resp.response = "OK"; }
        set resp.http.Access-Control-Allow-Origin = "*";
        set resp.http.Access-Control-Allow-Methods = "GET, POST, PUT, DELETE";
        set resp.http.Access-Control-Allow-Headers = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token";

        return (deliver);
}
sub vcl_fetch {
#  if (req.url ~ "\^platform"){
set beresp.http.Access-Control-Allow-Origin = "*";
set beresp.http.Access-Control-Allow-Methods = "GET, POST, PUT, DELETE, OPTIONS";
set beresp.http.Access-Control-Allow-Credentials = "true";
set beresp.http.Access-Control-Allow-Headers = "X-Accept-Charset,X-Accept,Content-Type,Origin, Accept,X-Requested-With, X-CSRF-Token"; #}
  }

and my Ajax Code is
 getApplications: function (serverRoot) {
            var deferred = new $.Deferred();
            var appURL = '/system/applications';
            $.ajax({
                url: serverRoot + appURL,
                type: 'GET',
           //     crossDomain: true,
                timeout: timeOut,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        log("system/applications call successful");
                        log("Body:\n" + xhr.responseText);

                        applications = $.parseJSON(xhr.responseText);
                        deferred.resolve(Mint.Core.clone(applications));
                    } else {
                        deferred.reject(" call not successful");
                    }
                },
                error: function (data, textStatus, xhr) {
                    deferred.reject(appURL + " rest call failed " + data.status + data.responseText);
                }

        });

in browser the request OPTIONS has
Remote Address:192.168.23.1:80
Request URL:http://example.com/system/applications
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:24.114.11.115
Origin:http://my-ownServer:8081
Pragma:no-cache
Referer:http://my-ownServer:8081/LG/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36
Response Headersview source
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:0
Date:Wed, 04 Feb 2015 08:50:10 GMT
Server:Apache-Coyote/1.1
Via:1.0 127.0.0.1 (squid/3.1.10)
X-Cache:MISS from 127.0.0.1
X-Cache-Lookup:MISS from 127.0.0.1:8080

Please correct me where i am going wrong  please do share your answers


text:
Q: How to style a Slider on React Native I have a specific sliders. How can I style them? I use react-native-slider. Here my code(I modified code from this example):
    render() {
        const sliderStyle = {
            sliderDummy: {
                width: 200,
                height: 80,
                position: 'absolute',
            },
            sliderReal: {
                backgroundColor: colors.primary,
                width: (this.state.slideValue / 50) * 200,
                height: 80,
                borderBottomRightRadius: 100,
                borderTopRightRadius: 100
            }
        }
        return (
            <View style={styles.container}>

                <View style={{overflow: 'hidden'}}>
                    <View style={{flexDirection: 'row', position: 'absolute'}}>
                        <View style={sliderStyle.sliderDummy}></View>
                        <View style={sliderStyle.sliderReal}></View>
                    </View>
                <Slider
                    style={{width: 200, height: 80}}
                    minimumValue={0}
                    maximumValue={50}
                    value={this.state.slideValue}
                    onValueChange={(value)=> this.setState({ slideValue: value}) }
                    maximumTrackTintColor='transparent'
                    minimumTrackTintColor='transparent'
                    thumbStyle={styles.thumb}
                />
                    <Text>{this.state.slideValue}</Text>
                </View>
            </View>
        );
    }
}

When I swipe right I have round corners in the middle of track:

But I need something like this:

Where is my mistake? Thanks.

A: I solved this problem easier way than expected. I just set trackStyle(react-native-slider) and this worked like a charm. But now I have another problem, how get slider style track like a "zebra".
render() {
        return (
            <View style={styles.container}>
                <Slider
                    style={{width: 150, height: 80}}
                    minimumValue={this.state.min}
                    maximumValue={this.state.max}
                    value={this.state.min}
                    onValueChange={(value)=> this.setState({ slideValue: value}) }
                    maximumTrackTintColor='transparent'
                    minimumTrackTintColor={colors.primary}
                    thumbStyle={styles.thumb}
                    trackStyle={styles.track}
                    step={1}
                />

                <Text>{this.state.slideValue}</Text>
                <Text>min {this.state.min}</Text>
                <Text>max {this.state.max}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    thumb: {
        width: 50,
        height: 80,
        backgroundColor: colors.primary,
        borderBottomRightRadius: 100,
        borderTopRightRadius: 100,

    },
    track:{
        height: 80,
        borderBottomRightRadius: 20,
        borderTopRightRadius: 20,
    }
});


text:
Q: How to apply latitude and longitude resolution to image mosaic in geoserver based on zoom level How we can skip points in the raster layer (created using image mosaic) based on zoom?
I think it's called latitude/longitude resolution or sometimes grid step.
Tried Point symbolizer/ filters in SLD, but not sure how to use filters to skip points.
Edit -
I created store and layers as mentioned in below link
https://geoserver.geo-solutions.it/multidim/multidim/mosaic_config/netcdf_mosaic.html
Everything works fine. Now the issue is all data is shown.
The default netcdf spatial resolution is 0.4 and I want to change this as per zoom levels. for ex for zoom 1-5=1, zoom 5-10=0.75 and so on

A: Found the solution, It's not what I need but still solves the issue.
The solution is to use wms_scale_denominator & Categories.
SLD block -
<ogc:Function name="parameter">
    <ogc:Literal>scale</ogc:Literal>
    <ogc:Function name="Categorize">
        <ogc:Function name="env">
            <ogc:Literal>wms_scale_denominator</ogc:Literal>
        </ogc:Function>
        <ogc:Literal>16</ogc:Literal>
        <ogc:Literal>100000</ogc:Literal>
        <ogc:Literal>8</ogc:Literal>
        <ogc:Literal>500000</ogc:Literal>
        <ogc:Literal>2</ogc:Literal>
        <ogc:Literal>1000000</ogc:Literal>
        <ogc:Literal>0.5</ogc:Literal>
        <ogc:Literal>5000000</ogc:Literal>
        <ogc:Literal>0.2</ogc:Literal>
        <ogc:Literal>10000000</ogc:Literal>
        <ogc:Literal>0.1</ogc:Literal>
        <ogc:Literal>20000000</ogc:Literal>
        <ogc:Literal>0.05</ogc:Literal>
        <ogc:Literal>60000000</ogc:Literal>
        <ogc:Literal>0.02</ogc:Literal>
    </ogc:Function>
</ogc:Function>


text:
Q: Extract additional method Info from Dll In my solution i have dll which contains methods in below format
    [TestMethod]
    [TestProperty("Priority", "P0")]
    [TestProperty("Owner", "vbnmg")]
    [TestProperty("Title", "Verify the log accessible")]
    [TestProperty("ID", "1")]
    public void LogAccesiblityTest()
    {
    //Test Code
    }

Some method have different priority,Owner,ID & Title
By Providing the dll  name & serach criteria (priority,Owner,ID & Title), can i get the methods name which are in given priority groupr or owner group etc.
I have the code through which i am getting the detail information of method names & parameres used, but i am not getting how to get the info from test property.
Can Someone please suggest how to do this.

A: It sounds like you're just looking for MethodInfo.GetCustomAttributes. Given your format, I'd probably write something like this:
public static Dictionary<string, string> GetProperties(MethodInfo method)
{
    return method.GetCustomAttributes(typeof(TestPropertyAttribute), false)
                 .Cast<TestProperty>()
                 .ToDictionary(x => x.Key, x => x.Value);
}

(That's assuming the TestPropertyAttribute has Key and Value properties, of course.)
To just detect the presence of an attribute (which you might want for  TestMethodAttribute) you can use MemberInfo.IsDefined.

A: Assuming you already have the MethodInfo objects (because you said you already have the code to get the information), you can call MethodInfo.GetCustomAttributes to get those attributes. It also has an overload where you can pass the type of the attribute you look for. You then just need to cast the results and inspect their properties.


text:
Q: Pick every element once from sorted array I have a sorted array and I want to take every element once into an other array
Example:
Input:  array[] = { 1,2,2,3,3,5 }
Output: array2[] = { 1,2,3,5 }

Here is my attempt
int db = 0,array2[100];

for(int i = 0;i < k;i++){
    int j = 0;
    for(j = 0;j < db;j++){
        if(array[i] == array2[j]){
            break;
        }
    }
    if(i == j){
        array2[db] == array[i];
        db++;
    }
}
/* PRINT
for(int i = 0;i < db;i++){
    cout<<array2[i]<<" ";
}
cout<<endl;*/

A: There's a standard algorithm std::unique_copy that does exactly this:
auto end = std::unique_copy(std::begin(array), std::end(array), array2);

The returned iterator end points to one past the last element that is inserted into array2, so you can calculate the number of unique elements that were copied like this:
auto num = std::distance(array2, end);

I would recommend using std::vector instead of arrays anyway, and then you don't have to worry about computing the number of copied unique elements. In case you use a vector the 3rd argument to the algorihtm would be std::back_inserter(vec).

A: We can't give you an answer about what happened to your code if we don't know what k is.
But generally, if you want unique values from a sorted array, the quick way to do it is just employ the set.
#include <set>

then set<int, greater<int> > s1;
for (int i: array) s1.insert(i);

this will only add unique value in the new vector in increasing order.


text:
Q: Dragging a Path I'm trying to drag a path around my canvas by re-plotting the coordinates, stored in an array of point,  then re creating it. The path drags but flips horizontally and vertically, like a mirror image, over where the user clicks. I have no idea why.
private void drag(MotionEvent e) {
    // TODO correct weird flip

    if (clicked(e)) {
        for (Point p : points) {
            int modX = (int) (e.getX() + (e.getX() - p.x));
            int modY = (int) (e.getY() + (e.getY() - p.y));
            p.set(modX, modY);
        }
        updateOutline();
    }
}

private void updateOutline() {
    // update the outline
    outline = new Path();
    outline.moveTo(points.get(0).x, points.get(0).y);

    for (Point coor : points)
        outline.lineTo(coor.x, coor.y);
}

Any help will be appreciated, thanks

A: In my opinion there is a problem in these lines:
int modX = (int) (e.getX() + (e.getX() - p.x));
int modY = (int) (e.getY() + (e.getY() - p.y));

Consider two points A(1,5) and B(4,5). If user clicks in C(3,6), then point A will be translated to A'(5, 7) and point B to B'(2, 7). As you can see, points A and B will change places.
You might want to store start drag position and calculate distance and updated path position using this information.


text:
Q: Add page into existing PDF document using C# and iTextSharp int iNbFichier = 0;
while (File.Exists(folderName + "/" + newFile + ((iNbFichier > 0) ? "_" + iNbFichier.ToString() : "") + ext))
{
    iNbFichier++;
}

// open the reader
PdfReader reader = new PdfReader(oldFile);
document = new Document(PageSize.A4, 5, 5, 120, 60);

// open the writer
FileStream fs = new FileStream(folderName + "/" + newFile + ((iNbFichier > 0) ? "_" + iNbFichier.ToString() : "") + ext, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

int numberPage = reader.NumberOfPages;

// the pdf content
PdfContentByte cb = writer.DirectContent;

for (int i = 1; i <= reader.NumberOfPages; i++)
{
      // create the new page and add it to the pdf
      PdfImportedPage page = writer.GetImportedPage(reader, i);
      cb.AddTemplate(page, 0, 0);
      if(i != numberPage) document.NewPage();
      cb = writer.DirectContent;
}

if (availableSpace < 90)
{
      writer.NewPage();
      cb = writer.DirectContent;
}

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 8);

// write the text in the pdf content
cb.BeginText();
string text = "Le " + DateTime.Now.ToString().Substring(0, 10);
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 455, 750, 90);
cb.EndText();

// write the text in the pdf content
cb.BeginText();
text = salarie.NOM + " " + salarie.PRENOM;
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 465, 750, 90);
cb.EndText();

// write the text in the pdf content
cb.BeginText();
text = "Signature :";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 475, 750, 90);
cb.EndText();

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(globale.EncodePhoto(this.signature));
//img.SetAbsolutePosition(485, 750);

img.Border = 0;

//Resize picture to fit 380x150 ratio if its bigger
int intMaxWidth = 100;
int intMaxHeight = 50;
BitmapImage bmpMain = this.signature;
if (bmpMain.Height > intMaxHeight || bmpMain.Width > intMaxWidth)
{
      double dblHeightRatio = Convert.ToDouble(intMaxHeight) / Convert.ToDouble(bmpMain.Height);
      double dblWidthRatio = Convert.ToDouble(intMaxWidth) / Convert.ToDouble(bmpMain.Width);
      double dblScaleRatio;

      //Use the smaller ratio
      if (dblHeightRatio > dblWidthRatio)
      {
            dblScaleRatio = dblWidthRatio;
      }
      else
      {
            dblScaleRatio = dblHeightRatio;
      }

      int intNewHeight = Convert.ToInt32(bmpMain.Height * dblScaleRatio);
      int intNewWidth = Convert.ToInt32(bmpMain.Width * dblScaleRatio);

      img.ScaleAbsolute((float)intNewWidth,
                                                    (float)intNewHeight);
}

img.SetAbsolutePosition(480, 700);
img.RotationDegrees = 90;

cb.AddImage(img);

// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();

If the available space into my table and footer is < to 90 then I want to create a new page and put the signature on the last page which is created.
But my code don't works. Someone can help me to solve this ?
My application is for tablet so the duplicate treatment take too much resources to be used in this case.

A: string oldFile = "Tmp.pdf";
string newFile = nomFichier = DateTime.Now.ToString().
                              Substring(0,10).Replace('/','-') +
                              "_" + salarie.NOM + "_" + salarie.PRENOM;
string ext = ".pdf";
string folderName = "FICHE_EPI";

//Si le tableau est trop bas pour faire passer la signature
if (availableSpace < 90)
{
    var tempFileLocation = @"Tmp2.pdf";
    var bytes = File.ReadAllBytes(@"Tmp.pdf");

    using (var reader1 = new PdfReader(bytes))
    {
        var numberofPages = reader1.NumberOfPages;
        var pages = 1;

        if (pages != 0)
        {
            using (var fileStream = new FileStream(
                   tempFileLocation,
                   FileMode.Create,
                   FileAccess.Write))
            {
                using (var stamper = new PdfStamper(reader1, fileStream))
                {
                    var rectangle = reader1.GetPageSize(1);
                    for (var i = 1; i <= pages; i++)
                        stamper.InsertPage(numberofPages + i, rectangle);
                }
            }
        }
    }
    File.Delete(@"Tmp.pdf");
    File.Move(tempFileLocation, @"Tmp.pdf");

This solve my problems.


text:
Q: Uncharted Golden Abyss : What is the location of Chapter 14? In Uncharted Golden Abyss, during chapters 2-12, the action is located in a south american counrty's jungle (presumably Panama).
Chapter 13 is a cut-scene located in the mansion of Chase's grandfather, in which there are talks about the Visigoths.
Then the action skips to an island in chapter 14, but I did not get where it is located.
Chase points to the map mentioning a place called "Casca Vieja" at this moment in the cut-scene.
Where is it supposed to be ?


text:
Q: 1 node appearing less in recursive implementation of Tree in C++ I have created an implementation of a complete binary-tree in C++ using class and recursion. At depth = 6 it is supposed to have 63 nodes. But in the output I can see only 62 nodes. Can someone please point out the problem?
class node{
public:
    node *left, *right, *root, *it;
    int data,m;

void create(){
        root = new node;
        it = root;
        root->data = 1;
        const int n = 6;          // Depth to be passed
        addchildren(root,n); }

void addchildren(node *x,int z)   // Recursion (z = No. of levels)
    {

        if (z==1)
            return;
        else
        {
            it->left = new node;
            it->left->data = 1;
            it->right = new node;
            it->right->data = 1;
            addchildren(it->left,z-1);
            addchildren(it->right,z-1);
            return;
        }
    }

void display(node *x,int z)
    {

        if (z==1)
            return;
        else
        {
            cout<<it->left->data;
            cout<<it->right->data;
            display(it->left,z-1);
            display(it->right,z-1);
            return;
        }
    }
};
int main()
{
    node A;
    A.create();
    A.display(A.root,6);
}

Output : 11111111111111111111111111111111111111111111111111111111111111 (62 1s)

A: Take a look at your display function:
void display(node *x,int z) {
        if (z==1)
            return;
        else
        {
            cout<<it->left->data;
            cout<<it->right->data;
            display(it->left,z-1);
            display(it->right,z-1);
            return;
        }
    }
};

Let's Rubber Ducky this function:

If we're on the lowest row of the tree, just return instead of displaying it.
Else, display out two children on the row below us, and then have them display their children.

This is an...interesting way of writing a display for a tree. I'd strongly suggest just printing the node you're currently on and then letting its children print themselves. This convoluted way of printing children yourself is causing your problem. After all, who is the root node a child of? Nobody! So who prints the root node? Nobody!!
In addition to this, you really really really need to set the left and right pointers in your nodes. As of now you have a bunch of wild pointers. I'd suggest adding a constructor to your node class to do this for you.
And lastly: why are you testing with a depth of 6? If I had to count that many 1's every time I ran the program to test I'm pretty sure I'd be pulling my hair out in the space of an hour. Start with a tree of depth 1 (which should fail with your current code!). If that works, go to a depth of 2. At most I'd test with a depth of 3. After all, the case of depth 6 vs. 3 is probably not at all different!


text:
Q: The constructor Vehicle(String[], int) is undefined I'm very new with java and can't figure this out!
this is how it should look like , but it gives me an error and i'm not sure if i have to convert it or not !
or i'm doing something else wrong!!!
here is my requirements:
Assign values to variables using the provided vehicle data. Refer to the Data File Layout Information for information of accessing these vehicle data values.
                      1. speeds
public class Bicycle extends Vehicle implements IOutput {

private static int speeds;

public Bicycle(String[] vehicleData) {
    super(vehicleData,speeds);   // get error: The constructor Vehicle(String[], int) is undefined

            // or i should this one :
    speeds = Convert.toInteger(vehicleData[0]);
}

here is the vehicle class
public Vehicle(String[] vehicleData) {
    count++;
    owner= new Owner(vehicleData);

    setVehicleType(Convert.toInteger(vehicleData[0]));
    make = vehicleData[1];
    model = vehicleData[2];
    color = vehicleData[3];
    purchaseDate = vehicleData[4];
    cost = Convert.toDouble(vehicleData[5]);
}

A: your constructor in your Vehicle class accepts only string[] and you are passing a string[] and an int.
change
super(vehicleData,speeds);   // get error: The constructor Vehicle(String[], int) is undefined

to
super(vehicleData);   // your error'd now disappear

or declare speeds in your super class Vehicle.
int speed;
public Vehicle(String[] vehicleData, int speed)

A: super is calling the Vehicle constructor, which accepts only a String, not a String and a int.
Change to this.
// remove static
int speed;
public Bicycle(String[] vehicleData) {
    super(vehicleData);
    speeds = Integer.valueOf(vehicleData[0]);
}


text:
Q: Apache start failing after apache config modifications, showing syntax error, cannot load php5apache2_2.dll into server I am stuck again with apache setup guys. I am working on a 64-bit system running Windows 7 professional with service pack 1. I copied the working php5 installation directory from teammates, copied the necessary .dll files from inside php5 installation folder (like they were in the working setup of teammates) to my windows/system32/. Apache server started successfully with the default apache config (httpd.conf) file. I was able to access localhost in browser. But php code was not parsing. I noticed no such line like the following in the apache config file:-
# PHP5 module
LoadModule php5_module D:/php5/php5apache2_2.dll

If I add this line, apache server start fails. Running test configuration gives the following error -
httpd.exe: Syntax error on line 60 of C:/Program Files (x86)/Apache Software Foundation/Apache2.2/conf/httpd.conf: Cannot load D:/php5/php5apache2_2.dll into server: The specified procedure could not be found.

But the php5apache2_2.dll file is there in the specified location and I have given all permissions to the current system user to the php5 installation directory. The same line also appears in the apache error log. Another thing here is that I am not sure when exactly logs are written to the log file. I am confused if log entries are not made if I have opened the log file for reading? lol ... because I could not observe a pattern in when entries are made. I saw some log entries being made, some not. But that is a separate problem for now.
I had previously setup apache, php on the same system, on another hard disk. I had followed the same steps like I followed now and it did setup successfully, although after a lot of head-scratching, like the log file entry confusion I wrote above. I don't remember how exactly I fixed it earlier. But, I tried with the same apache config file (the one which was working earlier on the previous setup on the old hard disk - had taken a backup), but it still gives the same error.
Update
I read http://us3.php.net/manual/en/install.windows.apache2.php and added AddHandler application/x-httpd-php .php right after LoadModule php5_module "D:/php5/php5apache2_2.dll". Still no success.
I also read this blog where some VC6 and VC9 binaries are mentioned. I don't know about them. Do I need to do something about that?
Further Update
I downloaded apache from http://httpd.apache.org/download.cgi - the "Win32 Binary without crypto (no mod_ssl) (MSI Installer)" option.

A: Most likely you have incompatible Apache build. You have not mentioned where did you download Apache HTTPD from + what PHP version do you have.

*

*Get latest Apache build from Apache Lounge website -- their builds are compiled with VC9 while apache.org builds are still VC6. You need VC9 build as that is how official PHP builds are compiled now (you can read small explanation on PHP for Windows website -- see link in #2).

*Get Thread-Safe build of PHP from PHP for Windows (based on your question you want to run it as Apache module). If you want to run it as FastCGI, then Non-thread safe build is required.

*Disable all non-default php extensions (until you successfully start Apache with PHP working).

*Configure your PHP and Apache if necessary (those Apache config lines you have mentioned so far are fine).
P.S.
"copied the necessary .dll files from inside php5 installation folder (like they were in the working setup of teammates) to my windows/system32/"

*

*You are on x64 bit version of Windows. C:\windows\system32\ is for 64-bit processes/files ONLY. In your case Apache and PHP are x32 so the correct place would be C:\Windows\SysWOW64.

*There is no real reason to copy those files there -- you could add your PHP installation path (D:\php5\) to the PATH environment variable (place it in front) and Windows will find all files automatically (restart may be required) -- works fine for me.
P.P.S.
Instead of installing it manually, you could use one of the already pre-configured stacks: XAMP, WAMP or similar.

A: I fixed the problem. Actually absence of some necessary dll files, not sure which particular file, was the reason and I was trying in the absence of a lot of dll files.
What I did was, I had followed the apache configuration part from teammate 1 and then copied the php5 directory from teammate 2 (who was on a 32-bit system with Windows px). I assumed that the php 5 folder would be same and was wrong. The problem got fixed when I took the php 5 folder of teammate 1.
I checked and found there were many differences in the contents of the two php5 folders, mainly dll files. Absence of necessary dll files must have been the issue because I needed a system restart after taking the correct php5 folder of teammate 1.
Moral of the story -
While copying, don't apply brain and copy from the same place :)

A: You don't have to copy any of those (like libeay32.dll, ssleay32.dll) files to anywhere, the problem can just be solved through adding the php installation directory to the system path environment variable.


text:
Q: MODIFY the view hierarchy of another app with an Accessibility Service It is common knowledge that we can observe or query the view hierarchy of any app with an AccessibilityService:
Create your own accessibility service.
It is also possible to perform actions on behalf of the user:
Developing an Accessibility Service for Android.
My question is, can we modify the view hierarchy of a foreground app with an AccessibilityService?

I have already referred the following questions:

*

*How do I add and remove a layout programmatically from an accessibility service?

*Get view of AccessibilityNodeInfo to create overlay.
What they're doing is using the WindowManager and the SYSTEM_ALERT_WINDOW permission to overlay a view on top of the app in the foreground. The problem with this approach is that if the user presses BACK or HOME, the app is dismissed, but the view remains visible on the screen, even after the app is gone. The view is on TOP of the view hierarchy, and not a part of it.

*

*Is there a way to add / modify the AccessibilityNodeInfo objects?

*Are these the same as a View or ViewGroup?

*Are we allowed to add views or modify existing views with an AccessibilityService?

My requirement is to display a small view within the app itself.
  It has to be part of the view hierarchy of the app, so that it stays
  or goes with the app. For this I need to modify the view hierarchy of
  the app, namely the AccessibilityNodeInfo objects retrieved from the
  service.

What I want is something similar to addView(), but add the View to the view hierarchy of the app itself, not on top of it.
How can we do this? Is this possible?
UPDATE:
Apps that support Custom Views for Accessibility

A: No, you can't modify the view hierarchy of another app because it exists in a separate process.
This is similar to not being able to modify accessibility nodes from within an accessibility service.

A: 1) You can exploit draw over other apps permission. That solution will allow you only to draw overlays over another apps and not to change another apps behavior.
2) You can exploit instrumentation test mechanism. If you have enough information about the app(app id, activity name) and enough privileges (Run an instrument test from within app and wait for result), or root privileges. Here is an example:
@RunWith(AndroidJUnit4::class)
class InjectView {
    @get:Rule
    val activityRule = ActivityTestRule<MainActivity>(MainActivity::class.java)

    @Test
    fun injectView() {
        val rootLayout = activityRule.activity.findViewById<ViewGroup>(android.R.id.content)
        activityRule.runOnUiThread {
            rootLayout.addView(TextView(activityRule.activity).apply {
                text = "Injected View"
            })
        }

        Thread.sleep(10_000)
    }
}

A: You can still go with the approach of drawing on top of the app, not as part of its view hierarchy (which is impossible) - using SYSTEM_ALERT_WINDOW permission.
In order to know when the app is dismissed and dismiss your own overlay - listen to the accessibility event TYPE_WINDOW_STATE_CHANGED and check that there's a package change.
You can also go further with listening to TYPE_WINDOW_CONTENT_CHANGED and determining that there was some layout update.
More accessibility events might come in handy or fine-tuning your overlay's accuracy.
In short - as long as you have the appropriate information to know about the underlying app's layout and when things happen, you can draw on top as if it's part of the app.
Might be tricky and require some calculations since you're not able to just push views into the hierarchy, but totally doable.


text:
Q: How do I get rid of these symbols from the text fields when reading a CSV file? Every time I open a CSV in Python, I keep seeing these weird symbols that represent the punctuation and special characters within the text fields. For example:
import pandas as pd
import csv
data = pd.read_csv("Test.csv", encoding="ISO-8859-1") #utf-8 encoding doesn't work
data.head()

The column with text will have something like "Assassinâ\x80\x99s creed origins".
So I guess you're wondering how I created the csv in the first place?
Here's the code I used:
def updateSubs_file():
    upload_count = 0
    import csv
    location = "csvs"
    filename = "Test.csv"
    file = location + filename
    with open(file, 'w', newline='', encoding='utf-8') as file:
        a = csv.writer(file, delimiter=',')
        headers = ["Title","Url","Author","Score"]
        a.writerow(headers)
        for sub in subStats:
            a.writerow(subStats[sub][0])
            upload_count+=1

        print(str(upload_count) + " rows have been uploaded")

updateSubs_file()

So I can see there's already an encoding mismatch when creating the csv and opening but I added the encoding="" arguments initially to avoid Unicode Decode Errors. This may/may not be a factor in my issue.
Your help would be appreciated in working out what is happening to my csvs when I'm uploading/reading them in Python.

A: UTF-8 does work.  You wrote it with UTF-8, so decode it with UTF-8.  For example, undoing the incorrect ISO-8859-1 decoding and re-decoding with utf8:
>>> s='Assassinâ\x80\x99s creed origins'.encode('iso-8859-1').decode('utf8')
'Assassin's creed origins'

If you are having problems decoding what you wrote with utf8, show the exact code with sample input and output to reproduce the issue.


text:
Q: Javascript disabled button does not gets enabled when the form is completed I have a form and I wanted to disable the submit button unless the required fields are filled.
So I added this:
$('#submitBtn').attr('disabled', true);

if ($('#inputMobile').val() != '' && $('#inputEmail').val() != '' && $('#inputPassword').val() != '' && $('#inputPasswordConfirmation').val() != '') {
      $('#submitBtn').attr('disabled', false);
}

Now it works fine and disable the submit button when the page loads but when I fill in the form fields, it does not enable the button however I tried setting the disabled attr to false.
So what's going wrong here? How can I solve this issue?

A: May be you need to addListener on form?
Also you could check solution in similar question
https://stackoverflow.com/a/67961881/19282017

A: Your code runs once, when the page is loaded, you need action after the user enters data. Use a change event.
You need a way to specify the event on all 4 fields, so give your four input fields a common class, for example registerInput.
<input type="text" class="registerInput">

Do that for all 4 of your fields.
Then specify a change event, selecting that class, so that your test is run every time the user changes one of the fields.
$(".registerInput").change(function() {
  if ($('#inputMobile').val() != ''
      && $('#inputEmail').val() != ''
      && $('#inputPassword').val() != ''
      && $('#inputPasswordConfirmation').val() != '') {
        $('#submitBtn').attr('disabled', false);
  }
});

A: With this dummy code, I just wanted to show that your code for changing the attribute is completely true. It seems your code doesn't meet the condition in the if statement.

$('#but2').attr('disabled',true)

$('#but1').on('click',() => {
  if(true){
    $('#but2').attr('disabled',!$('#but2').attr('disabled'))
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="but1">Toggle</button>
<button id="but2">Change me</button>


text:
Q: How do I use different Post-Processing effects on different cameras in Unity 2017.4.2f2? Before I explain my situation, it's important that I mention I'm using an older version of Unity, 2017.42f2 (for PSVITA support). for this reason, I'm also using the old Post-Processing Stack.

I'm making a game in which I want a lot of bloom on the UI, but not as much for the rest of the game. I used a camera to render the UI, gave it Post-Processing (Screen Space - Camera on Canvas),

and another one to render the rest of the game

Each is given a different profile to use different effects.

My expectation is that the UI renderer camera would only apply it's effects to the Canvas. Instead, it also applies them to the camera beneath it; the game renderer camera.
As you can see I used Don't Clear clear flags. I also tried Depth-only, to see if it would make a difference.
I'm lost as to what I could do. Grain and bloom get applied to everything

yet the profile for those effects is only given to the UI renderer Camera's Post Processing Behavior Script.

Does anyone have any suggestions or ideas? I'm lost.


text:
Q: Getting syntax error in Python code step in zap I'm getting a syntax error and I can't understand why.
I'm writing a simple Zap Code step to set up some values based on input values with a series of if-else statements.
if input_data.['workbench'] == 'True':
    workbench = 'False'
else:
    workbench = 'N.A.'
if input_data.['office'] == 'True':
    office = 'False'
else:
    office = 'N.A.'   # this is the line with the error

When I do a test run of this Python in a Zapier Code step, I get:

Traceback (most recent call last):
SyntaxError: invalid syntax (<string>, line 8)

I don't expect to get a syntax error at all, and I don't understand why one should occur at line 8 when there is a similar if-else construct prior to that which includes line 8.
There are similar, subsequent constructs before a final return statement (which is a Zapier mechanism).

A: Seems like a simple typo: The last character on this line is not a tick ('), but an apostrophe ('):
office = 'N.A.'

A: You see in the line that caused the error, the comment is highlighted as red (may be different colors in other IDEs), which indicates it is recognized as part of a string. Hence the error is cause by the string literal not closing appropriately, because of the typo of '.


text:
Q: How to get the value of the root? I have this statement:

If $\frac{\sqrt{7}}{\sqrt{5}+\sqrt{3}} \approx \frac{2}{3}$, Which of
  the following values are the closest to $\sqrt{21}$ ?
A) 68/15 B) 14/3 C) 19/4 D) 55/12 E) 9/2

My development was:
$\frac{\sqrt{7}}{\sqrt{5}+\sqrt{3}}  = \frac{\sqrt{35}-\sqrt{21}}{2} \approx \frac{2}{3}$
My idea was to treat the sign $\approx$ as a sign $=$ and thus eliminate roots and clear $\sqrt21$, with which I have obtained $55/12$ but I do not know if this is correct.
$\frac{\sqrt{35}-\sqrt{21}}{2} = \frac{2}{3}$
$35 = (\frac{4}{3} +\sqrt{21})^2$
$\sqrt{21} = \frac{110}{9} * \frac{3}{8} = 55/12$
So my doubt is: Can I treat a $\approx$ sign as a $=$ sign to work like an normal equation?

A: Rearrange:
$$\frac{\sqrt{7}}{\sqrt{5}+\sqrt{3}} \approx \frac{2}{3} \iff \frac{7}{\sqrt{35}+\sqrt{21}} \approx \frac{2}{3} \Rightarrow \sqrt{21}\approx \frac{21}{2}-\sqrt{35}$$
Use linear approximation to find $f(35)=\sqrt{35}$:
$$f(x_0+\Delta x)\approx f(x_0)+f'(x_0)\cdot \Delta x \ ;\\
f(36-1)\approx f(36)+\frac1{2\sqrt{36}}\cdot (-1)=6-\frac1{12}=\frac{71}{12}$$
So:
$$\frac{21}{2}-\frac{71}{12}=\frac{126-71}{12}=\frac{55}{12}.$$

A: From
$$\left(\frac23\right)^2\approx\left(\frac{\sqrt7}{\sqrt5+\sqrt3}\right)^2$$
we get
$$\frac49\approx\frac{7}{5+3+2\sqrt{15}},$$
hence $\sqrt{15}\approx31/8$.
 Now we have
$$\frac{2\sqrt{3}}3\approx
\frac{\sqrt7\sqrt3}{\sqrt5+\sqrt3}=\frac{\sqrt{21}}{\sqrt5+\sqrt3}.$$
Using the approximate value for $\sqrt{15}$ we arrive in
$$\sqrt{21}\approx\frac{55}{12}.$$


text:
Q: how to show text with time difference? (monodevelop c#) I made a GTK# 2.0 Project from MonoDevelop, and modified MainWindow.cs like this;
using System;
using System.Threading;
using Gtk;

public partial class MainWindow : Gtk.Window
{
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
    }

    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

    protected void OnButtonClicked(object sender, EventArgs e)
    {
        textview.Buffer.Text = "Hello, world!";
        Thread.Sleep(2500);
        textview.Buffer.Text += Environment.NewLine;
        textview.Buffer.Text += "Hello, world!";
    }
}

what I intended is: first "Hello, world!" is shown, and 2 seconds and half later, another "Hello, world!" is shown at next line.
but, what actually happend when I pressed the button: two "Hello, world" is shown simultaneously, after a term of 2 seconds and half.
then how can I show two lines with a time difference?

A: Use Task.Delay instead. You need to mark the method you call it from async.
await Task.Delay(3000);

A: @Doruk
using System;
using System.Threading;
using Gtk;

public partial class MainWindow : Gtk.Window
{
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
    }

    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

    protected async void OnButtonClicked(object sender, EventArgs e)
    {
        textview.Buffer.Text = "Hello, world!";
        textview.Buffer.Text += Environment.NewLine;
        await Task.Delay(2500);
        textview.Buffer.Text += "Hello, world!";
    }
}


text:
Q: How can I alter a connector with ksqldb once it has been already created? Once I have a connector created by using the ksqldb expression CREATE SOURCE CONNECTOR..., how can I make changes with ksqldb? Is there a way to alter the initial definition? Something like ALTER CONNECTOR...? If not, what is the proper way to handle changes in connectors with ksqldb?

A: Kafka Connect is stateless, so it's safe to run DROP + CREATE CONNECTOR with new config


text:
Q: Trying to extract from the deep node with scrapy, results are bad As a beginner I'm having a hard time, so I'm here to ask for help.
I'm trying to extract prices from the html page, which are nested deeply:

second price location:

from scrapy.spider import Spider
from scrapy.selector import Selector

from mymarket.items import MymarketItem

class MySpider(Spider):
    name = "mymarket"
    allowed_domains = ["url"]
    start_urls = [
        "http://url"
            ]

    def parse(self, response):
        sel = Selector(response)
        titles = sel.xpath('//table[@class="tab_product_list"]//tr')
        items = []
        for t in titles:
            item = MymarketItem()
            item["price"] = t.xpath('//tr//span[2]/text()').extract()
            items.append(item)

        return items

I'm trying to export scraped prices to csv. they do export but are being populated like this:

And I want them to be sorted like this in .csv:

etc.
Can anybody point out where is the faulty part of the xpath or how I can make prices be sorted "properly" ?

A: .extract() returns a list, even if just one argument found, take the first element of the list .extract()[0]

A: It's difficult to say what's wrong with the path. Install firepath extension for Firefox to test your xpath queries. One note for now:
titles = sel.xpath('//table[@class="tab_product_list"]//tr')

In your screenshot you have nested tables, so //tr will give trs from nested tables too.
def parse(self, response):
        sel = Selector(response)
        titles = sel.xpath('//table[@class="tab_product_list"]/tr')  # or with tbody
        items = []
        for t in titles:
            item = MymarketItem()
            item["price"] = t.xpath('.//span[@style="color:red;"]/text()').extract()[0]
            items.append(item)

        return items


text:
Q: What does "smart with someone" mean?
Dudley and I were in the alleyway between Magnolia Crescent and Wisteria Walk," said Harry, speaking fast, fighting to control his temper. "Dudley thought he'd be smart with me, I pulled out my wand but didn't use it. Then two dementors turned up —"

Does it mean to outsmart someone? or just another way of saying make a joke on someone?

A: Being 'smart with someone' means to be very clever with someone deliberately (For example) they don't like the other person or they want to go ahead of them in some way.

e.g. sentence:
rude person: you need to scoot over
me: don't get smart with me
rude person: what's your problem
me: that's not how you ask


text:
Q: Linear regulator drawing power when powered from output only I have a microcontroller circuit with a 3.3v linear regulator providing power when run by a 5v supply, the circuit can also be run directly from a 3v battery which connects to the output side of the regulator.
I have found that when powered from the battery the regulator consumes 20mA.
Is there a proper way of designing this type of circuit so that when powered by the battery the linear regulator is isolated and doing nothing?
I am trying to keep the circuit design as low cost as possible so I would like to stick with a cheap 3.3v regulator and change the circuit some other way.
Any advice would be appreciated,
Thanks

A: A few options:

*

*find a regulator that tolerates 'back feeding' and consumes less current in that situation

*isolate the regulator with a (schottky) diode. this will cause some voltage drop that might need compensation. A primitive way to do that is to put the same type of diode in the ground lead of the regulator.

*automatically switch between the regulator and the battery, for instance with a swiitch (which might double as a on-off switch).

A: I have a little thought how to do it: -

simulate this circuit – Schematic created using CircuitLab
Hope I got this right! When 5V is applied M2 gate is biased on and M1 switches fully on - it wouldn't switch on at all if it were not for the internal diode shown above M1. Choose a low \$V_{GS(threshold)}\$ P channel FET for M1.
When the 5V is removed and 3 applied to the output, there could be enough leakage back thru U1 to start to turn M2 on but I've loaded that side with 100 ohms and quite frankly this could by 1kohm (hard to predict without testing).
If I've made a stupid error please do say but I reckon it should work BUT this sort of circuit is prone to oddities like the input capacitor on U1 (not shown) maybe retaining a bit of charge (hence the 100 ohms for R2). Worth a try possibly.


text:
Q: SQL SELECT with join to exclude items that are already answered by the user So I'm trying to make some kind of webapp quiz.
People will be able to submit their own questions to a database and will be able to take a quiz of 10 random true/false questions.
I want to write an sql select to get questions that are :
1- not uploaded by the logged in user
2- not yet answered by the logged in user
At the moment I have this: ($userid = logged in user id)
        public function selectNewRandom($userid){

    $sql = "SELECT `questions`.`id`, `questions`.`quest`, `questions`.`answ`, `questions`.`uploader_id`,`answers`.`item_id`, `answers`.`user_id` FROM `questions` LEFT JOIN `answers` ON `questions`.`id` = `answers`.`question_id` WHERE `questions`.`uploader_id` != $userid AND (`answers`.`user_id` IS null OR `answers`.`user_id` != $userid) ORDER BY RAND()";
    $stmt = $this->pdo->prepare($sql);
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

To get 1 new question that doesn't break the above rules.
My database layout is:
QUESTIONS
-id
-quest
-answ
-uploader_id
ANSWERS
-id
-question_id
-user_id
-answered  (1/0 true false)
This works fine for the first user, he is only getting unique and unanswered questions.. But as soon as a second one logs I think what the command is doing is:
he finds the question_id in the answers table, sees a user_id that is different and stops checking and just allows that question to be returned, even when he also answered the question but the sql never checks. ? so is there maybe a way to check if there is not 1 entry in the answers table that has both the question_id that equals the question id and user_id that equals the $userid (=$_SESSION['user']['id'])
Is there any way to fix this, write another SELECT query or to do it a different way, php maybe?.. (returning an array of 10 questions is also ok..)
[SUMMARY]
It has te check every item with the questions id in the answers table and if one of them has a user_id equal to the logged in user, exclude that item from the result. it works fine if the answered table is empty, showing no more new questions in the end...But if you then log in with another user, no questions that are answered are excluded.

A: You need to compare the answer's userid in the ON clause.
SELECT q.`id`, q.`quest`, q.`answ`, q.`uploader_id`, a.`item_id`, a.`user_id`
FROM `questions` q
LEFT JOIN `answers` a
  ON q.`id` = a.`question_id` AND a.`user_id` = $userid
WHERE q.`uploader_id` != $userid AND a.`user_id` IS NULL
ORDER BY RAND()

You could also write this with EXISTS, but I prefer to use JOIN myself.
Basically, what this says is, "Give me all the questions left joined with answers from our user (ignoring answers from anyone else). Then throw away questions uploaded by our user, and throw away questions that have an answer."
That leaves you with what you want -- questions not uploaded or answered by your user.

A: there  might be  issue  with  creating join using PHP's PDO library, i suggest write simple join query and executed it via my_sqli library. Sometimes binding of parameters arise  such issues.


text:
Q: Why does my 12.04 Alternate CD boot to a blank screen with flashing cursor?
Possible Duplicate:
My computer boots to a black screen, what options do I have to fix it?

I cannot install Ubuntu 12.04.

*

*I burned ubuntu-12.04-alternate-i386.iso to a cd

*Put the burned cd in my computer and reboot, from the CD

*The screen is black,a  cursor flashing at the upper left corner

Did I do something wrong, or can the ISO file be the problem?
How to install Ubuntu alternate version through a CD?

A: I lost 3 days on this. After going down several dead-ends, I discovered the grub options "nomodeset" and "xforcevesa". Google "ubuntu blank screen nomodeset" and you'll find several discussions of the issue. My favorite comes from Ubuntu Forums and is a description of several grub settings that may come into play in this situation. You can find it here.
if you are getting the dreaded "Black Screen Of Boot Death" (actually, that's an overstatement - the system is not actually dead) it may be your video card has not been set up correctly during the boot process. Check out that link I mentioned above and see if it helps you as it did me.
AMD Athlon(tm) II X2 250 Processor × 2, GeForce GT 240, Ubuntu 11.10 32-bit, ASUS M4A87TD/USB3 ATX Mobo

A: I would re download the iso file as it might not have downloaded right. Second, see if your cd drive is not working.

A: I have similar difficulties, and have found no solution yet.  I even hear the Ubuntu tone as if the machine has reached a logon screen, but all I see is the blinking cursor.
It appears that the 12.04 LTS livecd doesn't do well with some graphics cards or certain chipsets, because it relies upon a preset environment (I have a recent nVidia card).  I've been digging and found that in some cases, there have been two solutions that have worked, though neither has for me.  Here's the instruction, apparently issued once the system has booted:
First option -
Ctrl - Alt - F1
   sudo service lightdm restart
Second option -
F6
   nomodeset (this often seems to be discussed as some sort of menu option)
     (There's also mention of Esc followed by adding "vga = normal" before a hyphen)
There's bound to be a single solution, but it's difficult to filter them out because there are so many incidents where 12.04 seems to have black screen issues.
IMPORTANT EDIT - apparently there was a marketing decision made sometime back in the Ubuntu boot process.  During startup, do you happen to notice something that looks like a sideways apartment building with an arrow pointing to a stick version of Michelangelo's Vitruvian Man?  That apparently is supposed to mean "hit a key to stop automatic boot".  If you do so, you can enter the old-style non-X environment, which is where the F6 option can be used.

A: I experiment with newer and older computers. In my AMD machine I installed the 32 bit version of Precise using WUBI in Windows. After the install I was able to boot up but I can not see the grub boot screen so I hit enter and Ubuntu loaded up. Then a message appeared the first time I ran it "you need to install your NVIDIA drivers".
-if you can boot up into ubuntu then try this.

*

*Open a terminal.

*sudo apt-add-repository ppa:ubuntu-x-swat/x-updates

*sudo apt-get update

*sudo apt-get install nvidia-current
To check press Window/superkey, type nvidia x server settings, and open it.
I have had little success so far with the 64bit version.
I hope the above works for you.


text:
Q: (Chrome on) Windows 8 complains certificate not yet valid Chrome on Windows 8 complains that a server certificate is not yet valid. Chrome on Linux does not complain though, and Firefox on the same Windows 8 machine does not complain either.
The certificate is a webserver certificate I made myself, and was signed by my own (self-signed) CA. I imported the CA certificate correctly in both Chrome on Windows (which uses the Windows internal certificate store) and Chrome on Linux and Firefox on Windows (which has its own certificate store).
In Firefox on Windows and Chrome on Linux I can check the certificate for the browser and it correctly lists all the details from the certificate.
Even in Chrome on windows, Chrome lists on the certificate warning page the correct system time. If I then check the certificate (after ignoring the certificate message and continuing anyway) it lists the correct validity period as well (2 days ago until a year-2 days from now).
So I am pretty much flabbergasted. The certificate seems to be valid checking everything in it, but still Chrome does not accept it.
Does anyone have any suggestions as to what to do next for finding and fixing the issue?


text:
Q: JMeter -XPath2 Extractor not working as XPath I tried to use JMeter recommendation to move to XPath2 over XPath Extractor

Since JMeter 5.0, you should use XPath2 Extractor as it provides better and easier namespace management, better performances and support for XPath 2.0

But for simple query I get no results, for output
<Object classId="QueryResultRow"><Property i:type="fn40:SingletonId" propertyId="Id"><Value>{abc-def}</Value></Property><Property i:type="fn40:SingletonString" propertyId="DCN"><Value>D112345</Value></Property></Object>

I use query /Object/Property/Value or //Object//Property//Value and it works only in XPath and not XPath2
Results:
Value={abc-def}
Value_1={abc-def}
Value_2=D112345
Value_matchNr=2

Same results with /*[local-name()='Object']/*[local-name()='Property']/*[local-name()='Value'] as @EdBangga suggested
Is there an issue with XPath2 Extractor or major change of syntax?

A: Your issue is due to namespaces in your XML (i)
Once you show the full XML with namespaces I can give more information but to summarize:

*

*you'll need to configure alias i to match the full namespace (you can use XPath2 Tester and Show Namespaces aliases)

*then it should work


text:
Q: PHP: Where is this variance in json encoding coming from? I have two arrays, that before I json_encode, look EXACTLY the same to me in terms of formatting, but once I json_encode to send back to my ajax call, there is a variance in the two and I can't figure out where this is coming from.
Array 1:
Array
(
    [0] => Array
        (
            [0] => Blue
            [1] => A
            [2] => Bob
            [3] => active
            [4] => Yes
            [5] => 0.0079
            [6] => 0.0100
        )

    [4] => Array
        (
            [0] => Red
            [1] => A
            [2] => Dan
            [3] => unconfirmed
            [4] => Unknown
            [5] =>
            [6] =>
        )

    [54] => Array
        (
            [0] => Green
            [1] => C
            [2] => Matt
            [3] => active
            [4] => Yes
            [5] =>
            [6] =>
        )

)

and after json_encode($string);:
[["Blue","A","Bob","active","Yes","0.0079","0.0100"],["Red","A","Dan","active","Yes",null,null],["Green","C","Matt","unconfirmed","Yes",null,null]]]

Valid JSON
Array 2:
Array
(
    [0] => Array
        (
            [0] => White
            [1] => A
            [2] => Ann
            [3] => active
            [4] => Yes
            [5] => 0.0079
            [6] => 0.0100
        )

    [12] => Array
        (
            [0] => Black
            [1] => C
            [2] => Mary
            [3] => active
            [4] => Yes
            [5] => 0.0104
            [6] => 0.0262
        )

    [35] => Array
        (
            [0] => Yellow
            [1] => C
            [2] => Alice
            [3] => active
            [4] => Yes
            [5] => 0.0330
            [6] => 0.0520
        )
)

and after json_encode($secondString);
{"0":["White","A","Ann","active","Yes","0.0079","0.0100"],"12":["Black","C","Mary","active","Yes","0.0104","0.0262"],"35":["Yellow","C","Alice","active","Yes","0.0330","0.0520"]]}

Invalid JSON
the second array is generated by this line of code:
$secondString = array_filter($string, function($value) { return $value[5] !== null; });

where in I create a new array by outputting anything from the first array where its 5th value is not blank.  The thing is - sometimes the second array looks exactly the same as the first, after performing this filter, while other times it causes this bad array.
Question
Why is this second string different from the first, and what are some things that could be causing this? I can't see any physical difference in the format of the two arrays, so I'm not sure what's causing this, and it's obviously not json (I assume) since my ajax call doesn't return it in its success function.

A: The first string is the value returned by json_encode(array_values($array)), the second one is returned by json_encode($array).
array_values() returns an array that have numeric sequential keys starting with 0. json_encode() produces a representation of a Javascript array from it.
The keys of your array are not sequential. They are 0, 4 and 54. json_encode() cannot produce a Javascript array from them. It produces a Javascript object in order to preserve the keys.
For the first array there is no need to store the keys in the JSON representation. Being numeric sequential starting with 0 they are, in fact, the default keys an array will have in both PHP and Javascript when elements are added to the array without specifying the keys where they should be stored.
An example:
// Encode an array having sequential keys starting from 0
$array = array('zero', 1, 'two');
echo(json_encode($array)."\n");
// produces: ["zero",1,"two"] - Javascript array

// Break the sequence
unset($array[1]);
// the keys are now: 0, 2
echo(json_encode($array)."\n");
// produces: {"0":"zero","2":"two"} - Javascript object

// fix the keys sequence
$array = array_values($array);
// the keys are now: 0, 1
echo(json_encode($array)."\n");
// produces: ["zero","two"] - JS array again

// setting a value at any key different than "2" (the next number in the sequence) will break it again
$array['foo'] = 'bar';
echo(json_encode($array)."\n");
// produces: {"0":"zero","1":"two","foo":"bar"} - object


text:
Q: Install artifacts from artifactory to local repository I have an artifactory which stores artifacts, this is a given pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.test2.test3</groupId>
    <artifactId>web-gen</artifactId>
    <version>v2.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Test dynamic web layer</name>
</project>

How can I install the given artifact to my local repository?
mvn install, mvn install:file and others can't help. Pretty frustrated about it...

A: The simplest solution would be to use it as a dependency which will automatically download the artifact and put it into your local repository.
Otherwise you can use the maven-dependency-plugin by using the get goal:
mvn dependency:get -DartifactId=WhatEver -DgroupId=XX -Dversion=xxx -Dclassfier=..


text:
Q: Default value for  tags I've got a select with two 'special' options, a bit like this:
<select>
 <option value="????">Choose one:</option>
 <option value="1">option1</option>
 <option value="2">option2</option>
   ....
 <option value="????">Free input</option>
</select>

When the user selects nothing, I should ignore the input. When the user selects 'free input', the value from a corresponding textbox is used.
I was wondering, which values would you give those options? I figured I should be able to use no value for the first, because that's what it is: no value. But the last option, should I use -1, 0, or something different?

A: I would use something that will be understandable to the next developer who will be reading the code. Therefore something like 'freeInput' or 'textFieldLookupValue' could be appropriate

A: If the rest of your options has numeric values, choose non-numeric values with "speaking values" for the special options.
This way the server logic can decide with a simple IsNumeric() call what to do, and you are free to add other special options later on.

A: Why not use "free" and "none". You are not restricted to integer values, so using descriptive values would improve comprehensibility.

A: How are you processing your data?
In C#, I will define a constant to represent the ID, and use this to identify it.
public string CONSTANT_OPTION_FreeInput = "-1";

// Test for value in a different method:
if (selectedValue == CONSTANT_OPTION_FreeInput) {
  // Do Stuff
}

You can do something similar in other languages as well.
Whatever value you use, just make sure that it will be easily understood by yourself and any other developer looking at the code in the future.

A: On the first one, you really don't even need the value attribute present. It'll come up as not being set on the server side regardless.
With regards to the free input choice, I'd go simply with free_input.
Of course, it's all up to you. Just choose something that is meaningful and relates to its purpose. ;-)

A: Make the first option an option group instead and then use no value for your "Free input". An option group is not selectable.


text:
Q: Calling third party middlewares inside a custom middleware in NodeJS Express I'm learning NodesJS Express. I am using Express-Validator for my testing purposes.
Here is my testing program.
const express = require("express");
const app = express();
const port = 5000;
let bodyParser = require("body-parser");

const { body, validationResult } = require("express-validator");

app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post(
  "/user",
  body("username").isEmail(),
  body("password").isLength({ min: 5 }),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    console.log("Login successfully!");
    res.send(200);
  }
);

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

When I tried to use a post request with the body parameter: { username:test@, password:12345a }, it worked as my expectation. The server will response like this:

The problem happened when I tried to wrap all the logic in the post request handler into a single middleware. When I sent the same post request, it didn't show the error like the example above. That means the two express-validator donot work. Here is my new program.
const express = require("express");
const app = express();
const port = 5000;
let bodyParser = require("body-parser");

const { body, validationResult } = require("express-validator");

app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const validateEmailAndPwdlength = (req, res, next) => {
  body("username").isEmail(); // the express-validator middleware doesn't work here.
  body("password").isLength({ min: 5 });  // the express-validator middleware doesn't work here.
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  console.log("Login successfully!");
  res.sendStatus(200);
};

app.post(
  "/user",
  validateEmailAndPwdlength
);

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

The two express-validator body("username").isEmail() and body("password").isLength({ min: 5 }) are the validation chains. From Express-Validator document, it says that 'The validation chain is a middleware, and it should be passed to an Express route handler'. Why should we place them a Express route handler? If not, how can we call them inside my second example?
Thank you so much for your time!

A: body("username").isEmail() evaluates to a function, and if you simply put it as a statement in your validateEmailAndPwdlength, it has no effect at all. You could invoke the function yourself, as in (simplified)
const validateEmailAndPwdlength = (req, res, next) => {
  body("username").isEmail()(req, res, function() {
    body("password").isLength({min: 5})(req, res, function() {
      const errors = validationResult(req);
      ...
    });
  });
}

but that is much longer and less readable (even in this simplified version) than your first version where you follow the express-validator's advice. It's so much more elegant, what don't you like about it?
Addendum: You can see in the Node.js console that the validation chains are actually functions:
> body("username").isEmail().toString()
'async (req, _res, next) => {\n' +
  '        try {\n' +
  '            await runner.run(req);\n' +
  '            next();\n' +
  '        }\n' +
  '        catch (e) {\n' +
  '            next(e);\n' +
  '        }\n' +
  '    }'


text:
Q: How to write an intersects for Shapes in android I have an written an Object called Shape which has a Point representing the topLeftCorner and a Dimension with represents its width and height.
To get the topRightCorner I can simply add the width to the topLeftPoint.x. I use to rotate them on a certain degree around their center. The problem after the rotation is, that my intersects(Shape) method fails, because it does not honor the rotation of the Shapes. The rotation will be the same for each Shape. My current implementation looks like this inside my Shape Object:
public boolean intersects(Shape s){
    // functions returning a Point of shape s
    return intersects(s.topLeft())
        || intersects(s.topRight())
        || intersects(s.bottomLeft())
        || intersects(s.bottomRight())
        || intersects(s.leftCenter())
        || intersects(s.rightCenter())
        || intersects(s.center());
}

public boolean intersects(Point p){
    return p.x >= leftX()
        && p.x <= rightX()
        && p.y >= topY()
        && p.y <= bottomY();
}

Basically I need functions like rotatedLeftX() or rotatedTopRight() to work properly. Also for that calculation I think it doesn't matter when the topLeft point before a rotation of ie 90 will turn into topRight...
I already read this and this Question here, but do not understand it fully.

A: I modified an algorithm from Stackoverflow to do what you are indicating with rectangles for a battleship game I wrote.  Here is the code:
    private boolean overlaid(int [][][] shps, int curr)
    {
        for (int i = curr-1; i>=0; --i)
        {
//              From: http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other/306332#306332
//              if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
//                      RectA.Y1 < RectB.Y2 && RectA.Y2 > RectB.Y1)

            if (shps[curr][0][1] <= shps[i][1][1] &&
                shps[curr][1][1] >= shps[i][0][1] &&
                shps[curr][0][0] <= shps[i][1][0] &&
                shps[curr][1][0] >= shps[i][0][0])
                return true;
        }

        return false;
    }

 private int [][][]   shps = {  {{-1,-1},{-1,-1}},
                                 {{-1,-1},{-1,-1}},
                                 {{-1,-1},{-1,-1}}  };

The shps parameter is just a matrix indicating the location of the top-left and bottom-right corners of each rectangle using {x0,y0}, {x1,y1}.  For example, shps[curr][0][1] == the current shp's y0.  For my purposes, I had to use <= and >=.  Also, you have to be mindful of the reverse of y if you are using screen coordinates versus Cartesian coordinates.  Also DeMorgan's Law if you want to use NOT overlaid.

A: I have a solution:
lets assume I want to calculate the rotation (90 degrees) of a Shape with x =1, y=1 (topLeft Point) and a width of 4 and a height of 6 around its center (3, 4) ==  (x1, y2)
rotatedX = x1 + cos(q) * (x - x1) - sin(q) * (y - y1)
rotatedY = y1 + sin(q) * (x - x1) + cos(q) * (y - y1)

in this case:
rotatedX = 3 + cos(90) * (1 - 3) - sin(90) * (1 - 4)
rotatedY = 4 + sin(90) * (1 - 3) + cos(90) * (1 - 4)

this is for a rotation in a cartesian-plane (where positive rotation values means rotation counter-clockwise)
So if you wanna aply a rotation of 90 degrees CLOCKWISE you just have to multiply rotation with -1;