text:
Q: Partitioning MySQL vs PostgreSQL For our new system we are looking for database server. We considered a lot of pros/cons for MySQL(InnoDB) vs PostgreSQL and the breaking point for us is partitioning. We will choose the one which partitioning fits better our needs.
Our case
The IS is backend for selling tickets. We sell thousands of tickets daily so the table scales quite fast and seat reservations scale even faster.
+--------------+            +-------------------+
| tickets      |    1:N     | seat_reservations |
+--------------+            +-------------------+

We want to use date partitioning for both of these tables and some others but this is the core.
We need to force preserve db integrity via foreign keys or some similar solution. I know that InnoDB doesn't support FK with partitioning.
The questions

*

*Does PostgreSQL support FK and Partitioning? Probably for rules based partitioning.

*Is another way how to force preserve DB integrity?

*Which SQL server do you recomend? (based on partitioning)

I plan to partition both tables. I want partition even more than that (log,...) but these are the main tables.
We are just building the system so we want to use the newest versions; MySQL 5.6 or PostgreSQL 9.3. The r/w ratio will be about 3:1 (r:w), and the line count will be 700k growing about 100k per month so we have to be able to have more than 7m lines.

A: Ok, PostgreSQL does not directly support foreign keys and partitions. You can create a foreign key on each partition, but there is no way to have a foreign key against a set of partitions without either coding the constraint triggers yourself or using a key management table.
There are several ways to resolve this, but they require some understanding of underlying db implementation concepts to make perform well.
The first is to do your referential integrity enforcement manually through triggers.  You can write constraint triggers which can be deferred (if needed) that check the existence of foreign key information.  Note this is subject to ALTER TABLE DISABLE TRIGGER ALL issues but it should generally work.
The second is to have a separate table which stores keys and is maintained through a combination of triggers and bulk data operations.  This can help a great deal.
So it is possible to enforce things but it requires a bit more work.
I don't know enough about MySQL's table partitioning capabilities to comment on it though.


text:
Q: How to update to the latest floating version with lock file in dotnet? I have project that references a nuget package. Here is a snippet from .csproj file:
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
...

<PackageReference Include="MyPackage" Version="1.*" />

Now after the restore the lock file is created and a version is locked, e.g. 1.0.1. What I want to do now is to force to reevaluate floating version after I publish a new package. I did not manage to achieve that, whatever I call, the version stays the same. This is what I tried, but to no avail:
dotnet restore -f --force-evaluate --no-cache

I use Rider and tried to do that in the GUI by clicking restore there. It does work but not at once, I have to wait some time before a new version is detected until it's getting restored. I did not manage to figure out what command Rider issues to do the update or why it does not work at once.

A: Apparently deleting of the packages.lock.json works just fine, but it's hardly a very good solution, so I still hope for a better answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: facing error in linkedin third party job posting widget integration Has anyone tried to do job posting integration with linkedin before? i am trying this but it is continuously giving me a 401 error.
this is the document that is given on linkedin docs
I tried implementing this but doesn't work. Has anyone got any idea?


text:
Q: How to properly install steambp I'm new at Ubuntu and very eager to learn the ropes. I´m having a bit difficulty working the Terminal though. I'm running Ubuntu 15.10.
I am trying to install this awesome GRUB modification https://github.com/LegendaryBibo/Steam-Big-Picture-Grub-Theme/blob/master/README.md
Now it tells me to install it by running the install.sh through root in terminal, I've managed to get root, but I have no idea how I go about installing the script. If anyone could tell me the exact way to do so that'd be great, the Readme is a bit lacking in information for starting people. I did install the font needed though.
Thanks in advance!

A: The commands to install it from the directory it is saved:
cd ~/Downloads
unzip Steam-Big-Picture-Grub-Theme-master.zip
sudo -i
cd ~/Downloads/Steam-Big-Picture-Grub-Theme-master/
chmod 755 install.sh
./install.sh

(it requires root).
The install script will install files to a new directory "SteamBP" in one of these directories, in the 1st one it finds: /grub /boot/grub /boot/grub2 and the grub version on the system needs to be at least 1.98.
There are 3 settings in the install.sh you can edit prior to installing:
Theme_Name="SteamBP"
Theme_Definition_File="theme.txt"
Theme_Resolution="any"

The 1st notice that all is going well will be a question regarding the resolution if the last option is set to "any".

Proof:


text:
Q: How can I grab the value of an input form on React Bootstrap? I am attempting to grab the value of an input form on React Bootstrap but the obvious way doesn't seem to be working.
This is the form field component:
const FormField = ({
  type,
  label,
  value,
  onChange,
  controlId,
  placeholder,
}) => (
  <Form.Group as={Row} controlId={controlId}>
    <Form.Label column sm={4}>
      {label}
    </Form.Label>
    <Col sm={8}>
      <Form.Control
        type={type}
        value={value}
        onChange={() => onChange(value)}
        placeholder={placeholder}
      />
    </Col>
  </Form.Group>
);

And here is the parent where I call that component above:
class FormFieldsGroup extends Component {
  state = {
    firstName: '',
  };

  render() {
   const { firstName } = this.state;
   return (
        <FormField
          type="text"
          label="First Name"
          controlId="firstName"
          placeholder="First Name"
          value={firstName}
          onChange={firstName => this.setState({ firstName })}
        />
   )
  }
}

It only returns an empty string.
What can I do to store the value of that input in a local component state?

A: value={firstName}

must be
value={this.state.firstName}

because your value is changing when you type

A: Can you try onChange={onChange} in Form.Control instead of   onChange={() => onChange(value)}
Also check whether it returns value direct or it returns event if returning event use event.target.value


text:
Q: How many digits after the decimal point can a float variable save in c? So, I am really confused about the number of decimals after the floating point in a float type variable.
In the book that I am reading, it says that the float variable can include up to 6 decimals after the
floating point. But the problem is, in the internet it says that a float variable can save up to
7digits after the decimal point. Who is right and what is the number of decimals that a float variable
can save after the decimal point?


text:
Q: How can I extract a JSON object from a CSV file in Python? I am extracting column values from a csv file (not the whole file). The values are in JSON format as follows:
{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}

I am able to get these values into a list with the following code (json objects = [6] indicates the seventh column in my csv file):
import csv

with open('C:\\file\\path\\to\\csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')

    json_objects = [6]

    for row in reader:

        single_json = list(row[i] for i in json_objects)
        print ', '.join(single_json)

How can I extract the columns as JSON's; not as lists?

A: This should do what you want:
#!/usr/bin/python

import csv
import json

