text:
Q: Format a nested set model result into PHP array Looking to create a function which arrangesmy nested set model into an array based on levels (categories[0], sub_categories[1], types[2]).
categories[0]
Alcohol |
        |     sub_categories[1]
        |—————Beer
        |
        |—————Spirts
        |
        |—————Cider
        |
        |—————Wine
        |     |
        |     |     types[2]
        |     |—————White wine
        |     |
        |     |—————Red wine
        |
Bvrages |
        |      sub_categories[1]
        |————— Soft Drinks

I was having a look at an older post and it got me close but only transferred the title and not the whole array How do I format Nested Set Model data into an array?.
What i want to achieve is a similar structure like above. Just remember i want to move all data not just the title.
My current output from my query is as follows:
    Array
(
    [0] => Array
        (
            [id] => 1
            [title] => alcohol
            [level] => 0
            [uri] => alcohol
            [count] => 100
        )

    [1] => Array
        (
            [id] => 2
            [title] => beer
            [level] => 1
            [uri] => beer
            [count] => 50
        )

    [2] => Array
        (
            [id] => 3
            [title] => cider
            [level] => 1
            [uri] => cider
            [count] => 20
        )

    [3] => Array
        (
            [id] => 4
            [title] => wine
            [level] => 1
            [uri] => wine
            [count] => 20
        )

    [4] => Array
        (
            [id] => 6
            [title] => white wine
            [level] => 2
            [uri] => white-wine
            [count] => 5
        )

    [5] => Array
        (
            [id] => 7
            [title] => red wine
            [level] => 2
            [uri] => red-wine
            [count] => 15
        )

    [6] => Array
        (
            [id] => 8
            [title] => spirits
            [level] => 1
            [uri] => spirits
            [count] => 5
        )

    [7] => Array
        (
            [id] => 9
            [title] => Beverages
            [level] => 0
            [uri] => beverages
            [count] => 50
        )

    [8] => Array
        (
            [id] => 10
            [title] => soft drinks
            [level] => 1
            [uri] => soft-drink
            [count] => 10
        )

)

Any thoughts?

A: If I understood you right, then try this solution:
 <?php
 $data=Array(
    0 => Array(
            'id' => 1,
            'title' => 'alcohol',
            'level' => 0,
            'uri' => 'alcohol',
            'count' => 100,
        ),
    1 => Array(
            'id' => 2,
            'title' => 'beer',
            'level' => 1,
            'uri' => 'beer',
            'count' => 50,
        ),
    2 => Array(
            'id' => 3,
            'title' => 'cider',
            'level' => 1,
            'uri' => 'cider',
            'count' => 20,
        ),
    3 => Array(
            'id' => 4,
            'title' => 'wine,',
            'level' => 1,
            'uri' => 'wine',
            'count' => 20,
        ),
    4 => Array(
            'id' => 6,
            'title' => 'white wine',
            'level' => 2,
            'uri' => 'white-wine',
            'count' => 5,
        ),
    5 => Array(
            'id' => 7,
            'title' => 'red wine',
            'level' => 2,
            'uri' => 'red-wine',
            'count' => 15,
        ),
    6 => Array(
            'id' => 8,
            'title' => 'spirits',
            'level' => 1,
            'uri' => 'spirits',
            'count' => 5,
        ),
    7 => Array(
            'id' => 9,
            'title' => 'Beverages',
            'level' => 0,
            'uri' => 'beverages',
            'count' => 50,
        ),

    8 => Array(
            'id' => 10,
            'title' => 'soft drinks',
            'level' => 1,
            'uri' => 'soft-drink',
            'count' => 10,
        )
);

$cats=array();
$prev_level=1;
$index0='';
$index1=0;
foreach($data as $dat){
    switch($dat['level']){
        case 0:
            $cats[$dat['uri']]=array(
                'name'=>$dat['title'],
                'sub_categories'=>array()
            );
            $index0=$dat['uri'];
            break;
        case 1:
            if($prev_level<1)
                $index1=0;
            else
                $index1++;
            $cats[$index0]['sub_categories'][$index1]=array(
                'name'=>$dat['title']
            );
            break;
        case 2:
            if($prev_level<2){
                $cats[$index0]['sub_categories'][$index1]['types']=array();
            }
            $cats[$index0]['sub_categories'][$index1]['types'][]=$dat['title'];
            break;
    }
    $prev_level=$dat['level'];
}

print_r($cats);
?>

A: Try to use this code:
<?php
//Represent your array like this (you may include other data to the each item)
//array must be ordered by 'left' field:

$data = array(
 array("left" => 1, "right" => 10, "name" => "P0"),
 array("left" => 2, "right" => 7, "name" => "P1"),
 array("left" => 3, "right" => 4, "name" => "P11"),
 array("left" => 5, "right" => 6, "name" => "P12"),
 array("left" => 8, "right" => 9, "name" => "P2")
);

//Converter function gets nested sets array and returns nested php array
function nest($arrData){
 $stack = array();
 $arraySet = array();
 foreach( $arrData as $intKey=>$arrValues) {
  $stackSize = count($stack);
  while($stackSize > 0 && $stack[$stackSize-1]['right'] < $arrValues['left']) {
   array_pop($stack);
   $stackSize--;
  }

  $link =& $arraySet;
  for($i=0;$i<$stackSize;$i++) {
   $link =& $link[$stack[$i]['id']]["children"]; //navigate to the proper children array
  }

  $tmp = array_push($link,  array ('item'=>$arrValues,'children'=>array()));
  array_push($stack, array('id' => $tmp-1, 'right' => $arrValues['right']));
 }

 return $arraySet;
}

//Print result
printArray(nest($data));

function printArray($array){
 echo "
";
 foreach ($array as $row){
  $children = $row['children'];
  echo "
";
  echo $row['item']['name'];
  if (!empty($children)) printArray($children);
  echo "
";
 }
 echo "
";
}
?>


text:
Q: How to Model a Lookup Table with Composite Key using JPA I have the following situation with a composite key in a lookup table:
LU_MASTER_TABLE
 - [PK1] TYPE = type of value being looked up
 - [PK2] ID = id of the value to lookup applying to that table
 - DESC = the description of the id.
TABLE2>
 - TYPE_A_ID
 - TYPE_B_ID
What is the best way to create a one to one relationship using Spring JPA?

A: So far, below is the best I can come up with.  Though it does not use the composite key so while it works, it doesn't really represent the DB structure.
 @Entity
 @Table(name= "LU_MASTER_TABLE")
 public class LuMasterTable {

   @Id
   @Column(name = "ID")
   protected String id;

   // Note I did not make typeField a PK even though it is in DB.
   // Ideally it would be part of composite key,
   // though I wasn't able to get composite key to work given
   // the scenario here where upon joining with another table,
   // it must be a type of "constant".  See where clause in other
   // table below to see what I mean.
   @Column(name = "TYPE")
   protected String typeField;

 }

table2
@Entity
@Table(name = "TABLE2")
public class Table2{

 ...

  @OneToOne
  @JoinColumn(name="TYPE_A_ID")
  @Where(clause = "typeField = TYPE_A")
  protected LuMasterTable typeALuMasterTable;

  @OneToOne
  @JoinColumn(name="TYPE_B_ID")
  @Where(clause = "typeField = TYPE_B")
  protected LuMasterTable typeBLuMasterTable;

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add unspecified options to cli command using python-click I would like to add unspecified options to the cli command using python-click library. So my cli function could look like the following
$ my-cmd --option1 value1 --options2 value2 --unknown_var value3

My current code:
import click

@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2):
  click.echo("my test")

I would like to see something like the following:
import click

@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2, **kwargs):
  click.echo("my test")
  # Manually manage **kwargs

A: You can pass context with ignore_unknown_options and allow_extra_args settings, the extra arguments will be collected in context.args list (['--unknown_var', 'value3', '--unknown_var2', 'value4']). Then you can transform it to dict.
import click

@click.command(name='my-cmd', context_settings=dict(
    ignore_unknown_options=True,
    allow_extra_args=True,
))
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def cli(ctx, option1, option2):
    click.echo({ctx.args[i][2:]: ctx.args[i+1] for i in range(0, len(ctx.args), 2)})

example
python cli.py --option1 value1 --option2 value2 --unknown_var value3 --unknown_var2 value4
>> {'unknown_var2': 'value4', 'unknown_var': 'value3'}

See Forwarding Unknown Options.


text:
Q: How would you get turtle to overlap certain areas of squares? So I had to get familiar with turtle for a project with school. I got basically everything my professor asked besides for overlapping the squares.
However he would like the squares to overlap like this

I haven't been able to replicate this at all. I am wondering if their is something I need to throw into my code to easily solve it.
Here is my code
import turtle #Imports the 'turtle module' which allows intricate shapes and pictures to be drawn
my_turtle_pos = (10 , 10)
def square(my_turtle,x,y,length) : #I set up a function that helps me determine the square

    my_turtle.penup() #Picks 'up' the turtle pen
    my_turtle.setposition(x-length/2,y-length/2) #Helps set positon
    my_turtle.pendown() #Puts 'down' the turtle pen
    my_turtle.color('black','red') #Allows black outline, with red filling
    my_turtle.begin_fill() #Starts the filling of red and helps remember the starting point for a filled area
    my_turtle.forward(length) #Moves the turtle by the specified amount 'length'
    my_turtle.left(90) #Moves the turtle by given amount '90'
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.end_fill() #Stops filling with red, which will close with the current color

def graphic_pattern(my_turtle,x,y,length,times): #recursive function
    if times <= 0:  #This just tells us how many 'times' it needs to repeat till given amount
        return
    newSize = length/2.2 #This will grab the new size
    graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1) #Functions to help with writing 'smaller' squares
    graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
    graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)
    graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
    square(my_turtle,x,y,length)

my_turtle = turtle.Turtle(shape="arrow") #You can use differen't shapes for the turtle, I chose arrow, though the turtle was cool :)
my_turtle.speed(100) #I am not sure how fast the turtle can go, I just chose 100 cause it went by quicker.

graphic_pattern(my_turtle,3,0,300,4) #Example pattern stated from homework assignment.

I think it's something to do with where the pen draws the squares first. Thanks for any input!

A: Sounds like it's a simple sequencing of your graphic_pattern() and square() methods. It seems you would want to draw the top right graphic_pattern() first, followed by the middle square, and then followed by the rest of the graphic_pattern() calls:
import turtle #Imports the 'turtle module' which allows intricate shapes and pictures to be drawn
my_turtle_pos = (10 , 10)
def square(my_turtle,x,y,length) : #I set up a function that helps me determine the square

    my_turtle.penup() #Picks 'up' the turtle pen
    my_turtle.setposition(x-length/2,y-length/2) #Helps set positon
    my_turtle.pendown() #Puts 'down' the turtle pen
    my_turtle.color('black','red') #Allows black outline, with red filling
    my_turtle.begin_fill() #Starts the filling of red and helps remember the starting point for a filled area
    my_turtle.forward(length) #Moves the turtle by the specified amount 'length'
    my_turtle.left(90) #Moves the turtle by given amount '90'
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.forward(length)
    my_turtle.left(90)
    my_turtle.end_fill() #Stops filling with red, which will close with the current color

def graphic_pattern(my_turtle,x,y,length,times): #recursive function
    if times <= 0:  #This just tells us how many 'times' it needs to repeat till given amount
        return
    newSize = length/2.2 #This will grab the new size

    graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
    square(my_turtle,x,y,length)
    graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1)
    graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
    graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)

my_turtle = turtle.Turtle(shape="arrow") #You can use differen't shapes for the turtle, I chose arrow, though the turtle was cool :)
my_turtle.speed(100) #I am not sure how fast the turtle can go, I just chose 100 cause it went by quicker.

graphic_pattern(my_turtle,3,0,300,4) #Example pattern stated from homework assignment.

A: You have to change the visit order of your recursive calls.
Now the order is post-order (visit all children, then visit the node).
With this particular order (visit upper right child, visit the node, visit the remaining children):
def graphic_pattern(my_turtle,x,y,length,times): #recursive function
    if times <= 0:  #This just tells us how many 'times' it needs to repeat till given amount
        return
    newSize = length/2.2 #This will grab the new size
    graphic_pattern(my_turtle,x+length/2,y+length/2,newSize,times-1)
    square(my_turtle,x,y,length)
    graphic_pattern(my_turtle,x-length/2,y-length/2,newSize,times-1) #Functions to help with writing 'smaller' squares
    graphic_pattern(my_turtle,x-length/2,y+length/2,newSize,times-1)
    graphic_pattern(my_turtle,x+length/2,y-length/2,newSize,times-1)

you can obtain the desired pattern.


text:
Q: testing objects with instanceof var google = {
    makeBeer : function(arg1,arg2){
         alert([this instanceof google, arg1, arg2]);
    }
}

google.makeBeer('water','soda');

The above does not alert when i check this instanceof google, but the same code works when i do this.
var google = {
    makeBeer : function(arg1,arg2){
         alert([this instanceof Object, arg1, arg2]);
    }
}

google.makeBeer('water','soda');

the reference 'this' is instance of Object, why not the Google Object. How can i ensure that the instance is of that particular object in my case.
Update to the same question:
var newWay = {}
google.makeBeer.call(newWay, 'pepsi', 'coke');

In the above case i am passing the newWay object to my funcion makeBeer, how can i know that its newWay object here.

A: The object referred to by the variable "google" is in fact just a plain object. The identifier "google" is just a variable name. The instanceof operator tells where an object came from, not what variable(s) happen to be referring to it.

A: From MDN entry on instanceof:

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

So unless you create the object with a unique constructor, something like:
var newWay = new Way(); // assuming you have defined an object Way

where newWay instanceof Way === true, you can't use instanceof to tell you anything other than that it is an object.


text:
Q: `__typename` returned by the server isn't match to graphql schema When I build schema using type-graphql and make a server with apollo-server-lambda and deploy it to netlify functions, something wrong happened.
schema generated by type-graphql
# -----------------------------------------------
# !!! THIS FILE WAS GENERATED BY TYPE-GRAPHQL !!!
# !!!   DO NOT MODIFY THIS FILE BY YOURSELF   !!!
# -----------------------------------------------

type Project {
  name: String!
  summary: String!
  titleAndSummary: String!
}

type Query {
  projects: [Project!]!
}

Problem
I think when I query to API
{
  __schema {
    types {
      name
    }
  }
}

API must respond like
{
    "data": {
        "__schema": {
            "types": [
                {
                    "name": "Query"
                },
                {
                    "name": "Project"
                },
                // ...
            ]
        }
    }
}

But I got
{
    "data": {
        "__schema": {
            "types": [
                {
                    "name": "Query"
                },
                {
                    "name": "a"
                },
                // ...
            ]
        }
    }
}

I'm going to use graphql with Elm-Graphql what auto-generate modules using their __typename property. That's why I must fix the above problem.
I try hard to resolve it but even can't find where's the problem. It seems like in type-graphql or apollo-server or even netlify functions (I tried both netlify dev server and real server with actual deployment)
Codes
graphql.ts
import 'reflect-metadata';
import { ApolloServer } from 'apollo-server-lambda';
import { buildSchemaSync } from 'type-graphql';
import { QueryResolver, ProjectResolver } from './resolver';

const schema = buildSchemaSync({
  resolvers: [QueryResolver, ProjectResolver],
});

const server = new ApolloServer({
  schema,
  debug: false,
});

export const handler = server.createHandler();

types.ts
import { ObjectType, Field } from 'type-graphql';

@ObjectType()
export class Query {
  @Field((type) => [Project!]!)
  projects!: Project[];
}

@ObjectType()
export class Project {
  @Field((type) => String!)
  name!: string;

  @Field((type) => String!)
  summary!: string;
}

resolver.ts
import { Resolver, Query, FieldResolver, Root } from 'type-graphql';
import { Project } from './types';
import { projectList } from '../../db/fakeDB';

@Resolver()
export class QueryResolver {
  @Query((returns) => [Project])
  projects() {
    return projectList;
  }
}

@Resolver((of) => Project)
export class ProjectResolver {
  @FieldResolver((returns) => String!)
  titleAndSummary(@Root() project: Project) {
    return project.name + ' ++ ' + project.summary;
  }
}

Trial
add __typename to Objec Type directly like below
 @Resolver((of) => Project)
export class ProjectResolver {
  @FieldResolver((returns) => String!)
  titleAndSummary(@Root() project: Project) {
    return project.name + ' ++ ' + project.summary;
  }

  @FieldResolver((returns) => String!)
  __typename() {
    return 'Project';
  }
}