with open('csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in reader:
        single_json = row[6]
        single_json = single_json.replace("u'", "'")
        single_json = single_json.replace("'", '"')
        data = json.loads(single_json)
        print json.dumps(data, indent=4)

Input file named "csv":
2840,test_category_labeling_highlight,84,3635,0,Other,"{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}",8,7,FALSE

Output:
{
    "Other": {
        "Text": "Telephone",
        "end": 54,
        "value": "contact information",
        "start": 45
    }
}


text:
Q: Representing a series of Matrix inner product with a single matrix product. I have a set of constraints in my optimization problem, constraints in the form , $\langle A, e_i e_j^T \rangle = r_{ij} ,\forall i,j \epsilon S$, where $A$ is an $n*n$ semidefinite and symmetric matrix, $e_i$ is a vector with $1$ on the $i th$ place and zero else where. Also, $\langle,\rangle$ is the matrix inner product which is $\langle A, B \rangle = trace(A^T B)$ and $S$ is a set of indices. Is there any way I can show all this constraints using some matrices $C$,$D$ in a single matrix product in the form: $ C A = D$, or even in the form of $C A E = D$. Size of the matrices $C$ and $D$ may be large. In my simple case, of course it is obvious that $A_{ij}=r_{ij}$, but I want to represent it in matrix product form. Actually I want to use it in my optimization problem to approximate constraints i.e. , $CA \approx D$.

A: Assuming $e_i$ is a column vector, we have
$$ e_i \, e_j^T = \delta_{ij},$$
where $\delta_{ij}$ is the Kronecker delta.
So you have
$$\langle A, e_i e_j^T \rangle = r_{ij} ,\forall i,j \in D \iff \langle A, \delta_{ij}\rangle = r_{ij}.$$
Therefore  the diagonal of matrix $A$ consists of the entries $r_{ii}$.


text:
Q: Button displays only last note in my note taker app

const adder = document.querySelector('.adder')
const gridcont = document.querySelector('.gridbox')
const text = document.querySelector('p')
const button = document.querySelector('.button')
const popup = document.querySelector('.popup-wrapper')
const popuptext = document.querySelector('.popup-content')
const close = document.querySelector('.popup-close')
const notecard = document.querySelector('.card')
const notetext = document.querySelector('.card-text')
const pi = document.querySelector('p')
let counter = 0;
let html;
let note;
let html2

/*close.addEventListener('click', e =>{
  popup.style.display ='none'
}) */

popup.addEventListener('click', e=>{
  popup.style.display ='none'
})

const template = note =>{
   html = `

Note ${counter}

${note}

    <button class="button" type="button">view detail</button>

`

gridcont.innerHTML += html
}

adder.addEventListener('submit', e =>{
  e.preventDefault()
  note = adder.add.value

  if(note.length){
    counter++
    template(note)
    adder.reset()
  }
})

gridcont.addEventListener('click', e =>{
    if(e.target.classList.contains('button')){
         popup.style.display = 'block'
         popuptext.innerHTML = html
    }
  });
.card{
  margin-left: 2rem;
  margin-top: 2rem;

}
.form-control{
  max-width: 500px;
}
.blu{
  color: blue;
}

.gridbox{
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}
.button{
  color:white;
  background-color: rgb(41, 41, 241);
  border-color: rgb(41, 41, 241);;
}

  .card-text{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }

.popup-wrapper{
  display: none;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.popup{
  font-family: arial;
  text-align: center;
  width: 100%;
  max-width: 500px;
  margin: 10% auto;
  padding: 20px;
  background: white;
  position: relative;
}

.popup-close{
  position: absolute;
  top: 5px;
  right: 8px;
  cursor: pointer;
}

.card-text-show{
  overflow: unset;
  text-overflow: unset;
  max-width: 200px;

}
<!DOCTYPE html>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
    <title>Note taker</title>

Note taker app

         <h8 class="blu">add note:

      <form class="adder">
         <input class="form-control m-auto" type="text" name="add"  placeholder="Enter your note here">
      </form>

x

im trying to make note taker app and each time i add the note and click the view detail button
it shows me only the content of  last item added regardless of which one i  press i dont know how to write with loop or forEach method i tried it but i failed can anyone explain what to do here im a begginer JS
const adder = document.querySelector('.adder')
const gridcont = document.querySelector('.gridbox')
const text = document.querySelector('p')
const button = document.querySelector('.button')
const popup = document.querySelector('.popup-wrapper')
const popuptext = document.querySelector('.popup-content')
const close = document.querySelector('.popup-close')
const notecard = document.querySelector('.card')
const notetext = document.querySelector('.card-text')
const pi = document.querySelector('p')
let counter = 0;
let html;
let note;
let html2

/*close.addEventListener('click', e =>{
  popup.style.display ='none'
}) */

popup.addEventListener('click', e=>{
  popup.style.display ='none'
})

const template = note =>{
   html = `

Note ${counter}

${note}

    <button class="button" type="button">view detail</button>

`

gridcont.innerHTML += html
}

adder.addEventListener('submit', e =>{
  e.preventDefault()
  note = adder.add.value

  if(note.length){
    counter++
    template(note)
    adder.reset()
  }
})

gridcont.addEventListener('click', e =>{
    if(e.target.classList.contains('button')){
         popup.style.display = 'block'
         popuptext.innerHTML = html
    }
  });

HTML
<!DOCTYPE html>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
    <title>Note taker</title>

Note taker app

         <h8 class="blu">add note:

      <form class="adder">
         <input class="form-control m-auto" type="text" name="add"  placeholder="Enter your note here">
      </form>

x

I dont really know many methods so i just use one way im stuck on this project for 4 days
CSS
.card{
  margin-left: 2rem;
  margin-top: 2rem;

}
.form-control{
  max-width: 500px;
}
.blu{
  color: blue;
}

.gridbox{
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}
.button{
  color:white;
  background-color: rgb(41, 41, 241);
  border-color: rgb(41, 41, 241);;
}

  .card-text{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }

.popup-wrapper{
  display: none;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.popup{
  font-family: arial;
  text-align: center;
  width: 100%;
  max-width: 500px;
  margin: 10% auto;
  padding: 20px;
  background: white;
  position: relative;
}

.popup-close{
  position: absolute;
  top: 5px;
  right: 8px;
  cursor: pointer;
}

.card-text-show{
  overflow: unset;
  text-overflow: unset;
  max-width: 200px;

}

A: On popuptext.innerHTML = html line you are making the mistake, so what is happening is you are setting the innerHTML of popuptext as variable html, so this line tries find html variable and goes to part of this code,
const template = note =>{
  html = `

Note ${counter}

${note}

    <button class="button" type="button">view detail</button>

`

  gridcont.innerHTML += html
}

and then it finds the HTML variable here, however the value of this html variable will be whatever you have set it to earlier, so if you add three notes then the value of the html variable will be innerhtml of the latest/last note that you added.
To fix that I have made a change as popuptext.innerHTML = e.target.parentElement.innerHTML, this line makes sure that whatever element you are clicking that element's associated innerhtml is added to the popup.

const adder = document.querySelector('.adder')
const gridcont = document.querySelector('.gridbox')
const text = document.querySelector('p')
const button = document.querySelector('.button')
const popup = document.querySelector('.popup-wrapper')
const popuptext = document.querySelector('.popup-content')
const close = document.querySelector('.popup-close')
const notecard = document.querySelector('.card')
const notetext = document.querySelector('.card-text')
const pi = document.querySelector('p')
let counter = 0;
let html;
let note;
let html2

/*close.addEventListener('click', e =>{
  popup.style.display ='none'
}) */

popup.addEventListener('click', e=>{
  popup.style.display ='none'
})

const template = note =>{

   html = `

Note ${counter}

${note.substring(0,6)}...${note}

    <button class="button" type="button">view detail</button>

`

gridcont.innerHTML += html
}

adder.addEventListener('submit', e =>{
  e.preventDefault()
  note = adder.add.value

  if(note.length){
    counter++
    template(note)
    adder.reset()
  }
})

gridcont.addEventListener('click', e =>{
    if(e.target.classList.contains('button')){
         popup.style.display = 'block'
         let temp = `

${e.target.parentElement.querySelector('.card-title').innerText}

${e.target.parentElement.querySelector('.only-popup').innerText}

    <button class="button" type="button">view detail</button>

`
         popuptext.innerHTML = temp
    }
  });
.card{
  margin-left: 2rem;
  margin-top: 2rem;

}
.form-control{
  max-width: 500px;
}
.blu{
  color: blue;
}

.gridbox{
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}
.button{
  color:white;
  background-color: rgb(41, 41, 241);
  border-color: rgb(41, 41, 241);;
}

  .card-text{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }

.popup-wrapper{
  display: none;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.popup{
  font-family: arial;
  text-align: center;
  width: 100%;
  max-width: 500px;
  margin: 10% auto;
  padding: 20px;
  background: white;
  position: relative;
}

.popup-close{
  position: absolute;
  top: 5px;
  right: 8px;
  cursor: pointer;
}
.only-popup{
  display:none;
}
.card-text-show{
  overflow: unset;
  text-overflow: unset;
  max-width: 200px;

}
<!DOCTYPE html>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
    <title>Note taker</title>

Note taker app

         <h8 class="blu">add note:

      <form class="adder">
         <input class="form-control m-auto" type="text" name="add"  placeholder="Enter your note here">
      </form>

x


text:
Q: Can You Securely Authenticate A Request Via IP? I am currently integrating the NAB Transact payment gateway into a e-commerce shop. Once the payment has been processed the NAB Transact system sends a POST request to our endpoint for us to process the result.
The problem is that the POST request contains no secure hash / token that we can use to post back to the NAB Transact system to authenticate that the request is real and not spoofed. Even worse, the NAB Transact system does not even have a API for any authentication of any information, essentially, very bad security!
Is there a way to securely authenticate these requests? For example, checking that the requests come from a list of known IP addresses that the NAB transact system operates on? Or reverse lookup a IP? What options are there and how would you implement this in PHP?
Isn't relying on IP authentication not that secure since it can be spoofed?

A: Authentication based on IP addresses is fine if you:

*

*know the list of IPs (i.e. the ones used by the payment provider)

*the IPs are static (obviously, but if the request is actually sent by the provider and not e.g. through a hidden form on the "payment successful" page that's the case)

*they immediately notify you of any changes (or your script might reject valid requests or accept requests from IPs not used by the provider anymore)

*all systems which can use the IP address (i.e. the servers of the payment provider assuming the datacenter is not using some crappy network setup) is trusted enough not to send any false notifications.

Spoofing the source IP is not possible since TCP uses a three-way-handshake and with a spoofed IP the handshake would fail.
So basically: Authentication by IP is acceptable if some basic criteria are met (see above), but of course it would be more secure if they provided you with a way to validate the notification - either by calling an API on their side or by using a cryptographic signature (better since it cannot fail due to an unreachable remote server).

A:
The problem is that the POST request contains no secure hash / token
  that we can use to post back to the NAB Transact system to
  authenticate that the request is real and not spoofed

Yup - that's a problem alright :)

Isn't relying on IP authentication not that secure since it can be
  spoofed?

It isn't at ALL secure!


text:
Q: Minesweeper program exceeding time limit I am following a course by princeton university on cousera, I wrote the following code for the following problem:

Minesweeper. Minesweeper is a 1960s era video game played on an m-by-n grid of cells. The goal is to deduce which cells contain hidden mines using clues about the number of mines in neighboring cells. Write a program Minesweeper.java that takes three integer command-line arguments m, n, and k and prints an m-by-n grid of cells with k mines, using asterisks for mines and integers for the neighboring mine counts (with two space characters between each cell). To do so,
Generate an m-by-n grid of cells, with exactly k of the mn cells containing mines, uniformly at random.
For each cell not containing a mine, count the number of neighboring mines (above, below, left, right, or diagonal).

Every time I submit to the grader; it says the 60 second limit was exceeded, and it stops grading.
This is the desired output

public class Minesweeper {

    public static void main(String[] args) {

        int m = Integer.parseInt(args[0]);
        int n = Integer.parseInt(args[1]);
        int k = Integer.parseInt(args[2]);

        boolean[][] minePositions = new boolean[m + 2][n + 2];
        int[][] grid = new int[m + 2][n + 2];

        int num = 0;
        while (num != k) {
            if ((m * n) == k) {
                for (int f = 1; f <= m; f++) {
                    for (int z = 1; z <= n; z++) {
                        minePositions[f][z] = true;
                    }
                }
                break;
            }
            int r = (int) (Math.random() * (m * n - 1));
            int q = r / n;
            int rem = r % n;
            if (q == 0) {
                q = 1;
            }
            else if (q > (m - 1)) {
                q = m - 1;
            }
            if (rem == 0) {
                rem = 1;
            }
            else if (rem > (n - 1)) {
                rem = n - 1;
            }

            if (!minePositions[q][rem]) {
                minePositions[q][rem] = true;
                num++;
            }
        }

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (minePositions[i - 1][j + 1]) grid[i][j]++;
                if (minePositions[i][j + 1]) grid[i][j]++;
                if (minePositions[i + 1][j + 1]) grid[i][j]++;
                if (minePositions[i - 1][j]) grid[i][j]++;
                if (minePositions[i + 1][j]) grid[i][j]++;
                if (minePositions[i - 1][j - 1]) grid[i][j]++;
                if (minePositions[i][j - 1]) grid[i][j]++;
                if (minePositions[i + 1][j - 1]) grid[i][j]++;
            }
            for (int j = 1; j <= n; j++) {
                if (minePositions[i][j]) System.out.print("*  ");
                else System.out.print(grid[i][j] + "  ");
            }
            System.out.print("\n");
        }

    }
}

A: I think using arrays of size (m + 2, n + 2) confused your math here. I'll continue on your work, always use m + 2 and n + 2 in your calculations to avoid any confusion.
int r = (int) (Math.random() * ((m + 2) * (n + 2)));
Generate a random number than can span all your array cells.
int q = r / (n + 2);
int rem = r % (n + 2);

// Increment num only if q and rem are in the ranges and the position does not have a mine on it
if (q > 0 && q <= m && rem > 0 && rem <= n && !minePositions[q][rem]) {
    minePositions[q][rem] = true;
    num++;
}

The full code
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);

boolean[][] minePositions = new boolean[m + 2][n + 2];
int[][] grid = new int[m + 2][n + 2];

int num = 0;
while (num != k) {
    int r = (int) (Math.random() * ((m + 2) * (n + 2)));
    int q = r / (n + 2);
    int rem = r % (n + 2);

    if (q > 0 && q <= m && rem > 0 && rem <= n && !minePositions[q][rem]) {
        minePositions[q][rem] = true;
        num++;
    }
}

for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
        if (minePositions[i - 1][j + 1]) grid[i][j]++;
        if (minePositions[i][j + 1]) grid[i][j]++;
        if (minePositions[i + 1][j + 1]) grid[i][j]++;
        if (minePositions[i - 1][j]) grid[i][j]++;
        if (minePositions[i + 1][j]) grid[i][j]++;
        if (minePositions[i - 1][j - 1]) grid[i][j]++;
        if (minePositions[i][j - 1]) grid[i][j]++;
        if (minePositions[i + 1][j - 1]) grid[i][j]++;
    }
    for (int j = 1; j <= n; j++) {
        if (minePositions[i][j]) System.out.print("*  ");
        else System.out.print(grid[i][j] + "  ");
    }
    System.out.print("\n");
}