But It throws an error on the request
◈ Error during invocation:  {
  errorMessage: 'Name "__typename" must not begin with "__", which is reserved by GraphQL introspection.',
  errorType: 'Error',
...

How can I solve it?
Because I'm not good at English, I worry about If there's a wrong thing. please let me know and correct. Thanks.

A: Looks like you have turned on bundle minification, so all the class names are mangled.

A: We see this with SST and TypeGraphQL when run in production. The "__typename" attribute of ObjectType() and InputType() classes are being transformed into two letter codes. See photo.
Michał, can you elaborate on the bundle minification in TypeGraphQL and how it can be configured to maintain the class names of the source code ObjectType() and InputType() declarations?
"@serverless-stack/cli": "0.54.4",
"@serverless-stack/resources": "0.54.4",
"apollo-server-lambda": "^2.21.1",
"type-graphql": "^1.1.1",

const server = new ApolloServer({
  schema: buildSchemaSync({
    resolvers: [getWebPaths],
    scalarsMap: [],
    validate: false,
  }),

  playground: true, //IS_LOCAL,
  introspection: true, // IS_LOCAL,

  context: async ({
    context,
    event,
  }: {
    event: APIGatewayEvent
    context: Context
  }): Promise<LambdaRoot> => {
    context.callbackWaitsForEmptyEventLoop = false

    return {
      event,
      context,
    }
  },
})


text:
Q: jQuery JavaScript Nested Asynchronous Functions callback I'm a little confused how to determine when async function called multiple times from another one is finished a call from the last iteration:
function MainAsyncFunction(callback) {
  for (var i = 0; i < 10; i++) {
    SubAsyncFunction(function(success) {
      if (i >= 10 && success) { // THIS IS WRONG?!
        callback(true); // happens too early
      }
    });
  }
};

function SubAsyncFunction(callback) {
  SubSubAsyncFunction(function() {
        callback(true);
  });
}

What I'm doing is calling the Google Distance Matrix service, which has a limitation of 25 destinations, hence I'm having to split my array of destinations to call this service multiple times but I don't understand when it's finished.
and in the main bit of code I can tell that the second iteration of the loop in the MainAsyncFunction hasn't yet completed when it does a call back.
I think my problem is I haven't got my head around the order of events when dealing with Async functions in JavaScript... please explain how the subject is normally achieved.

A: You could use the jQuery Deferred object, which acts as a token representing the status of an async operation.
The following is a simplified example:
//set up your sub method so that it returns a Deferred object
function doSomethingAsync() {
    var token = $.Deferred();
    myAsyncMethodThatTakesACallback(function() {
        //resolve the token once the async operation is complete
        token.resolve();
    });
    return token.promise();
};

//then keep a record of the tokens from the main function
function doSomethingAfterAllSubTasks() {
    var tokens = [];
    for (var i=0; i < 100; i++) {
        //store all the returned tokens
        tokens.push(doSomethingAsync());
    }

    $.when.apply($,tokens)
        .then(function() {
            //once ALL the sub operations are completed, this callback will be invoked
            alert("all async calls completed");
        });
};

The following is an updated version of the OP's updated code:
function MainAsyncFunction(callback) {
  var subFunctionTokens = [];
  for (var i = 0; i < 10; i++) {
    subFunctionTokens.push(SubAsyncFunction());
  }

  $.when.apply($,subFunctionTokens)
  .then(function() {
    callback(true);
  });
};

function SubAsyncFunction() {
  var token = $.Deferred();
  SubSubAsyncFunction(function() {
        token.resolve();
  });
  return token.promise();
};

A: Perhaps the ajaxStop() event? This is a jQuery event that only fires when all active AJAX requests are completed.

A: The problem is that the value of i is constantly changing in the loop, finally being out of bounds after failing the loop conditional.
The easiest way to fix this is:
for( i=0; i<5; i++) { // or whatever your loop is
    (function(i) {
        // the value of i is now "anchored" in this block.
    })(i);
}


text:
Q: Python inheritance, super call order and AttributeError I am confused about how inherited class attributes are initialized. I get an AttributeError on a child attribute that I thought was well defined.
I noticed that swapping the order of the super call to the parent after the definition does not yield an error but I do not understand why.
I have not been able to reproduce that error without using processes (I can post that test code too but I think this is lengthy enough), it seems then that the order in which the super is called does not matter.
Edit : It is probably because of running a process before counter is even defined that yiels the exception, but the problem does not happen if I use Thread instead of Process.
I might be missing something about how initializers work or doing something wrong.

*

*Why do I get an Attribute error?

*Why swapping the two line solves (or masks) the problem?

*Why does this problem does not happen using threads instead of processes?
I am using the code below.
Thanks for your help.

Here is the code that reproduces the issue. I tried my best to make it stand-alone.
from multiprocessing import Process
from multiprocessing import Queue

class Parent(object):
    def __init__(self):
        self._stuff_queue = Queue()
        self._process = Process(target=self._do_something)
        self._process.start()

    def _do_something(self):
        while True:
            stuff = self._stuff_queue.get()
            if stuff is not None:
                self.something(stuff)
            else:
                break

    def feed(self, stuff):
        self._stuff_queue.put(stuff)

    def something(self):
        raise NotImplementedError("Implement this something !")

class Child(Parent):
    def __init__(self):
        # --- Swapping those two lines avoids getting the AttributeError --- #
        super(Child, self).__init__()  # Same thing using Parent.__init__(self)
        self.counter = 0

    def something(self, stuff):
        self.counter += 1
        print "Got stuff"

c = Child()
c.feed("Hi SO!")
c.feed(None)  # Just to stop

Here is the message I get :
  File "/home/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "test_process.py", line 14, in _do_something
    self.something(stuff)
  File "test_process.py", line 30, in something
    self.counter += 1
AttributeError: 'Child' object has no attribute 'counter'


text:
Q: Checking if elements in array are even and sort them in specific order I've been trying to get my head around this but I can't seem to find a good way to do this, so basically what I'm trying to achieve is sorting array in a way that numbers are sorted for example like this:
Array output (unsorted)
7777777777
7777777777
6666666666
6666666666
2222222222

Array output (sorted)
7777777777
6666666666
2222222222
6666666666
7777777777

I was thinking about making an array NxN and sort it in a way that if there are like 2 array elements of sevens and sixes it will sort them like
7
6
6
7

and all odd numbers like in this exemple 2 it will sort them like
7
6
2
6
7

A: Count the values in the array.
$values = array_count_values($array);

(You can asort($values); or arsort($values); after this if you want larger groups of even values to be sorted toward the inside or outside of the symmetrical part of the result array. Or if you don't care, don't.)
Build arrays of evens and odds based on those counts.
foreach ($values as $value => $count) {
    if ($count % 2) {
        while ($count--) $odds[] = $value;
    } else {
        $count /= 2;  // half the size, so half can go at the beginning and half at the end
        while ($count--) $evens[] = $value;
    }
}

Merge the even and odd arrays together to create the result.
$result = array_merge($evens, $odds, array_reverse($evens));


text:
Q: How does a column of Zeros affect a Matrix? This was a sample test question and was not the answer to the question. I'm just curious about what the column of 0 does.
For reference if needed, the question was "Which of the following is the coefficient matrix for a homogeneous system Ax = 0 with only the trivial solution"
Here's the Matrix:
\begin{bmatrix}1&0&0&0\\0&1&0&0\\0&0&1&0\end{bmatrix}
I personally would assume that there would be only 1 solution as despite there being no pivot in the 4th column, the values in the 4th column are all 0.
(I'm definitely doing this part wrong) Writing this in parametric vector form, I would get
x1 = 0
x2 = 0
x3 = 0
x4 = free
and now I'm kinda lost about what to do..
Taking a guess, would the result be:
\begin{bmatrix}0\\0\\0\\1\end{bmatrix} * x4?
To be honest, I'm not exactly sure how to examine this matrix..
Simply put, how does the 0 column affect this matrix? Is the initial matrix equivalent to a 3x3 identity matrix? How many solutions are there? Infinitely many or just 1?

A: If $A$ has a column of zeros, then there is a solution with a free variable to the homogeneous equation $A \vec x = \vec 0$. To see this, let's take a small case, e.g. $2 \times 2$. If we have
$$\left[\begin{array}{cc} a & 0 \\ b & 0\end{array}\right] \left[\begin{array}{cc} x \\ y\end{array}\right] = \left[\begin{array}{cc} 0 \\ 0\end{array}\right]$$
then this corresponds to a system of equations
$$ax + 0y = 0 \quad \text{ and } \quad bx + 0y = 0$$
Neither equation actually depends on $y$, so this is a free variable; thus, any vector of the form $[0, y]^T$ is a solution.

A: If $A$ is the matrix of your system, then you have three equations in four variables,
$$
x_1=0,\\ \ \\
x_2=0,\\ \ \\
x_3=0.
$$
And $x_4$ does not appear in the equations, so you are free to choose it, and there are infinitely many solutions.
Another possible interpretation, is that the matrix you were given is an augmented matrix $\begin{bmatrix} A& 0\end{bmatrix}.$ In that case, the system would have three variables and the unique solution $x_1=x_2=x_3=0$.


text:
Q: How to compile a GNU Radio application with Microsoft Visual Studio on Windows Hello i'm trying to make a GNU Radio application using GNU Radio API.
My Setup :
Windows 10,
Microsoft Visual Studio 2013,
GNU Radio 3.8.1
I installed GNU Radio 3.8.1 from binaries on windows 10.
As my compiler doesn't find some libraries i add and build them:

*

*boost 1.74

*log4cpp 1.1.3

*mpir 3.0.0

I have a few errors during the compilation of my GNU Radio application.
Most of errors are located in the file : "rpccallbackregister_base.h" which is in GNU radio, but I never modified this file.
169 IntelliSense : missing base member or class name    rpccallbackregister_base.h  80  15
170 IntelliSense : missing base member or class name    rpccallbackregister_base.h  81  15
error C2612: trailing ')' illegal in base/member initializer list   rpcccallbackregister_base.h
error C2612: trailing ')' illegal in base/member initializer list   rpcccallbackregister_base.h
Error   3   error C2059: syntax error : ')' \rpccallbackregister_base.h 80  1
Error   87  error C2059: syntax error : ')' \rpccallbackregister_base.h 80  1

Have you some idea about this problem ?
Is my installation wrong ?
Thanks.


text:
Q: flutter app drawer navigation to new page looking for a better way to do it on how can I navigate from app drawer to next page, I have made a stateful widget in other file and imported in main.dart, instead of
Navigate.pop(context);

what do I use?
i have tried
Navigator.of(context).push(
    MaterialPageRoute<Null>(builder: (BuildContext context) {
        return new HomePage();

it loads page over the previous page and makes things laggy.
below is the code.
  return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(child: Text('some text')),
      drawer: Drawer(
        // Add a ListView to the drawer. This ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
                image: DecorationImage(image: AssetImage("assets/gold.jpg"),fit: BoxFit.cover)
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer // how do i close the drawer after click?
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );

I expect when I click on app drawer link it takes me to a new page and close app drawer itself

A: If you are looking for a way to edit your current pages e.g. tabs and then switching between the views without actually to start a new page route.
What I normally do, is:
enum Section
{
    GUEST,
    HOME,
    PAGE_1,
    PAGE_2
}

Your main build function:
@override
Widget build(BuildContext context)
{
    Widget body;

    /// You can easily control the section for example inside the initState where you check
    /// if the user logged in, or other related logic
    switch (section)
    {
        /// This is for example a login page since the user not logged in
        case Section.GUEST:
            break;

        /// Display the home section, simply by
        case Section.HOME:
            body = HomeSection();
            break;

        case Section.PAGE_1:
            body = Page1Section();
            break;

        case Section.PAGE_2:
            body = Page2Section();
            break;
    }

    return Scaffold(
        body: Container(
            child: body,
        ),
        /// Display the drawer for logged in users only
        drawer: section != Section.GUEST ? Drawer(
            // Your drawer
        ) : null,
    );
}

This is will even save the state across those sections, and you move around fast between them.
Regrading the drawer, you are doing it right. You just do that pop with the navigator on the context. Just make sure you have the right context. (and not an propagated one)
And of course, changing section is simple as:
setState(() => section = Section.HOME);


text:
Q: Two partitions of $\{ 1, 2, 3, 4, 5, 6, 7, 8, 9\}$ I recently stumbled upon the following problem, and I have no idea how to proceed.
Let $S=\{1, 2, 3, 4, 5, 6, 7, 8, 9 \}.$ Let $P_1, P_2$ be partitions of $S$. For $x \in S$, let $\pi_1(x)$ be the number of elements of the set $A \in P_1$ for which $x \in A$, and let $\pi_2(x)$ be the number of elements of the set $B \in P_2$ for which $x \in B$. Show that there exist distinct $x, y \in S$ with $\pi_1(x) = \pi_1(y)$ and $\pi_2(x) = \pi_2(y)$.
I know that some pigeon-hole principle type of argument is involved, I tried to visualize the problem in lots of ways, but I can't seem to find a solution without the number of things to be checked getting extremely large. A hint would be appreciated.

A: There can be at most three different part sizes in a partition of $[9]$. (The smallest partition with $4$ different part sizes would be $1+2+3+4$, with $10$ elements.) Also, it's impossible to have three part sizes with exactly $3$ elements for each part size (as that's only possible for part sizes $1$ and $3$). Thus, there is at least one part size in $P_1$  with at least $4$ elements in parts of that size. By the pigeonhole principle, at least two of these $4$ elements must be in parts with the same size, since there are at most $3$ part sizes in $P_2$.

A: Let $\pi(x) = (\pi_1(x),\pi_2(x))$. We want to show that $\pi$ is not injective.
So assume $\pi$ is injective. Consider the possible distinct values of $\pi_1$, let's call them $V_1 = \pi_1(S)$ and $V_2 = \pi_2(S)$.
$|V_1|$ can be at most $3$, since if there were $4$ or more sizes of partition classes, there would need to be at least $1+2+3+4=10$ elements in $S$. By symmetry also $|V_2| \leq 3$.
Since $\pi_1$ and $\pi_2$ each have at most three distinct values, $\pi$ can have at most $9$ distinct values. For $\pi: S \to V_1 \times V_2$ to be injective, we must have $|V_1| = |V_2| = 3$ and $\pi$ must be bijective. This implies that $|\pi_1^{-1}(v_1)| = |V_2| = 3$ for all $v_1 \in V_1$.
Now since $\pi_1^{-1}(v_1)$ is the disjoint union of sets of size $v_1$, we have that $v_1$ divides $|\pi_1^{-1}(v_1)|$, so $v_1$ can only be $1$ or $3$. Hence we have $V_1 \subseteq \{1, 3\}$ and therefore $3 = |V_1| \leq |\{1, 3\}| = 2$. By contradiction, $\pi$ is not injective.


text:
Q: Usage of Stream more than once I am trying to upload an image file to a repository using HttpPostedFile.InputStream and resize to different thumbnail sizes using the same stream.

*

*Step 1. Using Stream sm = HttpPostedFile.InputStream I am able to
upload the file successfully.

*Step 2. Use the same stream to resize the image to different sizes.
But always I get error saying that stream is being used.

Suppose if I skip step 1 and perform only step 2, I am able to resize the inputstream (images) to different size. Basically it is letting me to use the inputStream only once.
How can I achieve to process both step 1 and 2 sequentially ?
I did try storing the inputStream to a variable and used separate copy for each step but no luck.
Can someone suggest/help me ?
Thank you very much

A: You did set Stream.Position to 0 before reusing it?
By storing in multiple variables you're probably only duplicating the reference to the same object in memory.

A: If you're using this stream to upload several different images to a server, you probably want to open a new stream for each file you're uploading, rather than trying to upload all of them with a single stream.


text:
Q: Put views in an Android layout with automatic line break I want to put fixed-dimension buttons centred in a layout so that they automatically go to the next line when they are too many. But I know that this behaviour doesn't work with LinearLayout.
Do you have an idea on how I can proceed?
Here is the behaviour that I would like:

A: The Flexbox library from Google does exactly this:
Add the dependency to app/build.gradle:
dependencies {
    implementation 'com.google.android:flexbox:2.0.1'
}

Usage of the layout:
<com.google.android.flexbox.FlexboxLayout
    app:flexWrap="wrap">
        <View/>
        <View/>
        <View/>
        <View/>
</com.google.android.flexbox.FlexboxLayout>

A: This is the GridView behavior.

A: I finally proceeded dynamically :
I created a LinearLayout for each line, and calculated the width taken by the rectangles compared to the global layout width to calculate the number of lines needed and to put each rectangle in the good line.


text:
Q: Ballerina: How to connect Oracle database with Ballerina? I am new to Ballerina. How to create a connection to an Oracle database?

A: In ballerina, to connect to a database, we have to create a client (or rather an endpoint) of type jdbc. For example, if we want to connect to a mysql database you can create a jdbc client as below
endpoint jdbc:Client testDB {
   url: "jdbc:mysql://localhost:3306/testdb",
   username: "root",
   password: "root",
   poolOptions: { maximumPoolSize: 5 }
};

In the above example, the url field specify the database connection url. So if the database is oracle, then we can use the oracle based url scheme instead as below.
endpoint jdbc:Client testDB {
   url: "jdbc:oracle:thin:@localhost:1521/testdb",
   username: "test",
   password: "test",
   poolOptions: { maximumPoolSize: 5 }
};

Once you have created a client, then you can use it to do your operations based on the requirement. For example, the below code segment will create a new table in the database connected from the client.
import ballerina/io;
import ballerina/jdbc;

endpoint jdbc:Client testDB {
    url: "jdbc:oracle:thin:@localhost:1521/testdb",
    username: "test",
    password: "test",
    poolOptions: { maximumPoolSize: 5 }
};

function main(string... args) {
    var result = testDB->update("CREATE TABLE customers (customer_id number(10) NOT NULL,
                                customer_name varchar2(50) NOT NULL, city varchar2(50))");

    match result {
        int retInt => io:println("status: " + retInt);
        error e => io:println("failed: " + e.message);
    }
}

You also have to drop the Oracle JDBC driver jar into BALLERINA_HOME/bre/lib to get this working.
For a complete set of operations, you can refer this guide - https://ballerina.io/learn/by-example/jdbc-client.html


text:
Q: How to remove the action attribute in the form_open_multipart() in Codeigniter? Is there a way that I can remove the action attribute in CodeIgniter?
The code would normally be like this:
form_open_multipart('person/add', $attributes);

I was hoping that I could omit the first parameter so that I could not have an action attribute in the mark-up.
Thanks for those who could help.

A: Sure you can but consider:
1) The action attribute has a meaning and a function, don't know why you want it out
2) You can always pass it an empty string :
  <?php echo form_open('');?>

or <?php echo form_open_multiaction('');?>
gives:
  <form action="" method="post">

In case you're really sure about this, just open up the form_helper.php file, located in system/helpers/form_helper.php.
Pick lines 59 - 65 :
$action OR $action = $CI->config->site_url($CI->uri->uri_string());
$form = '<form action="'.$action.'"';
$form .= _attributes_to_string($attributes, TRUE);
$form .= '>';

and change line 60 to
$form = '<form ';

form_open_multiaction() just picks the form_open() and adds the enctype attribute, so you change form_open() and you're set.
It's up to you now, I still fail to see why an empty action won't suffice to your goals.


text:
Q: android why is a sublass slidingDrawer hight behaving bad? Probably simple but i cannot figure this out.
I have a subclass of SlidingDrawer only to handle the hight correctly.
(thanks to @seydhe for the solution)
The problem is that when i open the drawer the hight is not set correctly,
It get set as soon as i lift my finger from the handle-butten.
How can i make the SlidingDrawer set the hight before i start pulling the drawer?
I have tries in various combinations to slidingDrawerRight.requestLayout();
and it works. The problem is where can i call it?
I have tried in various places like
OnClickListener
OnTouchListener
OnDrawerCloseListener
but i cannot get it to work.
Maybe there's a way to fix the xml to do this?
adding tree images and the xml.
As shown in down belove picture nr:1,
 I start to open the drawer
and the size is irregular:
NR1: Image when being opened..

NR2: Image when fully opened as soon as i let go of finger.

nr3 Image when SD background is set to #eeffae and RelativLayout background is @null

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">

    <Gallery xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/examplegallery"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content" />
   <RelativeLayout
        android:id="@+id/InnerRelativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >
    <Button
        android:id="@+id/btn_newpen_drawtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pen"
    />
    <EditText
        android:id="@+id/etx_addtext_drawtext"
        android:layout_width="fill_parent"
        android:layout_toLeftOf="@+id/btn_delete_pen"
        android:layout_toRightOf="@+id/btn_newpen_drawtext"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:text="Enter text here"
    />
        <Button
            android:id="@+id/btn_delete_pen"
            android:layout_toLeftOf="@+id/btn_save_drawtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Del"
        />
        <Button
            android:id="@+id/btn_save_drawtext"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="save"
        />

    </RelativeLayout>

<LinearLayout android:id="@+id/linearLayoutSlidingDrawerRight"
              android:layout_width="150dip"
              android:layout_height="wrap_content"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              >

    <com.bollen.sppik.editimage.WrappingSlidingDrawer android:id="@+id/slidingDrawerRight"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:handle="@+id/slideHandleButtonRight"
        android:content="@+id/contentLayout2"
        android:orientation="horizontal">

        <ImageButton android:id="@+id/slideHandleButtonRight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/icon"
            android:onClick="btnSlidingDrawerHandler">
        </ImageButton>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/contentLayout2"
            android:orientation="vertical"
            android:background="#C0C0C0"
            >

            <ImageButton android:id="@+id/btn_A"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="Button_A"
                android:background="@android:color/transparent"
                android:src="@drawable/right_drawer"
                android:onClick="btnAListener">
            </ImageButton>

            <ImageButton android:id="@+id/btn_B"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_below="@+id/btn_A"
                android:text="Button_B"
                android:background="@android:color/transparent"
                android:src="@drawable/right_drawer"

                android:onClick="btnBListener">
            </ImageButton>

        </RelativeLayout>
    </com.bollen.sppik.editimage.WrappingSlidingDrawer>
</LinearLayout>
</RelativeLayout>

A: answering my own question.
I set the background to transparent like this
android:background="@null"

Looks ok and the odd resizing behavior still happens but it's not visible.


text:
Q: centering jButton horizontally in relation to JTable with GridBagLayout I hava a JTable and I have placed 3 JButtons below it. I've manage to put the left button on the left corner and the right button on the right corner but I can't figure out how to place the middle button in the center. I have tried using .weightx and .anchor without any results.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class AccessView extends JPanel{
  String[] columnNames = {"Date","Time","Type of access"};
  DefaultTableModel tableModel;
  JTable tAccesses;
  JScrollPane scrollPane;
  JButton bAdd, bMod, bDel;

  public AccessView(){
    createGUI();
  }

   public void createGUI(){
    this.setBorder(BorderFactory.createTitledBorder("Accesses"));
    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    bAdd = new JButton("Add");
    bMod = new JButton("Mod");
    bDel = new JButton("Del");

    tableModel = new DefaultTableModel(25,columnNames.length);
    tableModel.setColumnIdentifiers(columnNames);
    tAccesses = new JTable(tableModel);
    scrollPane = new JScrollPane(tAccesses);

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    this.add(scrollPane, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.anchor = GridBagConstraints.LAST_LINE_START;
    this.add(bAdd, c);

    c.gridx = 1;
    c.gridy = 1;
    this.add(bMod, c);

    c.gridx = 2;
    c.gridy = 1;
    c.anchor = GridBagConstraints.LAST_LINE_END;
    this.add(bDel, c);
  }
}

A: As suggested in the comments above, you can use another JPanel for the 3 JButtons.
Using BoxLayout for JPanel which will contain the 3 JButtons and Box.createHorizontalGlue() between each JButton you can get the following output:

In this case:

*

*Create a new JPanel
JPanel buttonsPane;

*Initialize it and set its layout to BoxLayout
buttonsPane = new JPanel();
buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.LINE_AXIS));

*Add the buttons along with Box.createHorizontalGlue() between them:
buttonsPane.add(bAdd);
buttonsPane.add(Box.createHorizontalGlue());
buttonsPane.add(bMod);
buttonsPane.add(Box.createHorizontalGlue());
buttonsPane.add(bDel);

*Add the buttonsPane to your JFrame's SOUTH alignment (or add it along with your current JPanel and edit its constraints (I used the former)):
frame.add(this);
frame.add(buttonsPane, BorderLayout.SOUTH);

Another way you could achieve a similar result (as per @MadProgrammer comment below) would be changing your constraints and adding "empty" components between your JButtons:
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.weightx = 1;
this.add(bAdd, c);

c.gridx = 1;
this.add(new JLabel(""), c); //Empty component just for the extra space

c.gridx = 2;
this.add(bMod, c);

c.gridx = 3;
this.add(new JLabel(""), c); //Empty component just for the extra space

c.gridx = 4;
this.add(bDel, c);

Which produces:

A: There are some ways to do this:

*

*Since you extends JPanel and have GridBagLayout for the whole
panel, you could just add additional row for buttons. It looks like
table layout in Web - and it actually is. There are pro and contras
with table layout. The main disadvantage is it's hard to mantain in a  long-term project. In particular, you can't re-use buttons elsewhere.

*You could create additional panel with buttons, as @Izruo suggested. The key feature is you could easily move this panel from bottom to left of your grid, add to another similar panel/menu etc. The simplest FlowLayout would be enough. After you created a ButtonPanel, you could

*

*add it to your grid. It's slightly better than table-only layout

*create CompositePanel which will contain both GridPanel and ButtonPanel
Studying Oracle tutorial I noticed that the last option is preferable. From my personal experience, it's a best practice


text:
Q: How do I get preg replace to work when the url contains a hashtag I found a function online for turning a url within a string into a clickable link. However, when the url contains a hashtag it doesn't work. eg. http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759
Here's the part of the function concerned:
$ret = preg_replace(
    "#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#",
    "\\1\\2",
    $ret
);

$ret = preg_replace(
    "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#",
    "\\1\\2",
    $ret
);

Any ideas? thanks

A: Try this:
<?php

$text = "This is my link:  http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759";
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","\\0", $text);
echo $text; // output: This is my link:  http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759

?>


text:
Q: How to put a table into a header using exam class I want to put a table into the header. I have copied the table on to every page in the past, but wastes a lot of time. I have tried \lhead \chead \rhead, and various combinations.
I need the college logo on the left on the header and  "Assessment Number"  on the right
Here's my MWE
  % !TeX program = xelatex
% !TeX spellcheck = en_GB
\documentclass[12pt,addpoints]{exam}
\usepackage{graphicx}
\usepackage{color}
\definecolor{Red}{rgb}{0.8,0.0,0.0}

\header{    \includegraphics {nmtafe1.jpg}
} {} { \large  \textbf{\textcolor{Red}{ Assessment Task 1}}}

\usepackage{xcolor}
\usepackage{colortbl}% need to colour table
\usepackage{fontspec}% need for arail from top line
\setmainfont{Arial}% needed for arial from top line
\renewcommand{\arraystretch}{2}
\usepackage{array}% this is need to centre data
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}} % this centres data
\globalcolorstrue
\setlength\arrayrulewidth{1.25pt}% so you can see table boarders at 100%
\usepackage{multicol}

\begin{document}

\begin{table}
    \begin{tabular}{|l|l|}
        \hline
        \cellcolor{blue!20}Qualification national code and title    &  \multicolumn{1}{|p{11cm}|}{\centering ****** Certificate **   in General Education for Adults}  \\
        \hline
        \cellcolor{blue!20}Unit/s national code/s and title     & \multicolumn{1}{|p{10cm}|}{\centering ****** Investigate and Interpret shapes  and \\ measurements and related formula  }\\
        \hline
    \end{tabular}
\end{table}

    \begin {questions}

    \question
    This is question on
\newpage

\question

This is question two

    \end {questions}

\end{document}

A: This code will insert the table in the center of the header, but will lower it using \raisebox,  and add extra space to the header with \extraheadheight[<1st page space>]{<other pages space>}

Using tabularx allowed to expand the table to full text width without guessing.
% !TeX program = xelatex
% !TeX spellcheck = en_GB

\documentclass[12pt,addpoints]{exam}

\usepackage{fontspec}% need for arial from top line
\setmainfont{Arial}% needed for arial from top line
\usepackage{array}% this is need to centre data
\renewcommand{\arraystretch}{2}
\newcolumntype{C}[1]{>{\centering\arraybackslash}X|} % this centres data

\setlength\arrayrulewidth{1.25pt}% so you can see table boarders at 100%