text:
Q: Is coding style mostly for readability or are there other factors? I remember reading in Douglas Crockford's "Javascript the Good Parts" book that there is potential for error with blockless statements because of automatic semicolon insertion.
if (condition)
   foo = true;

vs
if (condition)
{
   foo = true;
}

In the second the example it will work consistently, in the first example a semicolon will be automatically inserted by the interpreter and can lead to ambiguity in the code. As Douglas points out this is potentially bad and hard to debug, which I agree. But it got me thinking are there examples where coding "style" actually has syntax implications? In other words, examples where failing to follow a certain indentation or apparent style actually results in a bug or error. I suppose Python with its significant whitespace is an example, YML with its requirement for no tabs is another.
Feel free to respond in a wide variety of languages and idioms. I am curious to hear about the paradigm cases. In your answer I would like to know the WHAT and the WHY of the coding style or syntax behavior. I don't want to start any coding style flame wars, just matter of fact scenarios where the uninitiated would get tripped up.

A: Javascript treats these two cases seperately.  You have to use the first
return {
   // code
}

return
{
   // code
}

If you do not the interpreter adds semi colons in the wrong places.  I think it puts one after the condition. So the second would be read wrongly as.
return;
{
   // code
}

Which is not invalid syntax.

A: A coding style is not only for readability. There are some other factors like

*

*Avoid common language pitfalls (silent fails, exceptions while casting etc.)

*Ease of maintenance

*Increase the clarity of code (e.g. private functions always starting loweCase and public beeing PascalCase)

*Enforcing conventions (e.g. not using multiple inheritance or always inherit public in c++)

an example for ease of maintenacne is below:

if(x) return true;

vs.
if(x)
{
   return true;
}

it is clear the second is easier to maintain, because i can simply go ahead and add a new line and add a call to bla() without having to add brackets before.

A: No one has mentioned it before, but one point of style is to write
if (NULL==p) // ...
instead of
if (p==NULL) // ...
The two are functionally equivalent so it's a matter of style. Many prefer the style at the top, because if you type "=" by mistake instead of "==", the first won't compile whereas the second will, and creates a bug that is hard to find (though some compilers now give you a warning for if (p=NULL)).

A: In Python, the whitespace indentation, rather than curly braces or keywords, delimits the statement blocks. An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.

A: Whitespace is not significant in any of the C family of languages, except to separate certain language tokens. The layout of the source code has no effect on the executable produced by the compiler.

A: In C++, there's a difference between
vector<pair<int,int>>

and
vector<pair<int,int> >

because >> is treated as a single token by the parser.

A: Every time I open a parentheses, brace, single or double quote I always close it and then go back to write the statement, condition, etc... This saves me from quite some possibly big mistakes!

A: It depends on the language. In the curly family C/C++/Java/C#, whitespace is not the restriction as long as your braces are opened and closed properly.
In languages like VB where paired keywords are used, just because keywords delimit functions you can't have
Private Sub someFunction() End Sub

But in C, C++ and other curly languages, you can have
void someFunction() { }

In python, I guess its a completely different matter.
It all depends on the particular language. As per your specific example, I don't think there is a syntactical or semantic difference between the two.

A: It is language dependant.
For instance in Java
void someFunction() { }

and
void someFunction() {
}

and
void someFunction()
{
}

will have no implication whatsoever. However Sun has enlisted a list of coding conventions if you are interested you could read them here.
These are mainly for maintainability and readability of code but need not be strictly followed.

A: The title wasn't specific to conditional blocks, so this came to mind:
I don't see it mentioned yet, but one thing to consider is how do you find things with simple tools (like grep and its inferior implementations from windowsland).
For example consider this (admittedly a bit contrived) example
class Foo
// vs.
class
Foo

You can find former with regex "class\s+Foo", but for latter you'll have to have a specialized tool that can parse C++/C#/java.
This applies also in C for function prototypes, some weird people prefer
void
bar (void)
// to
void bar(void)

While you can generally assume that if in front of function name are some A-Z characters, then it's very likely definiton/declaration.
Actually when it comes to ifblocks, then placing the brace has very big impact on debugging code in Visual Studio 200x. When it steps into function/block, it will place text/execution line cursor on opening bracket. So if the bracket happens to be waaaaay on the right side, the code window has to scroll there and buggeritall stays there. Extremely annoying.


text:
Q: Dynamic IN+IF clause with GROUP_CONCAT? I am filtering buyers (many) for a given property (one) with the main condition of

*

*if the buyer requires specific exact # of bathrooms (buyers.bathroom_exact='1'), match it to the property's bathroom value.

Buyers can select multiple exact bathroom matches. Here's a sample schema:
CREATE TABLE `buyers` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `bathroomreq` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `buyers_bathrooms` (
  `buyer_id` int(10) unsigned NOT NULL DEFAULT '0',
  `number` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `buyers` ( name, bathroomreq ) VALUES ( 'John Doe', 1);
INSERT INTO `buyers` ( name, bathroomreq ) VALUES ( 'John Smith', 1);

INSERT INTO buyers_bathrooms ( buyer_id, number ) VALUES ( 1, 8 );
INSERT INTO buyers_bathrooms ( buyer_id, number ) VALUES ( 1, 9 );
INSERT INTO buyers_bathrooms ( buyer_id, number ) VALUES ( 1, 10 );
INSERT INTO buyers_bathrooms ( buyer_id, number ) VALUES ( 2, 5 );

The only way I can think of doing this is using a column which has an IF clause to see if the bathroomreq is 1, then match the group_concat of the buyers specified bathrooms:
SELECT IF ( bathroomreq = '1', 8 IN (
    SELECT GROUP_CONCAT(number) AS bathrooms
    FROM buyers_bathrooms
    WHERE buyers.id = buyers_bathrooms.buyer_id
) , 1 ) AS bathroom_match,

bathroomreq,

id, name

FROM buyers

So this property basically has 8 bathrooms and that's why 8 is hardcoded in there.
Here's a mysql fiddle:
http://sqlfiddle.com/#!2/508cc/1
Is this the only way of solving the problem and is it reliable? Can I do it an alternative way with something like a dynamic INNER JOIN if bathroomreq is 1? Basically, can I avoid having to branch based on bathroom_match in my application code and filter this elegantly through SQL alone?

A: I think you can do what you want with an exists clause:
select b.bathroomreq, b.id, b.name,
       (b.bathroomreq <> 1 or
        exists (select 1
                from buyers_bathrooms bb
                where bb.buyer_id = b.id and bb.number = 8
               )
       ) as bathroom_match
from buyers b;


text:
Q: Check if the Google Maps application is installed on the device I am trying to access the Google Maps appication from an IBM Worklight application by the following command line:
geo:37.786971,-122.399677

Is there any way to find out if the Google Maps application (or any map client application) exist on the mobile device?

A: Yes, You can write a Cordova plug-in in Worklight that will check whether Google Maps (or any other application) is installed or not.
** The Worklight Getting Started website is down, but for now you can get the same information in the IBM Worklight Information Center.


text:
Q: Issue Firefox text-overflow:ellipsis on child element With a parent div and a child div

        Oportunum est, ut arbitror, explanare nunc causam.

Using text-overflow: ellipsis on the div parent
.div-parent {
    border: solid 1px black;
    width: 200px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.div-child {
    display: inline-block;
}

On Chrome, the text is truncated and '...' are added as wanted.
But on Firefox, the text is only truncated...
fiddle
Any Ideas ?

A: I think Firefox is doing the right thing because technically the child div is set to inline-block so it will fit its content and it will overflow the parent element. So the inline-block is overflowing not the text.
You should make the child width:100% to have a text overflow and move the properties to the child div:

.div-parent {
  border: solid 1px black;
  width: 200px;
  white-space: nowrap;
}
.div-child {
  display: inline-block;
  width:100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

    Oportunum est, ut arbitror, explanare nunc causam, quae ad exitium praecipitem Aginatium inpulit iam inde a priscis maioribus nobilem, ut locuta est pertinacior fama. nec enim super hoc ulla documentorum rata est fides.


text:
Q: Soccer query - How to extract these data? I have a Soccer website, and I have a calendar of the match organized in this MySql table (called calendario) :
TEAM1   TEAM2   V1  V2   DAY   ID_SEASON

team1 | team2 | 3 | 1 | day1 | 1
team3 | team4 | 1 | 2 | day1 | 1
team1 | team4 | 0 | 0 | day2 | 1
team3 | team2 | 4 | 2 | day2 | 1
team1 | team3 | 2 | 3 | day3 | 1
team4 | team2 | 0 | 1 | day3 | 1
team1 | team2 | 3 | 1 | day1 | 2
team3 | team4 | 1 | 2 | day1 | 2
team1 | team4 | 0 | 0 | day2 | 2
team3 | team2 | 4 | 2 | day2 | 2
team1 | team3 | 2 | 3 | day3 | 2
team4 | team2 | 0 | 1 | day3 | 2

and I extract my result with this (long) query :
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3)  +
(sum(if(punteggio=3 and dove = 'T',1,0)) *  2)  -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario
union all
select team2 as squadra, v2 as fatti,v1 as subiti,'T',
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
) as tab
group by squadra
order by punti desc

unfortunatly, this extract ALL result from that table.
In fact I need to extract only results of the season 2 (ID_SEASON=2).
How can I do it?

A: Try with:
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3)  +
(sum(if(punteggio=3 and dove = 'T',1,0)) *  2)  -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
( select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario WHERE ID_SEASON = 2 )
union all
( select team2 as squadra, v2 as fatti,v1 as subiti,'T',
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
WHERE ID_SEASON = 2 )
) as tab
 group by squadra
order by punti desc