\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{colortbl}% need to colour table
\definecolor{Red}{rgb}{0.8,0.0,0.0}

\usepackage{tabularx}% added <<<<<<<<<<<<<<<

\header{ \includegraphics[scale=0.2] {example-image}}
 {\raisebox{-60pt}{\begin{tabularx}{\linewidth}{|l|C|} % added <<<<<<<<<<<<<<<<<
            \hline
            \cellcolor{blue!20}Qualification national code and title &   ****** Certificate **   in General Education for Adults \\
            \hline
            \cellcolor{blue!20}Unit/s national code/s and title     &  ****** Investigate and Interpret shapes  and  measurements and related formula \\
            \hline
 \end{tabularx}}}
 {\large \textbf{\textcolor{Red}{ Assessment Task 1}}}

 %move headers up or and down
\extraheadheight[120pt]{120pt}% addded <<<<<<<<<<<<<<<<<<

\globalcolorstrue

\usepackage{multicol}

\begin{document}
    \begin {questions}

    \question
    This is question one
    \newpage

    \question

    This is question two

    \end {questions}

\end{document}


text:
Q: Fancy Box not closing I recently started experimenting with fancy box. I am triggering the fancy box when there is a preg match in the url. Everything is running fine except upon clicking OK or CANCEL the
fancy box is not closing.
if(preg_match('/school/',$_SERVER['REQUEST_URI']) )
    {
       ?>

       <?php

    }

Continue or Decline

<input type="button" onclick="php_function();" value="OK" /><input type="button" value="CANCEL" onclick="$.fancybox.close();"

php_function() is a javascript function for ajax call.

A: why not open it whith its method instead trigger('click') ?
$.fancybox.open( [group], [options] )

ref: http://fancyapps.com/fancybox/#docs


text:
Q: Minimum height needed in textarea for draggable resize I have a textarea on my page. It has this draggable corner which lets me resize it. Like in this screencrop below

If I resize it too small, the corner will disappear (even though the corner will still let me resize the textarea).
I want to place the minimum height to whats needed for it to display the draggable corner image so not as to confuse users
What would this minimum-height required be? Do stuff like padding and margin affect it? Is it only in Chrome or is it the same in Safari/IE.. etc?

A: You should be able to define in the element cols and rows. Like  Doing this creates the minimun size. Then you can resize from there. OR in CSS
In CSS you could do min and max sizes. Safe for most modern browsers
  #confinedSpace textarea { resize:vertical; max-height:300px; min-height:200px; }
  #confinedSpace textarea.horiz { resize:horizontal; max-width:400px; min-width:200px; }


text:
Q: How to get data from (bluetooth) serial port into python program? I have managed to receive data from a bluetooth connected device by implementing exactly this solution:
https://scribles.net/setting-up-bluetooth-serial-port-profile-on-raspberry-pi-using-d-bus-api/
This works fine using the minicom, but I need to manipulate the data which arrives in a python program. How on earth do I go about getting the data into a python program instead of receiving it in the minicom???
Also: as I am an absolute beginner with python, bluetooth and github this is the only solution that I was able to get working. I have tried several approaches over the last couple of weeks and I am sure that there are many other which are better and easier and I would appreciate any suggestions of better/easier solutions.
Python 3.7
RPi3 (1.3)
Connection status in bluetoothclt->info:
Device 00:07:80:E0:A4:FC (public)
    Name: WT11i-A
    Alias: WT11i-A
    Class: 0x00001f00
    Paired: yes
    Trusted: yes
    Blocked: no
    Connected: yes
    LegacyPairing: no
    UUID: Serial Port (00001101-0000-1000-8000-00805f9b34fb)
    UUID: PnP Information (00001200-0000-1000-8000-00805f9b34fb)
    Modalias: bluetooth:v0047pF000d0400

sudo rfcomm -a show hci0:
rfcomm0: B8:27:EB:A6:D7:4F -> 00:07:80:E0:A4:FC channel 1 connected [reuse-dlc release-on-hup tty-attached]

A: With the amazing assistance of ukBaz I finally got it working.
The trick is: ditch RFCOMM ... not much of a surprise apparently.
I disconnected the RFCOMM connection and did not connect using the 'Blueman manager'. By instead just running the Bluedot default client script it worked!


text:
Q: Execute line given in output of another command Warning: this question is not about usage of git, but about usage of pipes in Linux, git command is given here as example.
Having such output of git push
fatal: The current branch my_branch has no upstream branch.
To push the current branch and set the remote as upstream, use

   git push --set-upstream origin my_branch

I want to execute given command, i.e. git push --set-upstream origin my_branch.
By doing git push 2>&1 | tail -3 I get git push --set-upstream origin my_branch printed on screen.
Question: What command should be added to next pipe so given git push will be executed. So I could do git push 2>&1 | tail -3 | command_to_eval_given_string

A: Just pipe to bash itself:
git push ... | bash

This will send the stdout from the previous pipes to bash, that will then execute it.
$ echo "echo 'hello'" | bash
hello
$ echo "uptime" | bash
 16:22:37 up  7:31,  3 users,  load average: 0,03, 0,14, 0,23

A: Rather than piping to another command, you can instead wrap the pipeline in a command substitution and eval it. This will execute the command in your current shell session. For example:
eval "$(printf 'some output 1\nsome output 2\necho execute me'| tail -1)";
## execute me


text:
Q: Show there is a path in X $\times$ Y if and only if there is a path in X and a path in Y (a) Let $(x_1,x_2) \in X$ and $(y_1,y_2) \in Y$. Show that there is a path from $(x_1,y_1)$ to $(x_2, y_2)$ if and only if there is a path $x_1$ to $x_2$ in $X$ and a path $y_1$ to $y_2$ in $Y$.
(b) show that $X \times Y$ is path connected if and only if $X$ and $Y$ are both path connected.
Firstly, I'm not sure about the difference between questions and (a) and (b). I would have assumed that proving (a) would also prove (b).
I went about this question as follows:
First I prove that if there is a path $x_1$ to $x_2$ in $X$ and a path $y_1$ to $y_2$ in $Y$ then there is a path $(x_1,y_1)$ to $(x_2, y_2)$ in $X \times Y$.
Suppose $\exists$ a continuous function $g: [0,1] \to X$ and a continuous function $h: [0,1] \to Y$. Then $X$ and $Y$ are path connected. Suppose $x_1$ and $x_2$ $\in U \subset X$ and $y_1$ and $y_2$ $\in V \subset Y$. Then $$(x_1,y_1), (x_2,y_2) \in U \times V \subset X \times Y$$ hence there exists a continuous function $f: [0,1] \to X \times Y$
For proving the converse, could I just say that there exists a projection map $\pi_1(x_1,y_1) = x_1$ and $\pi_1(x_2,y_2) = x_2$ which creates a continuous map from $[0,1] \to X$? And the same for $Y$?

A: Path-connectedness is much more than just saying that there exists a continuous function $g:[0,1]\to X$, especially considering there is always such a map when $X$ is non-empty (namely, take a constant map).  Path-connectedness says that for every two points $x$ and $y$ in $X$, then there exists a continuous map $f:[0,1]\rightarrow X$ such that $f(0)=x$ and $f(1)=y$.
Really the entire question boils down to the fact that $f:Z\to X\times Y$ is continuous if and only if there exists $g:Z\rightarrow X$ and $h:Z\rightarrow Y$ with $g,h$ continuous and $f(z)=(g(z),h(z))$ for all $z\in Z$.  What you say with regards to the projections (which you will recall, are continuous maps) helps to prove this (if you haven't done so already).  Then apply this to paths in $X$, $Y$, and $X\times Y$.
To prove the direction that if $g,h$ are continuous, we can actually start by proving that if we have maps $\varphi: A\rightarrow X$ and $\psi: B\rightarrow Y$, then the map $\varphi\times \psi: A\times B \rightarrow X\times Y$ defined by $\varphi\times \psi: (a,b)\mapsto (\psi(a),\psi(b))$ is continuous; this follows by noting that for $U\subset X$ and $V\subset Y$, then $(\varphi\times\psi)^{-1}[U\times V]=\varphi^{-1}[U]\times \psi^{-1}[V]$. Next, show that the map $\chi: Z\rightarrow Z\times Z$ defined by $\chi(z)=(z,z)$ is continuous (show $\chi^{-1}[U\times V]=U\cap V$).  Then taking $A=Z=B$, we'd see that $f=(\varphi\times \psi)\circ \chi$ is the composition of continuous functions, and hence continuous itself.


text:
Q: Inverting the logarithm rule for quotients In school I have been taught that $\log_a\frac{r}{s} = \log_ar - \log_a{s}$. Furthermore, it has been said that this rule can be inverted (applied from the right to the left). Then, I came across this:

Simplify $\lg(x-y) - \lg(y-x)$.

Note that $\lg(x)$ means $\log_{10}(x)$. Let's consider $x, y \in \mathbb R^+$.
The "simplification" yields $\lg\frac{x-y}{y-x} = \lg(-\frac{y-x}{y-x}) = \lg(-1) \space\space\space ( = \frac{\ln(-1)}{\ln(10)} = \frac{\pi i}{\ln(10)})$.
However, if you look at the task, you would get different results depending on whether $x > y$ or $y > x$. (try it with a calculator or simply google an example...) So, is this rule wrong or do I have to make these "case differentiations" every time I am using this rule?

A: This is one of those cases where there are two seemingly different expressions that express the same value.  $\mathbb e ^ {\mathbb i \pi} = -1$ and $\mathbb e ^ {-\mathbb i \pi} = -1$.  Both are valid solutions to $\lg\frac{x-y}{y-x}$ and which one you arrive at depends on how you break down your expression.


text:
Q: How to count and do jointure like stuff on couchDB I'm currently trying to get the number of events for one organizer.
This is what my organizer document looks like:
{
 "doc_type": "User",
 "email": "xxx@gmail.com",
 "blebleble: "blebleble",
}

This is what my event document looks like:
{
"doc_type": "Event",
 "email": "xxx@gmail.com",
 "blablabla: "blablabla",
}

I still couldn't figure out how to do some kind of jointure between both docs and do a count on the number of event that shares the same. I think I can work around the email that both docs shares but I don't know how I can do that. I'm still having trouble with CouchDB. Doesn't seems like a hard thing to do in SQL, but can't find out for nosql.
Thanks you in advance.

A: "jointure" is not not a term I've encountered in my field so I am left to guess what is meant is join.
Joins are possible with CouchDB views, but what I read from the requirement in the OP is to get counts of events by email. See CouchDB's Joins With Views documentation. For that, I don't see documents with an ancestral relation rather a one-to-many relation, i.e. user ==> events.
Consider this design document:
{
    "_id": "_design/SO-68999682",
    "views": {
      "user_events": {
        "map": `function (doc) {
           if(doc.doc_type === 'Event') {
              emit(doc.email);
           }
        }`,
        "reduce": '_count'
      }
    }

The view's map function simply adds doc.email to the 'user_events' index when appropriate.  Of particular interest the reduce function specifies the built-in reduce function _count.
Given such a view index one may apply the /db/_design/design-doc/_view/view-name endpoint to, for example,
View all events
{
   reduce: false,
   include_docs: true
}

Get a count of all events
{
   reduce: true
}

Get a count of events for every email (summary)
{
   reduce: true,
   group_level: 1
}

Get a count of events for a specific email
{
   reduce: true,
   group_level: 1,
   key: email
}

Get all events for a specific email
{
   reduce: false,
   include_docs: true,
   key: email
}

The _count reduce built-in provides high performance. The snippet below demonstrates the above using the very handy and compatible PouchDB.

async function showAllEventDocs() {
  let result = await db.query('SO-68999682/user_events', {
    reduce: false,
    include_docs: true
  });
  //show
  gel('user_events_view').innerText = result.rows.map(row => [row.doc.email, row.doc.date].join('\t\t')).join('\n');
}

async function showEventCountTotal() {
  let result = await db.query('SO-68999682/user_events', {
    reduce: true
  });
  gel('event_count_total').innerText = result.rows[0].value;
}

async function showEventCountSummary() {
  let result = await db.query('SO-68999682/user_events', {
    reduce: true,
    group_level: 1
  });
  //show key/value (email, count)
  gel('event_count_summary').innerText = result.rows.map(row => [row.key, row.value].join('\t\t')).join('\n');
}

async function showUserEventCount(email, displayElement) {
  let result = await db.query('SO-68999682/user_events', {
    reduce: true,
    group_level: 1,
    key: email
  });
  //show value (count)
  gel(displayElement).innerText = result.rows[0].value;
}

async function showUserEvents(email, displayElement) {
  let result = await db.query('SO-68999682/user_events', {
    reduce: false,
    include_docs: true,
    key: email
  });
  //show
  gel(displayElement).innerText = result.rows.map(row => [row.doc.email, row.doc.date].join('\t\t')).join('\n');
}

function getDocsToInstall(count) {
  const docs = [{
      "doc_type": "User",
      "email": "Jerry@gmail.com"
    },
    {
      "doc_type": "User",
      "email": "Bobby@gmail.com"
    },
    {
      "doc_type": "Event",
      "email": "Jerry@gmail.com",
      "date": getDocDate().toISOString().slice(0, 10)
    }, {
      "doc_type": "Event",
      "email": "Jerry@gmail.com",
      "date": getDocDate().toISOString().slice(0, 10)
    }, {
      "doc_type": "Event",
      "email": "Jerry@gmail.com",
      "date": getDocDate().toISOString().slice(0, 10)
    }, {
      "doc_type": "Event",
      "email": "Bobby@gmail.com",
      "date": getDocDate().toISOString().slice(0, 10)
    }, {
      "doc_type": "Event",
      "email": "Bobby@gmail.com",
      "date": getDocDate().toISOString().slice(0, 10)
    },
  ];
  // design document
  const ddoc = {
    "_id": "_design/SO-68999682",
    "views": {
      "user_events": {
        "map": `function (doc) {
           if(doc.doc_type === 'Event') {
              emit(doc.email);
           }
        }`,
        "reduce": '_count'
      }
    }
  };

  docs.push(ddoc);
  return docs;
}

const db = new PouchDB('SO-68999682', {
  adapter: 'memory'
});
// install docs and show view in various forms.
(async() => {
  await db.bulkDocs(getDocsToInstall(20));
  await showAllEventDocs();
  await showEventCountTotal();
  await showEventCountSummary();
  await showUserEventCount('Jerry@gmail.com', 'jerry_event_count');
  await showUserEventCount('Bobby@gmail.com', 'bobby_event_count');
  await showUserEvents('Jerry@gmail.com', 'jerry_events');
  await showUserEvents('Bobby@gmail.com', 'bobby_events');
})();
const gel = id => document.getElementById(id);

function getDocDate() {
  const today = new Date();
  const day = Math.random() * 100 % today.getDay() + 1; // keep it basic
  return new Date(today.getFullYear(), today.getMonth(), day)
}
.bold {
  font-weight: bold
}

.plain {
  font-weight: normal
}

All user_events (entire view)

Total number of events:  events

Event count summary (user, count)

Event count by email (specific to user)

Bobby@gmail.com has  events

Jerry@gmail.com has  events

Events by email

Bobby@gmail.com

Jerry@gmail.com

Notice the demo snippet's documents have a date field. If such a field existed in the OPs Event documents, then changing the emit to
emit(doc.email + '/' + doc.date);

would allow all the aforementioned queries plus the option to query by a date or date range, an exercise which I'll leave readers to explore.


text:
Q: Ajax based commenting Comment model
  belongs_to :post
  validates_presence_of :username
  validates_presence_of :body

Post model
  has_many :comments

posts_controller
def show
 @post = Post.find(params[:id])
 @comments = @post.comments
 @comment = Comment.new
end

comments_controler
def create
 @comment = Comment.new(params[:comment])
 if @comment.save
     @comments = @comment.post.comments
     respond_to do |format|
        format.js
     end
 else
     #what to do in here
 end
end

create.js
$("#comments").html("<%= escape_javascript(render :partial => "comments", :collections => @comments) %>");

posts show.html

 <%= render :partial => "comments", :collection => @comments %>

 <%= form_for(@comment, :method => :put, :remote => true) do |f| %>

 <% if @comment.errors.any? %>

 <% @comment.errors.full_messages.each do |msg| %>
 <%= msg %>
 <% end %>

 <% end %>

 <%= f.text_field :username %>
 <%= f.text_area :body %>
 <%= f.hidden_field :post_id, :value => @post.id  %>
 <%= f.submit %>

 <% end %>

I want to write something in commented are of create action in comments_controller so that i can display validation errors without reloading page. Any help will be appreciated. I can also change all codes if there is another solution to make ajax based commenting.

A: You could do this like this:
else
  respond_to do |format|
    format.js {
      render :text => "oops"
      # or
      render :partial => "/comments/error_message", :locals => {:comment => @comment} # @comment.errors would contain the validation errors
    }
  end
end


text:
Q: How do I rename c# types in Visual Studio? I need to redeclare a type called "Matrix4" to "Matrix" so that all references to "Matrix" will redirect to "Matrix4". Is there any simple way to do this without doing something drastic like a wrapper?
The reason I need this is for conditional library inclusions.
    #if USE_XNA
        using Library = XNA;
    #elif USE_OPENTK
        using OpenTK;
    #endif
    #if USE_OPENTK
        //Set "Matrix4" references to "Matrix"
    #endif

Matrix4 in OpenTK is roughly the same type as the Matrix type in XNA except it has a different identifier

A: Either you rename Matrix4 to Matrix like Random832 said or you declare an alias:
using Matrix = Namespace.Matrix4;

A: Right click on the name, select "Refactor -> Rename...".
That'll handle everything within the solution. If this is a public class in a library, you may need to change anything else that uses it too.

A: I wouldn't call a wrapper class "drastic," I'd call it the correct solution.
If anything else differs between the interfaces of those two libraries - method names, method parameter types, even the order of parameters - you are pretty much boned.
You should wrap Matrix/Matrix4 into a wrapper interface, and use that interface throughout the program... and do the same for any other classes you need from the two libraries.


text:
Q: Where can I learn properties about spaces of linearly independent projectors? I am interested in characterizing the space of all collections of $d^2$ linearly independent projectors on the Hilbert space $\mathbb{C}^d$. The linear independence I desire is in the vector space of $B(\mathbb{C}^d)$ of bounded operators on the Hilbert space.
I'm interested in this space because such sets of projectors correspond to minimal informationally complete rank-1 POVMs in quantum measurement theory (this shouldn't be necessary information for addressing my problem, but I include it for context). This has a connection to frame theory (a minimal informationally complete rank-1 POVM is a tight frame), but literature I've found on the subject seems to be missing the mark so far.
For instance, Manifold structure of spaces of spherical tight frames appears to be a promising article, but spherical tight frames are both too general and too restrictive for my interests (too general since I would like to fix the number of frame elements to $d^2$ and require the operators $\vert v\rangle\langle v\vert$ made from the frame elements $\vert v\rangle$ to be linearly independent operators; too restrictive since I would like to allow my frame elements to have different norms unlike the spherical case).
Does anyone know of literature addressing this structure?


text:
Q: Take in input as one string, help fix main so it only asks for one input Currently I have a class that shifts the input of a given string to print out an output. The program works fine and has the correct output, however I am not sure how to fix main so that it just needs to ask for one string instead of four separate strings. Please show how you would fix this
example output: WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO
the only issues I have is how main asks for four separate inputs, i would like it to only ask for one string, please show how
    public class shiftRows {

       public static String Shift(String str, int shiftNum)
       {
           char[] out = new char[4];
           if(shiftNum==1)
           {
               out[0]=str.charAt(1);
               out[1]=str.charAt(2);
               out[2]=str.charAt(3);
               out[3]=str.charAt(0);
           }
           if(shiftNum==2)
           {
               out[0]=str.charAt(2);
               out[1]=str.charAt(3);
               out[2]=str.charAt(0);
               out[3]=str.charAt(1);
           }
           if(shiftNum==3)
           {
               out[0]=str.charAt(3);
               out[1]=str.charAt(0);
               out[2]=str.charAt(1);
               out[3]=str.charAt(2);
           }
           return new String(out);
       }
       public static void main(String[] args)
       {

           Scanner sc =new Scanner(System.in);

           String[] input=new String[4];

           String[] output=new String[4];

           System.out.println("Enter 4 String's :");
           for(int i=0;i<4;i++)
           {
               input[i]=sc.next();
           }
           output[0]=input[0];
           for(int i=1;i<4;i++)
           {
               output[i]=Shift(input[i],i);
           }

           for(int i=0;i<4;i++)
           {
               System.out.println(output[i]);

             }

       }

}

A: Provides the same output, and uses the input of a single continuous String.
public static void main(String[] args)
{
   Scanner sc = new Scanner(System.in);

   String[] input= new String[4];

   String[] output= new String[4];

   // -
   System.out.println("Enter a String");
   String inputStr = sc.next();

   for (int i = 0, n = 0; i < 4; i++, n+=4) {
       input[i] = inputStr.substring(0+n, 4+n);
   }
   // -

   output[0] = input[0];
   for(int i=1; i<4; i++)
   {
       output[i] = Shift(input[i],i);
   }

   for(int i=0; i<4; i++)
   {
       System.out.println(output[i]);
   }

}


text:
Q: Child with z-index lower than parent becomes unclickable HTML

Το "Ανέλυτρον" ^

Όραμα

Φιλοσοφία

Ο Χώρος

CSS
.style-nav{...}
.style-nav ul li a:hover{...}
.dropdown{
    position: relative;
    cursor: pointer;
}
.dropdown span{
    ...
    position: relative;
}
.dropdown-content{
    position: absolute;
    z-index: -1;
}
.dropdown-content ul{...}
.dropdown-content ul li{...}
.dropdown-content ul li a {...}
.style-nav .dropdown:hover .dropdown-content{
    ...
    position: absolute;
    z-index: -1;
}
.title{
    ...
    position: relative;
    z-index: -2;
}

I need .dropdown-content to appear below the .style-nav but in front of the .title, however, it is a child of the .style-nav, and although lowering the z-index of it makes it appear fine, it is unclickable. Any way to fix it?


text:
Q: Using a const instead of values from database in Sequelize Node.js I'm working on a project that has some users and roles. I want to add association (belongsToMany) on users and roles. I'm using MySQL database and users are stored in users table. Currently i'm storing roles in database as well but i want roles to be stored in a file instead of database. Is there a way i could use a const instead of table from database.
index.js file:
...
db.user = require("./user.model.js")(sequelize, Sequelize);
db.role = require("./role.model.js")(sequelize, Sequelize);

db.role.belongsToMany(db.user, {
  through: "user_roles",
  foreignKey: "roleId",
  otherKey: "userId"
});
db.user.belongsToMany(db.role, {
  through: "user_roles",
  foreignKey: "userId",
  otherKey: "roleId"
});

role.model.js file
module.exports = (sequelize, Sequelize) => {
  const Role = sequelize.define("role", {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING
    }
  });

  return Role;
};