A: My request:
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3)  +
(sum(if(punteggio=3 and dove = 'T',1,0)) *  2)  -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove, ID_SEASON,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario
union all
select team2 as squadra, v2 as fatti,v1 as subiti,'T' as dove, ID_SEASON,
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
) as tab
where ID_SEASON = 2
group by squadra
order by punti desc


text:
Q: can you get a count on matches in a list comprehension (trying to insertionSort on a qsort after threshold) I come from a C++ background so I'm not sure if I'm even going about this properly. But what I'm trying to do is write up quick sort but fallback to insertion sort if the length of a list is less than a certain threshold. So far I have this code:
insertionSort :: (Ord a) => [a] -> [a]
insertionSort [] = []
insertionSort (x:xs) = insert x (insertionSort xs)

quickSort :: (Ord a) => [a] -> [a]
quickSort x = qsHelper x (length x)

qsHelper :: (Ord a) => [a] -> Int -> [a]
qsHelper [] _ = []
qsHelper (x:xs) n
    | n <= 10 = insertionSort xs
    | otherwise =  qsHelper before (length before) ++ [x] ++ qsHelper after (length after)
        where
            before = [a | a <- xs, a < x]
            after = [a | a <- xs, a >= x]

Now what I'm concerned about is calculating the length of each list every time. I don't fully understand how Haskell optimizes things or the complete effects of lazy evaluation on code like the above. But it seems like calculating the length of the list for each before and after list comprehension is not a good thing? Is there a way for you to extract the number of matches that occurred in a list comprehension while performing the list comprehension?
I.e. if we had [x | x <- [1,2,3,4,5], x > 3] (which results in [4,5]) could I get the count of [4,5] without using a call to length?
Thanks for any help/explanations!

A: Short answer: no.
Less short answer: yes, you can fake it. import Data.Monoid, then
    | otherwise =  qsHelper before lenBefore ++ [x] ++ qsHelper after lenAfter
        where
            (before, Sum lenBefore) = mconcat [([a], Sum 1) | a <- xs, a < x]
            (after, Sum lenAfter) = mconcat [([a], Sum 1) | a <- xs, a >= x]

Better answer: you don't want to.
Common reasons to avoid length include:

*

*its running time is O(N)

*

*but it costs us O(N) to build the list anyway

*it forces the list spine to be strict

*

*but we're sorting the list: we have to (at least partially) evaluate each element in order to know which is the minimum; the list spine is already forced to be strict

*if you don't care how long the list is, just whether it's shorter/longer than another list or a threshold, length is wasteful: it will walk all the way to the end of the list regardless

*

*BINGO

isLongerThan :: Int -> [a] -> Bool
isLongerThan _ []     = False
isLongerThan 0 _      = True
isLongerThan n (_:xs) = isLongerThan (n-1) xs

quickSort :: (Ord a) => [a] -> [a]
quickSort []     = []
quickSort (x:xs)
    | not (isLongerThan 10 (x:xs)) = insertionSort xs
    | otherwise =  quickSort before ++ [x] ++ quickSort after
        where
            before = [a | a <- xs, a < x]
            after = [a | a <- xs, a >= x]

The real inefficiency here though is in before and after. They both step through the entire list, comparing each element against x. So we are stepping through xs twice, and comparing each element against x twice. We only have to do it once.
            (before, after) = partition (< x) xs

partition is in Data.List.

A: No, there is no way to use list comprehensions to simultaneously do a filter and count the number of found elements. But if you are worried about this performance hit, you should not be using the list comprehensions the way you are in the first place: You are filtering the list twice, hence applying the predicate <x and its negation to each element. A better variant would be
(before, after) = partition (< x) xs

Starting from that it is not hard to write a  function
partitionAndCount :: (a -> Bool) -> [a] -> (([a],Int), ([a],Int))

that simultaneously partitions and counts the list and counts the elements in each of the returned list:
((before, lengthBefore), (after, lengthAfter)) = partitionAndCount (< x) xs