A: One thing that you could do is eliminate the Role table, and just create a UserRole table with a belongsTo() association to the User table. (And associate User to it by using hasMany())
You could then make the "name" column in UserRole have the ENUM datatype, and have the model draw the values available in that ENUM from reading the file in the file system. (Alternately, you can hard-code the values into the ENUM and that would be the "file" where you're updating possible role names)
I'm not totally sure what problem this is looking to solve, though. This seems like it would lead to a decrease in performance overall, though it WOULD eliminate the need for a Many-to-Many relationship that can be frustrating to work with.


text:
Q: Create WordPress instance inside another instance? I'm trying to install an WordPress v4.1.1 instance inside an existing instance of WordPress v4.1.1.
example:
http://website.com

is a website build in WordPress, and I want to create another website inside a subfolder of the current WordPress website
http://website.com/business

This way I would have two different websites with one inside another. The problem is that when reaching http://website.com/business it returns an 404 error from the outer website.
I think the problem is the .htaccess file that redirects to the outer instance of WordPress.
How do I fix the .htaccess files? which are:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A: There is no need to create another website inside a subfolder of the current WordPress website, there is a WordPress feature that was created and does exactly the same thing: take a closer look here https://codex.wordpress.org/Create_A_Network

A: Like so
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /business/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


text:
Q: AsynTask and Service binding This is a very silly one, and it's only because I don't like my code outputting errors to logcat that I'm asking about it.
I have a service called BackgroundCollectorProcess. It's main job, it to process rows in the database that haven't yet been reported. This is done via an XMPP connection. So, in onStartCommand I have the following:
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.d("BGCP", "Spinning");

        // Bind to our XmppConnector service to post any waiting transactions
        Intent iXmpp = new Intent(getApplicationContext(), BackgroundXmppConnector.class);
        bindService(iXmpp, mConnection, Context.BIND_AUTO_CREATE);

        // Start the sending of all collected logs
        new DeliveriesSenderTask().execute();
        new GeoLogSenderTask().execute();

        /*
            WARNING!!

            You can't call unbindService(mConnection) here - as the two main threads
            for posting delivery and geolocation transactions wont have completed in
            time. Thus, leaving this object unable to complete it's task.

            Logcat will throw up an "error" - saying about a resource binding being
            leaked in this class.

            TODO: Revisit this once there is a definitive answer to the problem.
         */

        // Commit suicide. BackgroundCollectorKicker will ressurect me.
        stopSelf();

        return Service.START_NOT_STICKY;
    }

As you can see by my massive wall of text for a comment, I've run into a stupid logcat error. Which is:
05-16 15:30:26.243: E/ActivityThread(16078): Service com.goosesys.gaggle.services.BackgroundCollectorProcess has leaked ServiceConnection com.goosesys.gaggle.services.BackgroundCollectorProcess$1@449ddff0 that was originally bound here
05-16 15:30:26.243: E/ActivityThread(16078): android.app.ServiceConnectionLeaked: Service com.goosesys.gaggle.services.BackgroundCollectorProcess has leaked ServiceConnection com.goosesys.gaggle.services.BackgroundCollectorProcess$1@449ddff0 that was originally bound here
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ContextImpl.bindService(ContextImpl.java:1507)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ContextImpl.bindService(ContextImpl.java:1496)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
05-16 15:30:26.243: E/ActivityThread(16078):    at com.goosesys.gaggle.services.BackgroundCollectorProcess.onStartCommand(BackgroundCollectorProcess.java:70)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2681)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ActivityThread.access$1900(ActivityThread.java:146)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1337)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.os.Looper.loop(Looper.java:137)
05-16 15:30:26.243: E/ActivityThread(16078):    at android.app.ActivityThread.main(ActivityThread.java:5171)
05-16 15:30:26.243: E/ActivityThread(16078):    at java.lang.reflect.Method.invokeNative(Native Method)
05-16 15:30:26.243: E/ActivityThread(16078):    at java.lang.reflect.Method.invoke(Method.java:511)
05-16 15:30:26.243: E/ActivityThread(16078):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
05-16 15:30:26.243: E/ActivityThread(16078):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
05-16 15:30:26.243: E/ActivityThread(16078):    at dalvik.system.NativeStart.main(Native Method)

These are the AsyncTasks:
    private class DeliveriesSenderTask extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected Void doInBackground(Void... arg0)
        {
            try
            {
                doPostDeliveries();
            }
            catch(Exception ex)
            {
                Utility.writeExceptionToLog(getApplicationContext(), ex);
            }
            return null;
        }
    }

    private class GeoLogSenderTask extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                doPostGeoLogs();
            }
            catch(Exception ex)
            {
                Utility.writeExceptionToLog(getApplicationContext(), ex);
            }
            return null;
        }
    }

Now, given that the tasks to be run themselves, are (or can be) quite time consuming, they have to be run in separate threads. So, I can't then call unbindService(), because the threads haven't finished.
My question is... When is best to call unbindService? Obviously, I've attempted to call it once GeoLogSenderTask has completed, but I still get LogCat outputting this silly message, because the main thread will finish before the two asynctasks.
Any help is greatly appreciated. Thanks.

A: Save both asyncTask instances as member variables.
Introduce in both AsyncTask implementations the onPostExecute method and in both methods check if the other task has finished with AsyncTask.getStatus == AsyncTask.Status.FINISHED.
When the other is finished call stopSelf() of the service.
 protected void onPostExecute(Result result) {
    if(otherTask.getStatus() == AsyncTask.Status.FINISHED) {
      stopSelf();
    }
  };


text:
Q: CSS: Positioning So I have the following sequence of html:

I am trying to display them like the following image:
Does anybody know the appropriate css to do so?

A: You can do this with Flexbox.