Here is a possible implementation (with a slightly reordered type):
{-# LANGUAGE BangPatterns #-}
import Control.Arrow

partitionAndCount :: (a -> Bool) -> [a] -> (([a], [a]), (Int, Int))
partitionAndCount p = go 0 0
    where go !c1 !c2 [] = (([],[]),(c1,c2))
          go !c1 !c2 (x:xs) = if p x
                              then first (first (x:))  (go (c1 + 1) c2 xs)
                              else first (second (x:)) (go c1 (c2 + 1) xs)

And here you can see it in action:
*Main> partitionAndCount (>=4) [1,2,3,4,5,3,4,5]
(([4,5,4,5],[1,2,3,3]),(4,4))


text:
Q: AssertionError occurs to file not found when executing train.py I am trying to execute python train.py within Anaconda prompt but I am receiving numerous line text and an AssertionError: File not found: div2.yaml.
As you can see my div2.yaml file is based on the coco128 thats linked to my datasets photos and validation.
python train.py --img 640 --batch 16 --epochs 3 --data div2.yaml --weights yolov5s.pt
I tried to Upload more screen prints to show the file directories, but it wont allow me.
The div2.yaml file is located in C:\Users\Marti\Desktop\yolov5\Data.
I have tried entering the full directory into the code but I have the same outcome.
I am not sure what is wrong, if someone can help
Thanks


text:
Q: doe's any one know how to use agoraRTC TokenGenerator in android? I followed this documenttation and applied each instruction correctly. I placed the files in the /src folder. but when I tried to import the files it doesn't work correctly as it says.
import io.agora.media.RtcTokenBuilder;
import io.agora.media.RtcTokenBuilder.Role;

it shows error in io.agora.media part. I don't know how to import from the /src folder any help?

A: i have solved it !
in the documentation it says to place the folder in src of project mode. i have tried but it didn't work. so i placed the io directory in normal java package in app mode.
 implementation "commons-codec:commons-codec:1.11"

i have added above library in my project and all works fine


text:
Q: Javascript - move/drag icons to table I am trying to like 10x10 table where I can drag images to each another.
Does anybody have an idea how this can be accomplished using JavaScript? I have already tried something with Dragula but it didn't work well.
This is what I want to work in real time:

A: You can add the
draggable="true"

attribute to the html elements.
If that doesn't help then try checking out W3Schools.
You can also check out Mozilla
Hope this helps.


text:
Q: Aligning text in S columns in a way that respects the decimal marker for numerical entries As I understand it, using various options for the S column in siunitx, I may produce columns containing both numerical and nonnumerical entries. I may have the numerical entries aligned at their decimal points. I may have the text entries either left-, right-, or center- justified with respect to the column's width.
Is it possible to have the numerical entries aligned by their decimal, while controlling the text entries' alignment as it relates to the decimal marker?
To complicate things further, is it possible to apply alignments differently row by row? In particular, could I leave column-centered alignment for the head entry of a column, while making my special decimal marker-based alignment apply to later entries?
The following MWE sort of produces what I want with exaggerated numbers, but I have manually forced some space in the last two entries to make it happen. I want to not have to do this.
\documentclass{article}

\usepackage{siunitx}

\newcommand*\heading[1]{\multicolumn{1}{c}{#1}}

\begin{document}

\begin{tabular}{S[table-format=9.3,table-text-alignment=center]}
\hline
\heading{Title}\\
\hline
1\\
2.000\\
6\\
24.0\\
123456789\\
{\phantom{123\,456\,78}\vdots\phantom{\,000}}\\
{\phantom{123\,456\,7}$f(n)$\phantom{\,00}}
\end{tabular}

\end{document}

Note that I do want a centered title, and that ideally I actually want the remaining text entries centered with respect to a point that is roughly 0.5\ex to the left of the decimal marker. Also, note that since I have such asymmetry between integer an fractional parts, I do not think that table-number-alignment=center-decimal-marker is helpful.

A: Let me say two things before:

*

*This is not an only-siunitx solution. Sadly, table-text-alignment doesn't take decimal-marker :(

*I provide two macros:

*

*\widestparts{<digits before …>}{<… and after decimal marker>}†

*\tcenter{<text to center at the decimal marker>}

† This works now, thanks to Peter Grill's question, Martin Scharrer's answer and Peter's hint in the chat.
Manual aligning
You can add another \textcenter macro that takes three arguments:

*

*stuff before your actual text,

*stuff after your actual text (in the example below I also removed the decimal marker .), and

*stuff that gets actually typeset.

For example:
\newcommand*{\textcenter}[3]{{%
    \hphantom{\num{#1}}%
    \makebox[\widthof{.}][c]{#3}\hspace{-\decimalmarkerwidth}%
    \hphantom{\num[add-decimal-zero = false,add-integer-zero = false,scientific-notation = fixed]{#2}}%
}}

Code
\documentclass{article}
\usepackage{xcolor} % only for this example (redefinition of hphantom}
\usepackage{mathtools,calc,siunitx,ifthen}
\usepackage[T1]{fontenc}
% getting the width of the decimal marker: . or ,
\newlength{\decimalmarkerwidth}\settowidth{\decimalmarkerwidth}{.} % or ,

% remove the % in the next line to get gray phantoms
%\renewcommand\hphantom[1]{{\color[gray]{.7}#1}}

\newcommand*\heading[1]{\multicolumn{1}{c}{#1}} % not used anymore ... (but can used (without the multicolumn) for other formatting (bf, color, ...)

\makeatletter
\newcounter{alex@auxctr} % (Internal)

% \widestparts takes two arguments: #1 = number of digits before the decimal marker
                                  % #2 = number of digits after the decimal marker
\newcommand*{\widestparts}[2]{%
    \alex@widestpartauxloop{\alex@widestpartleft}{#1}{9}%
    \alex@widestpartauxloop{\alex@widestpartright}{#2}{0}%
}

% (Internal) \alex@widestpartauxloop loops over #2 and adds #2 times #3 to #1.
\newcommand*{\alex@widestpartauxloop}[3]{%
    \def\alex@WidestPartTemp{}\setcounter{alex@auxctr}{0}%
    \whiledo{\value{alex@auxctr}<#2}{\g@addto@macro\alex@WidestPartTemp{#3}\stepcounter{alex@auxctr}}%
    \xdef#1{\alex@WidestPartTemp}%
}

% \tcenter takes one argument: #1 = actual text that should be typeset
\newcommand*{\tcenter}[1]{{%
    \hphantom{\num{\alex@widestpartleft}}%
    \makebox[\widthof{.}][c]{#1}\hspace{-\decimalmarkerwidth}%
    \hphantom{\num[add-decimal-zero = false,add-integer-zero = false,scientific-notation = fixed]{.\alex@widestpartright}}%
}}
\makeatother

\usepackage{booktabs} % for \top-, \mid- and \bottomrule

\begin{document}
\widestparts{9}{3}
\begin{tabular}{S[table-format=9.3,table-text-alignment=center]}
    \toprule
             \tcenter{Title}            \\ \midrule
                    1                   \\
                  2.000                 \\
                    6                   \\
                   24.0                 \\
                123456789               \\
    \tcenter{$\smash{\vdotswithin{.}}$} \\ % \smash is used to hide the oversized vertical height of \vdots
             \tcenter{$f(n)$}           \\ \bottomrule
\end{tabular}
\end{document}

Output


text:
Q: Alias Dimension member value in SSAS Is it possible to display or return a different value for an attribute in SSAS?
For example, in my date dimension I derive the business day within the month. Something like this:
    DateId          Date            BusinessDay         WeekDay
    20120101        2012-01-01      01                  Mon
    20120102        2012-01-02      02                  Tue
    20120103        2012-01-03      03                  Wed
    20120104        2012-01-04      04                  Thu
    20120105        2012-01-05      05                  Fri
    20120106        2012-01-06      05                  Sat
    20120107        2012-01-07      05                  Sun
    02120108        2012-01-08      06                  Mon

But the problem is every month has a 01 BusinessDay in it, so when I am creating a hierarchy for this, I get an error for duplicates. Also on the weekends I keep the business day constant.
So I need a way to have a unique BusinessDay value, but show a user friendly value. I was thinking I could concatenate the DateId + BusinessDay, but with an expression only show the Right 2 characters.
Making 2012010101 display as 01
Is this even possible? Maybe in the attributes properties somewhere?

A: I was able to accomplish this by doing the following:
I added two columns to the DSV. One for the value to be displayed, and a second for the true value. Next, I opened the Design view of the date dimension and added the attribute relationship just like adding any new attribute.
Now to make this work you have to open the attribute properties. and scroll all the way to the bottom and under the Source options update the KeyColumns to the actual value attribute. Next, in the same Source Options, update the NameColumn to the Display value you want.
It's actually pretty easy.


text:
Q: C# / WinAPI - Monitoring a Memory Region I was wondering if there is a way to monitor a particolar memory region for changes. I'm using the following method in order to open a process and obtain a collection of its used memory regions:
internal static MemoryProcess OpenProcess(Process process)
{
    IntPtr processHandle = OpenProcess(ProcessAccess.Desided, true, (UInt32)process.Id);

    if (processHandle == IntPtr.Zero)
        return null;

    IntPtr processAddress = new IntPtr();
    List<MemoryRegion> memoryRegions = new List<MemoryRegion>();

    while (true)
    {
        MemoryBasicInformation info = new MemoryBasicInformation();

        if (VirtualQueryEx(processHandle, processAddress, out info, MemoryBasicInformation.Size) == 0)
            break;

        if (info.Allocation.HasFlag(MemoryAllocation.Commit) && info.Type.HasFlag(MemoryType.Private) && ((info.Protection & MemoryProtection.Readable) != 0) && ((info.Protection & MemoryProtection.Protected) == 0))
            memoryRegions.Add(new MemoryRegion(info.BaseAddress, info.RegionSize));

        processAddress = new IntPtr(info.BaseAddress.ToInt64() + info.RegionSize.ToInt64());
    }

    if (memoryRegions.Count == 0)
    {
        CloseHandle(processHandle);
        return null;
    }

    return (new MemoryProcess(processHandle, memoryRegions));
}

I saw a lot of applications doing this. Cheat Engine is one of them. Let's say I open a Google Chrome Tab process and I search and find a specific value (the string "stackoverflow") within it's memory:

Now, i use that tab to browse another, completely different, website and I see those address values changing:

Last step: I close that Chrome tab killing its corresponding process:

So... of course there MUST be a sort of monitoring for memory regions. And, in fact, there is:

Using Process.Exited event is not enough to achieve a real time update of memory addresses values I think... so, how can I do that?

A: If you can intercept VirtualAlloc called in target application, and combined MEM_WRITE_WATCH to original flags, system will keep track of this allocated memory region, then you can call the GetWriteWatch function to retrieve the addresses of the pages that have been written to since the region has been allocated or the write-tracking state has been reset. This looks a lot of work to do though.


text:
Q: Message sent from .net System.Net.Mail is not visible on BlackJack II Windows Mobile I'm sending a message from my ASP.net page to an email account, the message is sent properly and is viewable in Thunderbird or any other email client I use.
But I can not view the message text in my Windows Mobile 6.1 (BlackJacK II) device, I've played around with setting
    msg.BodyEncoding = System.Text.Encoding.Unicode;

or
    msg.BodyEncoding = System.Text.Encoding.UTF8;

or even
    msg.BodyEncoding = System.Text.Encoding.ASCII;

but none of these work and message body is simply not visible on the device.
the code to send the message is below
Where Body is an ASP.net TextBox control
 try
  {
    MailMessage msg = new MailMessage("test@test.com", "test@test.com");
    msg.Subject = "[TestProduct - TestPage.aspx]";
    msg.Body = Body.Text;
    msg.IsBodyHtml = true;
    SmtpClient sc = new SmtpClient("localhost");
    sc.Send(msg);
    txtMsg.Text = "Thank you for contacting TestCompany Inc someone will contact you promptly.";
  }
  catch
  {
    txtMsg.Text = "Unable to send your message at this time, Please try again later. Sorry for inconvineance.";
  }

When the IsBodyHtml = false and I do not set the Encoding these are the headers that I receive
From - Tue Jun 09 11:48:23 2009
Received: from chronos ([127.0.0.1]) by chronos.lunarpages.com with MailEnable ESMTP; Tue, 09 Jun 2009 11:45:09 -0700
MIME-Version: 1.0
From: Removed
To: Removed
Date: 9 Jun 2009 11:45:09 -0700
Subject: [TestProduct - TestPage.aspx]
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
Return-Path: <Removed>

test this message

and still I'm unable to see it in device.

A: Just as a test, I'd try:

*

*don't set IsBodyHtml at all

*set Subject to "foo" (that literal string)

*set Body to "bar" (that literal string)

that should give the simplest mail - if it works, change one thing at a time until it breaks :)

A: Check to make sure the blackjack is set to receive HTML emails.

A: I feel its the issue with your Mobile device. Did you try another device? Which browser are you using? Check your browser settings.

A: The mail client on the BlackJack probably cannot display HTML messages.  Most email programs generate plain-text versions of the messages that they send.  However, System.Net.Mail.SmtpClient does not do this automatically.
You can create an AlternateView object with a plain text version of the message by like this
string plainTextVersion = //...
msg.AlternateViews.Add(AlternateView.CreateFromString(plainTextVersion, null, "text/plain");
msg.AlternateViews.Add(AlternateView.CreateFromString(Body.Text, null, "text/html");

EDIT: If the device can display HTML messages, this won't solve the problem.

A: Can you view the raw message on the mobile device? If so, I'd post it for some of the experts here. it would help greatly to see what's MIME parts the device attempting to render.


text:
Q: Multiple instances of the same subscriber on different machines I am trying to implement the publisher subscriber pattern using Nservice bus , what i am trying to do is as follow :
I have web application , user can write news and add documents to that Application using his account .
I have a Windows forms desktop application that running on users machines , they can login this desktop app using the same credentials they are using to access the web application.
what i need to to is when users on web applications add news or documnets , the installed desktop app should receive notifications to informing it about this added news .....
i imagin that my desktop application will be the subscriber that will subscribe on events that will be published from the server
what i need to know is
when multiple users for example 1000 user , install this desktop app on different machines to start using it , in this case Nservice bus will consider them as multiple subscribers and will send a copy of message to each one of them or what ???

A: As described in the documentation, it works like this:

*

*If you use Send(ICommand command), you get message sent directly to the matching target. In this case, if you have multiple consumers, they will compete to get this message and only one gets it. This is usually used to scale applications.

*If you do Publish(IEvent @event), your message will get delivered to all subscribers.

A: When Pub/Sub happens in NServiceBus, there is one logical publisher that sends an event to multiple logical subscribers. Each logical subscriber will only receive one copy of each event that is published.
If many subscribers represent the same logical entity then each event will be processed by only one of the subscribers within that logical entity. Two subscribers are considered to represent the same logical entity if they share an Endpoint Name.
In this case, if every instance of the desktop application have the same endpoint name then they are considered to represent the same logical entity.  When an event is published, then only one of those desktop application instances will get a copy of the event. That is probably not what you want.
If you give each instance of the desktop application a different endpoint name then they each represent their own logical entity. When an event is published, all of the desktop instances will get a copy of the event. That is also probably not what you want.
Another thing to consider is pub/sub in NSB is persistent and reliable. If you start a desktop application and it sets up a subscription, that subscription is in effect even if the desktop application is offline. Messages may be queued up waiting for the Desktop Application to come back online to be processed, even if you never run the desktop application again. Does your desktop application need these or do you only care about events that occur while you are connected?
If you want to notify a specific subscriber or subset of subscribers that are online when an event occurs on the server then I would use SignalR before using NSB.
Additional Info

MSMQ and SQL Server do not support pub-sub out of the box and so they use a feature called message driven-subscription. Message driven subscriptions work by having the subscriber send a message to the publisher when it starts up (or calls Subscribe()). This message contains a Reply To header which the publisher stores and uses to send copies of each message that is published.
For SQL Server transport, the Reply To address will be the name of the Endpoint. This in turn is mapped to a table in the database that represents the queue of messages. If multiple subscribers share the same Endpoint name (and hence the same table) then they will get one copy of the event between them and will be competing to see which subscriber pulls it from the queue.
For MSMQ, the Reply To address will be the name of the Endpoint and the name of the machine separated by an @ symbol. This means that each subscription will be for a different address. When the event is published, each subscriber will get it's own copy of it. If multiple subscribers represent the same logical entity (i.e. share an Endpoint name), then you should have a distributor in front of them. When you do this then the Reply To header on outgoing subscribe messages will be the address of the Distributor. When an event is published, it will always go to the Distributor which will hand it off to one (and only one) of it's workers for processing.
Rabbit MQ and Azure Service Bus have built-in mechanisms for pub/sub but they will behave in a manner similar to SQL Transport. One instance of the logical subscriber will get a copy of the event.


text:
Q: How to get the paremeters when I have a given data and formula in r? I have a data frame like below,
structure(list(`Plot No.` = c(11, 12, 13, 14, 21, 22, 11, 12, 13, 14, 21, 22, 23, 11, 12, 13, 14, 21, 22, 23), Sample_ID = c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7), Treatment = c("A", "D", "TD", "T", "CO2", "DCO2", "A", "D", "TD", "T", "CO2", "DCO2", "TCO2", "A", "D", "TD", "T", "CO2", "DCO2", "TCO2"), T = c(5, 5, 5, 5, 5, 5, 15, 15, 15, 15, 15, 15, 15, 25, 25, 25, 25, 25, 25, 25), `R (µg CO2-C/g dry soil/hr)` = c(0.0224577914447771, 0.0179442829609729, 0.02688584916844, 0.0330002622240527, 0.0567148195871392, 0.0355053037352641, 0.0778264447670878, 0.0716472116716462, 0.119423848928993, 0.148338665254101, 0.190316253331465, 0.132496405855809, 0.0977254791656324, 0.241058563330705, 0.241395505291938, 0.341614787593164, 0.461344596068699, 0.585524319295799, 0.383691841463553, 0.31883194104183)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

I also have a formula for these data to fit, which is:
R= a*exp^(b*T)   (1)
Q10=exp^(10*b)   (2)

I want to calculate the values of Q10, so firstly, I need to get the values of coefficients a and b through the given dataset of R and T. Then using the parameter b to calculate Q10.
I don't really know how to realize this in R. Hope some could give me some hints. Thanks!

A: You can solve this with nls (Nonlinear Least Squares), since the model you describe is not linear. First, I rename R (µg CO2-C/g dry soil/hr) to R.
df <- structure(list(`Plot No.` = c(11, 12, 13, 14, 21, 22, 11, 12, 13, 14, 21, 22, 23, 11, 12, 13, 14, 21, 22, 23), Sample_ID = c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7), Treatment = c("A", "D", "TD", "T", "CO2", "DCO2", "A", "D", "TD", "T", "CO2", "DCO2", "TCO2", "A", "D", "TD", "T", "CO2", "DCO2", "TCO2"), T = c(5, 5, 5, 5, 5, 5, 15, 15, 15, 15, 15, 15, 15, 25, 25, 25, 25, 25, 25, 25), `R (µg CO2-C/g dry soil/hr)` = c(0.0224577914447771, 0.0179442829609729, 0.02688584916844, 0.0330002622240527, 0.0567148195871392, 0.0355053037352641, 0.0778264447670878, 0.0716472116716462, 0.119423848928993, 0.148338665254101, 0.190316253331465, 0.132496405855809, 0.0977254791656324, 0.241058563330705, 0.241395505291938, 0.341614787593164, 0.461344596068699, 0.585524319295799, 0.383691841463553, 0.31883194104183)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

df$R <- df$`R (µg CO2-C/g dry soil/hr)`

Fit your model with nls (we have to provide it start values, I guessed these).
nlsfit <- nls(R ~ a*exp(b*T), data = df, start = list(a = 0.1, b = 0.1))

coefs <- coef(nlsfit)
coefs

#          a          b
# 0.02093579 0.11467305

Check the fit:
plot(df$T, df$R)
lines(df$T, coefs[["a"]]*exp(coefs[["b"]]*df$T))

And then we can calculate Q10
Q10 <- exp(10*coefs[["b"]])
Q10

# 3.147884


text:
Q: Evaluate $\int_{2}^{7} \frac{x}{1-\sqrt{2+x}} d x$ We have the following integral:
$$
\int_{2}^{7} \frac{x}{1-\sqrt{2+x}}\, dx
$$
And this is my solution, which seems to be wrong, and I am failing to see where exactly I failed at:
We have $u=1-\sqrt{2+x}, x=u^2-2u-1, dx=-2\sqrt{2+x}\, du$, and we know that $x\geq -2$ and thus $u\leq 1$:
\begin{align}
\int_{2}^{7} \frac{x}{1-\sqrt{2+x}}\, dx
&=-2\int_{-1}^{-2} \frac{(u^2+2u-1)(u-1)}{u}\, du\\
&= -2 \left( \int_{-1}^{-2} u^2 d u + \int_{-1}^{-2} u\, du +\int_{-1}^{-2} -3\, du + \int_{-1}^{-2} \frac{1}{u}\, du \right) \\
&= -2\left[\frac{u^3}{3}+\frac{u^2}{2}-3u+\ln{|u|}\right]_{-1}^{-2}\approx -18
\end{align}
Can someone please help me pinpoint the issue?

A: I would have calculated it like this:
Let $u=1-\sqrt{2+x} \Leftrightarrow x=(1-u)^2-2$ where $x\ge-2$. We then have
$$ \mathrm dx=2(1-u)(-1)\,\mathrm du$$
so
\begin{align*}
\int_2^7\!\frac{x}{1-\sqrt{2+x}}\,\mathrm dx
&=\int_{-1}^{-2}\!\frac{(1-u)^2-2}{u}\cdot2(1-u)(-1)\,\mathrm du
\\&=2\int_{-2}^{-1}\!\frac{((1-u)^2-2)(1-u)}{u}\,\mathrm du
\\&=2\int_{-2}^{-1}\!\frac{(1-2u+u^2-2)(1-u)}{u}\,\mathrm du
\\&=2\int_{-2}^{-1}\!\frac{(u^2-2u-1)(1-u)}{u}\,\mathrm du
\\&=2\int_{-2}^{-1}\!\frac{-u^3+3 u^2-u-1}{u}\,\mathrm du
\\&=2\int_{-2}^{-1}\!\Bigl(-u^2+3u-1-\frac{1}{u}\Bigr)\,\mathrm du
\\&=2\Bigl[-\frac13u^3+\frac32u^2-u-\ln(|u|)\Bigr]_{-2}^{-1}
\\&=-\frac{47}{3}+2\ln(2).
\end{align*}

A: The first thing I would like to point out is that since you want to do a substitution, it is really extra (unnecessary) work writing $dx$ in terms of $x$ (where the aim of substitution is to "get rid" of the initial variable and simplify the integral in the process).
With that out of the way, let $u = 1 - \sqrt {2 + x}$, then $x = u^2 - 2u - 1$ and $\mathrm{d}x = 2u - 2$.
Now, observe that, $\forall\ n \in \mathbb {R}$, $\sqrt n \geq 0$, so we note that $u \leq 1$.
\begin{align}
\int_{2}^{7} \frac x {1 - \sqrt {2 + x}}\ \mathrm {d}x & =
2\int_{-1}^{-2} \frac {(u^2 - 2u - 1)(u - 1)} u\ \mathrm {d}u
\\[5 mm] & =
2\int_{-1}^{-2} \frac {u^3 - 3u^2 + u + 1} u\ \mathrm {d}u
\\[5 mm] & =
2\left[\frac {u^3} 3 - \frac {3u^2} 2 + u + \ln|u|\right]^{-2}_{-1}
\\[5 mm] & =
2\ln 2 -\frac {47} 3
\end{align}

A: exactly, when you have $u=1-\sqrt{2+x}\ => x=u^2-2u-1$
Then $du=2(u-1)dx$
Plugging it into your formula we get
$=2\int\ \frac{(u^2-2u-1)(u-1)}{u}$


text:
Q: Should I trash old CS6 programs before reinstalling CS6 on same disc? After experiencing hardware problems on a MacMini, I need to reinstall CS6 on the internal SSD. I used Utilities/Adobe/CS6 installer to uninstall CS6 programs. These remain on the SSD but are now inoperable. Is it advisable to manually remove and trash these old CS6 program files on SSD (freeing up disc space) before reinstalling from original CS6 DVD?

A: Er... in answer to my own question, I came upon the Creative cloud cleaner tool at https://helpx.adobe.com/creative-cloud/kb/cc-cleaner-tool-installation-problems.html, followed instructions and cleared all old adobe CS applications before reinstalling CS6.


text:
Q: Office 2011 mac / Exchange contacts We have Exchange 2010 SP2 running in our environment and a whole bunch of Mac office 2011 users.
Recently, we had a new hire start and two of the mac office 2011 users (OSX Lion) noticed he's not showing up when they search for him in the global address list. If you search within OWA or Office 2010 for Windows, he shows up. It's just the mac Office 2011 users.
Anyone have any idea why this might happen?
Thanks!

A: Not sure what you mean. If the user is a configured Exchange/AD user, they're going to be available in the GAL.
If you're saying that there are problems searching for the user within Office 2011, then that's more of a problem with the Macintosh client.
See: https://superuser.com/questions/212754/global-address-list-in-outlook-2011-for-mac
But the official word from Microsoft is that the GAL is not searchable as it was in Entourage. Autofill from the To: form still works, though.
You can also add a "Directory Service" account in Outlook 2011 and enter your LDAP information to get something closer.


text:
Q: magento2 how to add product grid in ui form using ui component Magento 2 : How to add a product grid in custom module using ui component?
this refreance is not work me it is display look like layout grid

A: The following reference adds the productgrid in uiform
https://www.rohanhapani.com/magento-2-how-to-add-product-grid-in-ui-form-using-uicomponent/


text:
Q: R - plot overlapping time intervals I have a list of people and their working start and end times during a day. I want to plot a curve showing the total of people working at any given minute in the day. What I could do is just add 1440 additional conditional boolean variables for each minute of the day and sum them up, but that seems very inelegant. I'm wondering if there a better way to do it (integrals?).
Here's the code to generate a df with my sample data:
sample_wt <- function() {

    require(lubridate)

    set.seed(10)

    worktime <- data.frame(
            ID = c(1:100),
            start = now()+abs(rnorm(100,4800,2400))
            )

    worktime$end <- worktime$start + abs(rnorm(100,20000,10000))

    worktime$length <- difftime(worktime$end, worktime$start, units="mins")

    worktime
}

To create a sample data , you can do something like:
DF <- sample_wt()

A: Here one option using  IRanges package from Bioconductor.
library(IRanges)
## generate sample
DF <- sample_wt()
## create the range from the sample data
rangesA <- IRanges(as.numeric(DF$start), as.numeric(DF$end))
## create one minute range
xx = seq(min(DF$start),max(DF$end),60)
rangesB <- IRanges(as.numeric(xx),as.numeric(xx+60))
## count the overlaps
ov <- countOverlaps(rangesB, rangesA, type="within")
## plot the result
plot(xx,ov,type='l')

A: Surely it can be improved, but this seems to do it:
time_range <- seq(min(DF$start), max(DF$end), 60)
result <- integer(length(time_range))
for (t in seq_along(time_range)) {
  result[t] <- sum(DF$start <= time_range[t] & DF$end >= time_range[t])
}

A: I don't have lubridate installed, so I produced the data.frame through Sys.time instead of now (guess they should be similar). This could make the trick:
    minutes<-seq(as.POSIXct(paste(sep="",Sys.Date()," 00:00:00")),by="min",length.out=24*60)
    rowSums(outer(minutes,worktime$start,">") & outer(minutes,worktime$end,"<"))


text:
Q: Flattening with missing or no results I am pretty new to Bigquery and I would like to unnest 2 tables in one query.
I tried to query below code but it did not work. It gave me this message: "This query returned no results".
SELECT
    timestamp AS Date,
    A.key,
    B.name
FROM `pms_table_request_log.partners_request_log_*`,
     UNNEST(jsonPayload.response.body.channels) AS A,
     UNNEST(jsonPayload.response.body.data.rows) AS B;

I expect key and name to be unnested.

A: If with unnesting you mean to "flatten", which means to bring data from array fields to top level, you can try LEFT JOIN instead of CROSS JOIN (which is the comma)
SELECT timestamp AS Date ,A.key ,B.name
FROM pms_table_request_log.partners_request_log_*
  LEFT JOIN UNNEST(jsonPayload.response.body.channels) AS A
  LEFT JOIN UNNEST(jsonPayload.response.body.data.rows) AS B

If any of the array is empty, CROSS JOIN would destroy the whole row while LEFT JOIN preserves the left "table"


text:
Q: How to keep data history in mysql? I saw many threads asking about keeping history of records in mysql. However, I'm not quite sure they are suitable with my case.
I'm developing an application form with a lot of user information. So far, I have to normalize it into 12 tables even though most of them have 1:1 relations but I though they would be good in the future use:

*

*User (Id, Fullname, Username, Email, CreatedDate, UpdatedDate, ...)

*Family (Id, UserId, Name, Relation, Job, ...)

*Address (Id, UserId, Road, District, Province, ...)

*...

When clients filled all the fields in the form, they have two options, firstly, they can save it as draft, secondly, they can confirm sending the application and can't change it anymore.
I have done some research so far. They are many ways to do it. For example, I could duplicate all the tables with some additional fields; VersionId. However due to the enormous number of tables, I don't think it's a good idea.
So, what I think is to add VersionId to each existing tables. When they save the form as draft, I would just put the information without touching the VersionId field, however, I would increase VersionId by 1 whenever the user confirm submitting the application.
Any suggestion would be really welcomed.

A: Add a status column to each table. It can have the values draft, current, and history.
When the user makes a change to their data, create a new row with status = draft. As they edit, you modify that row. When they confirm the changes, you set the old current row's status to history, and set the draft row's status to current.

A: I think it mainly depends on the business requirement (since it doesn't sound like there would be so many updates for the same user I am assuming that performance is not a concern but you may want to think about that too since an insert in this case is cheaper than an update).
So the question you need to ask yourself is does the business require that you keep the history or not? for example if user A fills out the form, and later on he updates some of the information e.g. he has a new address, do you want to be able to know what were his previous addresses or not? If you do then you have to store them (I would add the date of the change in addition to the version id)


text:
Q: Increasing form input width for a position absolute element in Bootstrap 3 I'm trying to increase the width of an input element of a form group in Bootstrap 3. As per this answer I can control the width by applying the col property to the div containing the input element.
The form has position absolute and I think that's what's stopping it from changing the width. Removing the position absolute allows me to increase the width. How can I increase the width of the element?
Here is my code
<form id="search_bar" class="navbar-form navbar-left">
    <div class="form-group col-md-6" id="dj-search">
        <input type="text" class="form-control typeahead" placeholder="Search favourite DJs" autocomplete="off">
    </div>
</form>

Here is a JSFiddle for the same.

A: Set the width of your two .form-control class to the value you want.

A: You probably should add 'left' with 'right'. Like this. Adjust width with left and right.
#search_bar {
  position: absolute;
  right: 40px;
  left:40px;
}

Here is your fiddle with changes made


text:
Q: How to gain shell access when I'm locked out with "PTY allocation request failed on channel 0" I installed gitosis on a remote shell. It's working fine. But now I can't login to the interactive shell. As told here, it seem gitosis disabled tty. Is there anyway I can get it back? I don't have root access to the remote server.

A: You may be able to login if you make your ssh client not ask for a tty, probably by using the -T flag.
e.g.
ssh -T remotehost

You will not get a shell prompt, the normal editing keys will not work, and you won't be able to use full screen programs such as vi, emacs or less, but you will be able to run simple shell commands.
I don't know how to re-enable the tty though, sorry.


text:
Q: Почему oracle distributed transaction не блокирует таблицы? Вот такой распределенный комит по 2х фазному протоколу:
public static void main( String[] args ) throws SQLException, XAException {
    OracleXADataSource dataSource1 = new OracleXADataSource();
    dataSource1.setURL("jdbc:oracle:thin:@//localhost:1521/XE");
    dataSource1.setUser("system");
    dataSource1.setPassword("111");

    OracleXADataSource dataSource2 = new OracleXADataSource();
    dataSource2.setURL("jdbc:oracle:thin:@//localhost:1521/XE");
    dataSource2.setUser("alex");
    dataSource2.setPassword("111");

    XAConnection xaConnection = dataSource1.getXAConnection();
    XAResource res = xaConnection.getXAResource();
    Connection connection = xaConnection.getConnection();
    FooXid xid1 = new FooXid(1);
    res.start(xid1, XAResource.TMNOFLAGS);
    connection.createStatement().execute("INSERT INTO TABLE1 VALUES (1)");
    res.end(xid1, XAResource.TMSUCCESS);

    XAConnection xaConnection2 = dataSource2.getXAConnection();
    XAResource res2 = xaConnection2.getXAResource();
    Connection connection2 = xaConnection2.getConnection();
    FooXid xid2 = new FooXid(2);
    res2.start(xid2, XAResource.TMNOFLAGS);
    connection2.createStatement().execute("INSERT INTO TABLE1 VALUES (2)");
    res2.end(xid2, XAResource.TMSUCCESS);

    int verdict = res.prepare(xid1);
    int verdict2 = res2.prepare(xid2);

    if (verdict == XAResource.XA_OK)
        res.commit(xid1, false);//breakpoint1

    if (verdict2 == XAResource.XA_OK)
        res2.commit(xid2, false);//breakpoint2

    xaConnection.close();
    xaConnection2.close();

    connection.close();
    connection2.close();
}

когда я дебагером дохожу до //breakpoint1 или //breakpoint2 и пробую выбрать из таблицы значения SELECT, то запрос проходит.
Но ведь таблица должна быть заблокированной согласно документации!


text:
Q: Install magento 2 extension without ssh I need to install several extensions. I don't have SSH to that host so I need to be able to do everything with FTP + magento 2 backend.
So far I've copied the extension files on the /app/ dir.
Looking at extension istructions i see this:
php bin/magento setup:upgrade
php bin/magento cache:flush
php bin/magento setup:static-content:deploy

There is a way to accomplish this in another way? Installing extensions in Magento feels really cumbersome and awkward compared to other CMS like Wordpress or Drupal.
Update
I found an article that suggests to do this:
Edit app/etc/config.php file and three line code:
'Ves_All' => 1,
'Ves_Megamenu' => 1,
'Ves_Setup' => 1,

But I have no clue what is that and I haven't found so far any info about those options.

A: Make a new php file Let say "updater.php" and paste following code in it (add php tags at start n end of file).
  system('php bin/magento setup:upgrade');
  system('php bin/magento cache:flush');
  system('php bin/magento setup:static-content:deploy');

We are using system() function to run PHP SSH commands.
Upload this file in your Web root and access it using
http://yourdomain/updater.php
You will see output of commands after few seconds

A: If you can upload file to your server, you can use my file to run magento command line

Realy sorry!I cannot upload php file here. So you can down it on this page http://www.mageoneplus.com/how-to-run-magento-command-line-without-ssh-access.html

 Welcome to ssh command line

        <?php
            if(isset($_SERVER['ORIG_PATH_INFO'])){
                $url = $_SERVER['ORIG_PATH_INFO'];
            }elseif(isset($_SERVER['PATH_INFO'])){
                $url = $_SERVER['ORIG_PATH_INFO'];
            }
        ?>
        <form action="<?php echo $url; ?>" id="mageoneplus-ssh" method="post" >

Example: php bin/magento

                <?php
                    $value = "php bin/magento ";
                    if(isset($_POST["command"]) && $_POST["command"]){
                        $value = $_POST["command"];
                    }
                ?>
                <input type="text" style="width:600;"  name="command" id="command"  value="<?php echo $value ?>"  placeholder="Enter command line here..." />

        </form>
        <button type="submit" form="mageoneplus-ssh" value="Submit">Run</button>

            <?php
                if(isset($_POST["command"]) && $_POST["command"]){

                    try{
                        $output = null;
                        set_time_limit(0);
                        $str = $_POST["command"];
                        exec($str, $output);
            ?>

The result:

                    <?php
                        foreach($output as $op){
                    ?>

<?php echo $op; ?>

                    <?php
                        }
                    ?>

            <?php

                    } catch (Exception $e) {
                        echo 'you must enable exec';
                    }
                }
            ?>

Written by Louis Pham


text:
Q: Appropiate way of managing fixed cells in a table view I have a grouped-style UITableView intended to show a fixed number of sections, each of one having in turn a fixed set of cells, similarly to Settings app. Some of the cells are custom and different between them: some of them have a textfield, another have a switch, another a button. I also have UITableViewCellStyleDefault cells.
Custom cells are loaded from nib files, and I've defined a strong property for each cell in the whole table view. My cellForRowAtIndexPath: method looks like this:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"cell"];

   if (cell == nil) {

      if (indexPath.section == 0) {

         if (indexPath.row == 2) {
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"TypeACell" owner:nil options:nil];
            for (UIView *view in views) {
               if ([view isKindOfClass:[UITableViewCell class]])
               {
                   cell = (TypeACell *)view;
               }
            }

            // set property
            self.typeARow = cell;
         }

        else {
           NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"TypeBCell" owner:nil options:nil];
           for (UIView *view in views) {
              if ([view isKindOfClass:[UITableViewCell class]])
              {
                 cell = (TypeBCell *)view;
              }
           }

           // set properties
           if (indexPath.row == 0) {
              self.typeBRow0 = cell;
           }
           else {
              self.typeBRow1 = cell;
           }
        }
     }

     else {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

        // set property
        self.defaultCell = cell;
     }
  }

  return cell;
}

For the custom cells, I've also set the reuse identifier to "cell" in their nib files. Is this the correct way to proceed when you know beforehand the set of cells for a table that represents for example a form or a menu, like Settings app? Does the reuse identifier be the same for all the cells, or should each different cell have its unique identifier?
Thanks!


text:
Q: PyQt4 application on Windows is crashing on exit I am writting a desktop application with PyQt4 and all of the sudden it started to crash on exit.
I reviewed all of my code to make sure I wasn't doing anything funny to make it crash and I don't think there's anything wrong with the code.
I have seen some complaints about this before but it was related to a previous version and people advised to upgrade PyQt4 to the latest version and so I did, but that didn't help with the crashing problem.
So I ask, is there anything that can lead to this behavior with PyQt4, do I need to do some kind on termination procedure to cleanup Qt or anything else I am missing?

A: I had the same problem with a simple hello world application (QDialog with 20 labels). Weirdly the problem disappears with 10 labels.
I solved by forcing exit as follows:
def closeEvent(self, event):
    exit()

This happens on Windows with PyQt v4.10.3 for Python v2.7 (x32) on VirtualBox.

A: A debugger will only tell us what we already know: The application crashes on exit.
You probably need to set an active window which, when closed, will result in deterministic garbage collection and a clean application exit. There are more proper ways to do this, but the simpl;e example below should require minimum code changes, and is based on a dialog application that I wrote and works fine.
#The application
app = QtGui.QApplication(sys.argv)

#The main window
MainWindow = QtGui.QMainWindow()
app.setActiveWindow(MainWindow) #<---- This is what's probably missing

#the ui
ui = Ui_MainWindow()
ui.setupUi(MainWindow)

#start the application's exec loop, return the exit code to the OS
exit(app.exec_())


text:
Q: Excel VBA: How to Read file names of type PDF and spit them into a column on a sheet In Excel 2003 is there any way to read pdf file names from a single directory and put them inside an Excel spreadsheet?

A: Dim c as Range, tmp
Dim FolderPath as string

FolderPath = "C:\MyFolder\"
Set c = ActiveSheet.Range("A1")

tmp = Dir(FolderPath & "*.pdf")
Do While tmp<>""
  c.value = tmp
  set c = c.offset(1,0)
  tmp=Dir()
Loop

Tim

A: To list files from a folder take a look at FileSystemObject.
Provide os more info about what you need, we'll help you better.
Rgds


text:
Q: SAS - Fails to load program with long name from Windows Explorer I am using Base SAS 9.4 on Windows 7.  For various reasons, which are detailed below, some of my programs have extremely long names.  Exacerbating this further, the programs are stored deep in the abyss of a network drive.  This causes problems when trying to open from Windows Explorer.  I believe the problem lies with SAS, but have tagged the question with Windows in case not.  I'm hoping there is some way to address this problem via a configuration file or an edit to the registry.

To open a program, I typically double click on the .sas file in Windows Explorer. This opens the Enhanced Editor after a brief waiting period in which a SAS message box states:

The SAS System is processing requests. Please wait...

When a program's full name, including path and extension, exceeds 182 characters (i.e. has form: \\network-location\a\bunch\of\....\folders\program path exceeding 182 char.sas), the same "SAS System is processing requests" message appears, but then a Windows error is generated.

Not surprisingly, no solution is proffered by Windows.
When the program name is such that the full path is exactly 182 characters, nothing happens.  I double click on the program and the only result is to select the file in Windows Explorer.  If I monitor "Processes" within the Windows Task Manager, no new processes are started when such a program is double clicked.
When the program name is such that the full path is less than 182 characters, the program opens in the Enhanced Editor as expected.

According to MSDN, the max path is 260 characters.  Clearly, 182 is well below that limit.  SAS is the only application which has a problem with the path length.  For example, I can copy the file name and extension, create a new text document with the same name (plus .txt) and open the file in Notepad, Notepad++, Word, Wordpad, Emacs, etc.
I have deduced two workarounds for working with names exceeding 182 characters.
If I open SAS via SAS.exe, I can load a program through the Open dialog with a path exceeding 182 characters just fine.  This is not a good solution, however, as the Open dialog does not allow paths to be copy/pasted.  The entire file path must be traversed.  I can also drag such a program into the editor window within SAS to load it.  This too is not a good solution, as a program will only load if there is a blank editor window.  If the program is accidentally dragged on the the log window, it will execute automatically.  Also, the program does not open in a convenient location.  It opens in the middle of the Enhanced Editor and must be manually resized.  That the programs can be loaded and executed at all leads me to believe that there is some way to fix this problem.  It seems that somewhere in the process of loading the file, SAS violates some variable limit.
Of course, people would suggest that I use a different network location or shorter names.  To the former, I am required to use a specific network location.  To the latter, these programs are being developed in parallel with various reports.  Many of the programs are similar and the corresponding references (table/figure numbers) in the reports change multiple times/aren't always communicated to me.  Through experience, I've found the surest way to work with these uncertainties is to simply name the file by the label it's given in the report.  Otherwise, I need to adopt unclear abbreviations, bad organizational practices, or introduce intermediate steps (like creating codes or a document which indexes the programs).

Edit: Per Joe's comment, it seems that the Open dialog allows copy and paste for specific file names.  A file path can be copied in Windows Explorer via Shift + Right Mouse Click > Copy as Path and pasted into the "File Path" box in the Open dialog.

To avoid traversing the tree, the Current Folder may be updated before accessing the Open dialog.  This is located at the bottom right of the Enhanced Editor.

The Open dialog starts at whatever the Current Folder location is set to.

A: I suspect your issue is that your 260 limit is in fact applicable.
When you double-click a program file, it doesn't just copy the path to SAS.  Instead, what happens is SASOACT.exe is called, with a command of something similar to this:
"C:\Program Files\SAS94\SASFoundation\9.4\core\sasexe\sasoact.exe" action=Open datatype=Access filename="%1" progid=SAS.Application.940

That's well over 100 characters already by itself; presumably, behind the scenes, you end up with something like
"C:\Program Files\SAS94\SASFoundation\9.4\core\sasexe\sasoact.exe -open ""%1"""

Which adds around 70 or 80 characters to what you're passing it.  Thus the 260 character limit.
You should use one of the workarounds - I personally prefer to just file->open, myself, but really whatever works best for you is fine.  You could also consider using another editor for the simple double-click actions, though any editor you chose would still have some issues.
You could also consider asking IT to install SAS itself in a location that had a shorter path name, though realistically that might save 10 characters or so.
As for pasting; you can paste a path name just as easily as a file name into the file->open dialog.  I have no idea why you don't seem to think you can, but I just did so now with no more difficulty than any other folder dialog...

Another workaround to consider, by the way, is mapping a drive letter to the network path.  I.e., if your network path is
//myserver/projects/financial/projectnumber/.../

You map some letter (let's say R: arbitrarily) to that root path, //myserver/projects/financial/projectnumber, which is not changing anything other than how you refer to it locally. Then you can use:
R:\...\filename.sas

And you don't have to navigate paths, etc.  You'd have to repeat that mapping process on any machine that you wanted to do this on, but if this mostly about your own workflow, that shouldn't be an issue. Just don't refer to R: inside the program itself and nobody else will ever know that you've changed anything.


text:
Q: PHP - PCLZIP adding file from string PCLZIP is a great library, but unfortunately it is poorly documented.
I am using it in order to support also servers where ZipArchive is disabled (or php version not supported)
I have a function to add uploaded files (one by one) to a ZIP archive.
If the archive is not existing, it creates one, if the archive exists, it just adds the new files.
The problem I have is with a function adding a TXT file, that is based on the Comments from the archive. (the function reads the comments that were previously prepared, and should create a TXT file from string and insert into the archive.)
I can not seem to find a function to OVERWRITE a file from string (Or I do not know how to use it ).
I can create it with   PCLZIP_ATT_FILE_NAME ,but somehow, when I run the function, it creates a new .txt file (with  the same filename!) every time it adds a file to the archive (as opposed to OVERWRITE the existing one)
I tried to use PCLZIP_ATT_FILE_NEW_FULL_NAME - but I can not find where to give it the parameters to WHICH file it needs to overwrite ..
The function is here : (sorry if it is long..)
    $archive = new PclZip($zipname);

        if (!file_exists($zipname)){  //The Archive already exists - let´s just ADD new files.

            $comment = $comment_head . $comment_add ;

            $string_content = $comment;

            $v_list = $archive->create($file,
                                        PCLZIP_OPT_ADD_PATH, $sitename,
                                        PCLZIP_OPT_COMMENT, $comment,
                                        PCLZIP_OPT_REMOVE_ALL_PATH);

                                        $prop = $archive->properties();
                                        $prop = $prop['comment'];
                                        if (!$prop) {$prop = $comment;}

            $list = $archive->add(array(
                                   array(
                                   PCLZIP_ATT_FILE_NAME => $string_file,
                                   PCLZIP_ATT_FILE_CONTENT => $prop,
                                   PCLZIP_ATT_FILE_NEW_FULL_NAME => $string_file
                                         )
                                   )
                                   );

                      if ($v_list == 0) {
                        die("Error : ".$archive->errorInfo(true));
                      }

        } else {

// No Archive already exists - Create with new file .

        $comment_add =  $meta['file'] . PHP_EOL . PHP_EOL ;/*.$comment_foot*/ ;

        $b_list = $archive->add($file,
                                    PCLZIP_OPT_ADD_PATH, $sitename,
                                    PCLZIP_OPT_ADD_COMMENT, $comment_add,
                                    PCLZIP_OPT_REMOVE_ALL_PATH);

                                $prop = $archive->properties();
                                        $prop = $prop['comment'];
                                        if (!$prop) {$prop = $comment;}

            $list_6 = $archive->add(array(
                                   array( PCLZIP_ATT_FILE_NAME => $string_file,
                                        PCLZIP_ATT_FILE_CONTENT => $prop
                                         )
                                   )
                                   );

                  if ($b_list == 0) {
                    die("Error : ".$archive->errorInfo(true));
                  }

      }

So - anyone knows how to OVERWRITE a file from string (and not from file..) with PCLzip ??

A: $archive = new PclZip("archive.zip");
$v_filename = "new_file.txt";
$v_content = "This is the content of file one\nHello second line";
$list = $archive->create(array(
                               array( PCLZIP_ATT_FILE_NAME => $v_filename,
                                      PCLZIP_ATT_FILE_CONTENT => $v_content
                                     )
                               )
                         );
if ($list == 0) {
  die("ERROR : '".$archive->errorInfo(true)."'");
}

http://www.phpconcept.net/pclzip/news/3-pclzip-26