body, html {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.box-content {
  display: flex;
  height: 100vh;
  flex-wrap: wrap;
}

.box {
  border: 3px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  background: #22B14C;
  margin: 10px;
}
.box2, .box3{
  flex: 0 0 calc(50% - 20px);
}

.box1 {
  flex: 0 0 calc(100% - 20px);
}

One

Two

Three

A:

body {
  color: white;
}
.box-content {
  width: 700px;
  height: 210px;
  margin: 0 auto;
  background: red;
  border:10px solid red;
}
.box1 {
  width: 680px;
  height: 80px;
  background: green;
  padding: 10px;
 }
.box2 {
  width: 325px;
  height: 80px;
  background: green;
  float: left;
  padding: 10px;
  margin-top: 10px;
 }
.box3 {
  width: 325px;
  height: 80px;
  background: green;
  float: right;
  padding: 10px;
  margin-top: 10px;
 }

Box 1

Box 2

Box 3


text:
Q: How should I proceed for building a website where you can play chess with other people? I'm a beginner: I know HTML/CSS and a little Javascript. Also, I've started learning Python.
As a first personal objective, I want to build a site where you can play with friends simply by sending them a URL (like lichess.org does). No need for registration.
Could I create the chessboard and the pieces just with javascript? If not, is Python a good language for such a task? Where can I find a guide for building simple games?

A: I guess you need a starting point.
if you are looking to built something from the ground up. I'd start with programming the logic of each of the chess pieces. Then implement that onto a board, then implement that with all other game rules.
Any language can achieve what you are trying to do. Python is as good as any to do that.
I'm guessing you didn't spend a lot of time googling this, here's some info:
https://softwareengineering.stackexchange.com/questions/160740/best-approach-for-writing-a-chess-engine
Forget the multiplayer stuff for now. Start with building the game.


text:
Q: EPPlus Table @ Column reference I'm trying to use EPPlus to create a table on a worksheet. I can create the table, but all my @ variables become #Ref! when opening up the file. If I paste the exact same formula into Excel it takes it and has no problem. What am I missing here? Do I need to apply the table somehow after creating it?
Thanks,
Lee
private void ProcessVehicleData(BorrowingBase bbData, ExcelWorksheet ew, int colStart, int rowStart) {
    int origFirstRow = rowStart;
    foreach (DailyCAPS data in bbData.DailyCAPS) {
        FillRow(ew, data, colStart, rowStart);
        ++rowStart;
    }

    try {
        ExcelAddressBase eab = new ExcelAddressBase(origFirstRow - 1, ExcelColumnNameToNumber("A"), rowStart - 1, ExcelColumnNameToNumber("Y"));
        ExcelTable et = ew.Tables.Add(eab, "VehicleData");

        if (origFirstRow != rowStart) {
            ew.Cells[origFirstRow, ExcelColumnNameToNumber("Y")].Formula = "=IF([@Inventory Days]>210,\"H\",IF([@TitleApp]+[@UtahTitleReceived]=0,\"B\",\"\"))";
        }
    }
    catch { }
}

A: See comments for answer...github.com/JanKallman/EPPlus/issues/521

A: No,epplus can't do it.
Because epplus Tables.Add is only pure data fill not workbook query,so =[@XXX] is not work.


text:
Q: Python dot-syntax-functions based on condition Is it possible in python to call dot-syntax-function based on condition. Simple example to turn:
if condition:
  foo().bar().baz()
  lots_of_code()
else:
  foo().baz()
  lots_of_code()

def lots_of_code():
  # lots of code

into:
foo().(if condition: bar()).baz()
# lots of code only once

A: No, it is not possible.
The syntax for attribute reference is
attributeref ::=  primary "." identifier

Quoting the documentation,

An attribute reference is a primary followed by a period and a name

name must be a regular Python identifier and identifiers can't contain special characters like (.
However, you can use a simple conditional expression to select primary:
(foo().bar() if condition else foo()).baz()

It's equivalent to
if condition:
    primary = foo().bar()
else:
    primary = foo()

primary.baz()

Note that in this case we have to use parentheses, because attribute reference has higher precedence than conditional expression.

A: Since foo() is called in either case, start by doing so unconditionally. Save that object to f, with the intention of calling f.baz(). Before that, though, check your condition to see if f should really be the result of foo().bar().
f = foo()
if condition:
    f = f.bar()
f.baz()


text:
Q: Java Logger does not print anything to console I'm just starting to learn about Logger in Java; however, I don't understand how it works.
I have this code right after my class declaration:
private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());

Then in my methods I use it like this (examples):
LOGGER.log(Level.FINE, "Testing");
LOGGER.info("More testing...");

...
} catch(Exception e) {
    LOGGER.log(Level.SEVERE, e.toString(), e);
}

But nothing prints to the console. Is it being saved in a file somewhere or am I just using it incorrectly?
I am using Eclipse Mars 2 with Java 1.6.0_22 if it makes a difference.
EDIT: I am using the java.util.logging.Logger library.

A: Here's what you should know, java.util.Logging is controlled by a root logger file found in the JRE/lib folder called logging.properties that defaults to Level.INFO, hence Fine messages are not displayed by default since FINE is lower than INFO,
 private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());

 Handler handlerObj = new ConsoleHandler();
 handlerObj.setLevel(Level.ALL);
 LOGGER.addHandler(handlerObj);
 LOGGER.setLevel(Level.ALL);
 LOGGER.setUseParentHandlers(false);

Now you can use your LOGGER object just fine and should work. checkout Java Logging Overview
 LOGGER.log(Level.FINEST, "finest");

Remember that there's a reason the Log Level is set to FINE, so,lowering the level could also print unnecessary info from core libraries. Let me know if it helps.
Regards Douglas

A: My assumption is that you are using Log4J. If that is correct, the logger should be saving to a file by default not printing to a console (which is usually done with System.out.println("message")). Do you have a log4j.properties file?

A: This seems to work for me in a brand new Eclipse project.
import java.util.logging.Logger;

public class Foobar {

    public static final Logger LOGGER = Logger.getLogger(Foobar.class.getName());;

    public Foobar() {
        LOGGER.info("Constructed");
    }

    public static void main(String[] args) {
        new Foobar();
    }
}

A: The nothing is displayed because there are no handlers attached to the Logger with name MyClass.class.getName();
But,there is one handler by default in the parent logger instance.This handler is ConsoleHandler that has log level INFO.
It's easy to verify:
public class StackAnswerAboutLogger {

private static final Logger LOGGER = Logger.getLogger(StackAnswerAboutLogger.class.getName());
private static final Logger PARENT_LOGGER = Logger.getLogger("");

public static void main(String[] args) {
    LOGGER.info("Count of LOGGER handlers: " + Integer.toString(LOGGER.getHandlers().length));
    LOGGER.info("Count of PARENT_LOGGER handlers: " + Integer.toString(LOGGER.getHandlers().length));
    Handler defaultConsoleHandler = PARENT_LOGGER.getHandlers()[0];
    LOGGER.info("Default Console Handler Log Level: " + defaultConsoleHandler.getLevel().toString());
  }

}

Output:
Jan 10, 2020 10:23:53 PM init.StackAnswerAboutLogger main
INFO: Count of LOGGER handlers: 0
Jan 10, 2020 10:23:54 PM init.StackAnswerAboutLogger main
INFO: Count of PARENT_LOGGER handlers: 0
Jan 10, 2020 10:23:54 PM init.StackAnswerAboutLogger main
INFO: Default Console Handler Log Level: INFO

To display the log with ANY level, you could configure either PARENT_LOGGER handlers or LOGGER ones.
Handler defaultConsoleHandler = PARENT_LOGGER.getHandlers()[0];
LOGGER.info("Default log level of PARENT_LOGGER: " +PARENT_LOGGER.getLevel().toString());
LOGGER.info("Default Console Handler Log Level: "+defaultConsoleHandler.getLevel().toString());
defaultConsoleHandler.setLevel(Level.ALL);
PARENT_LOGGER.setLevel(Level.ALL);
LOGGER.log(Level.FINEST, "here is finest log");
LOGGER.log(Level.SEVERE, "here is severe log");

Output:
Jan 10, 2020 10:38:10 PM init.StackAnswerAboutLogger main
INFO: Default log level of PARENT_LOGGER: INFO
Jan 10, 2020 10:38:10 PM init.StackAnswerAboutLogger main
INFO: Default Console Handler Log Level: INFO
Jan 10, 2020 10:38:10 PM init.StackAnswerAboutLogger main
FINEST: here is finest log
Jan 10, 2020 10:38:10 PM init.StackAnswerAboutLogger main
SEVERE: here is severe log


text:
Q: Oracle Developer Tools for visual studio .net errors i had installed oracle 12c on pc and visual studio 2015 when i tried to install ODAC for integrating oracle over visual studio
then i got an error that
   [INS-50013] Oracle Developer Tools for Visual Studio .NET Error.
   Please install Visual Studio before you proceed with this installation
i forgot to mention that i had installed visual studio in one user and oracle in another user though i could access all the features of both oracle and visual studio
Please  give me the way to get out of this problem

A: Now supported VS2015. still not support vs2017.
Anyone can get from this:
http://www.oracle.com/technetwork/topics/dotnet/downloads/index.html
Updated: Now we can get ODAC for vs2017 at ODAC for vs 2017


text:
Q: How do I make a scrypt hash using Node.js's crypto library? function sha512(s){
    var sha = crypto.createHash('sha512');
    sha.update(s);
    return sha.digest('hex');
};
exports.sha512 = sha512;

I'm using this right now, but I want to switch it to scrypt.  How can I do that?

A: You should use node-scrypt.
It has clear API and good documentation.
var scrypt = require("scrypt");
var scryptParameters = scrypt.params(0.1);

var key = new Buffer("this is a key"); //key defaults to buffer in config, so input must be a buffer

//Synchronous example that will output in hexidecimal encoding
scrypt.hash.config.outputEncoding = "hex";
var hash = scrypt.hash(key, scryptParameters); //should be wrapped in try catch, but leaving it out for brevity
console.log("Synchronous result: "+hash);

//Asynchronous example that expects key to be ascii encoded
scrypt.hash.config.keyEncoding = "ascii";
scrypt.hash("ascii encoded key", {N: 1, r:1, p:1}, function(err, result){
    //result will be hex encoded
    //Note how scrypt parameters was passed as a JSON object
    console.log("Asynchronous result: "+result);
});

A: I'll throw my implementation out there: https://www.npmjs.org/package/scryptsy.
Here's an example:
var scrypt = require('scryptsy') //npm install --save scryptsy

var key = "pleaseletmein" //can be of type 'Buffer'
var salt = "SodiumChloride" //can be of type 'Buffer'
var data = scrypt(key, salt, 16384, 8, 1, 64)
console.log(data.toString('hex'))
// => 7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887

Documentation here: http://cryptocoinjs.com/modules/crypto/scryptsy/

A: Simplified barrysteyn/node-scrypt sync example with (de)serialization:
    let scrypt = require('scrypt')
    let scryptParameters = scrypt.paramsSync(0.1)

    function encode(s) {
      return scrypt.kdfSync(s, scryptParameters).toString('Base64')
    }

    function verify(encoded, s) {
      return scrypt.verifyKdfSync(new Buffer(encoded, 'Base64'), s)
    }

    // Example:
    let s = encode('my password')  // c2NyeXB0AAwAAAAI....
    verify(s, 'my password')   //true
    verify(s, 'my pa$$word')   //false

Tested on node 7.0.0, scrypt 6.0.3.