text:
Q: Segmentation fault, Pilha em c Não sei o que pode estar dando esse erro em meu código, por favor se alguém souber o que está acontecendo. Aqui vai o código.
#include <stdio.h>
#include <stdlib.h>

struct no {
    int dado;
    struct no *prox;
};

typedef struct no criano;
typedef criano *no_pont;
int tam;

//void cria_Fila(no_pont *head, no_pont *tail);
int fila_Vazia(no_pont head);
void insere_Fila(no_pont *head, no_pont *tail, int valor);
int retira_Fila(no_pont *head, no_pont *tail);
void imprime_Fila(no_pont atual);

int main() {
    no_pont head=NULL;
    no_pont tail=NULL;
//  cria_Fila(&head,&tail);
    insere_Fila(&head, &tail, 52);
    insere_Fila(&head, &tail, 21);
    insere_Fila(&head, &tail, 532);
    imprime_Fila(head);

    return 0;
}

/*void cria_Fila(no_pont *head, no_pont *tail, int tam){
head=NULL;
tail=NULL;
tam=0;
}*/

int fila_Vazia(no_pont head) {
    return head=NULL;
}

void insere_Fila(no_pont *head, no_pont *tail, int valor) {
    no_pont novo;
    novo = (no_pont*)malloc(sizeof(no_pont));

    if(novo!=NULL) {
        novo->dado=valor;
        novo->prox=NULL;

        if(fila_Vazia(*head)) {
            *head=novo;
        } else {
            (*tail)->prox=novo;
        }
    } else {
        printf("%d nao inserido. Nao ha espaco na memoria\n",valor);
    }
    tam++;
}

int retira_Fila(no_pont *head, no_pont *tail) {
    int valor;
    no_pont aux;

    valor = (*head)->dado;
    aux= *head;
    *head= (*head)->prox;
    if( *head == NULL ) {
        *tail = NULL;
    }
    free(aux);
    tam--;
    return valor;
}

void imprime_Fila(no_pont atual) {
    if(atual == NULL) {
        printf("A fila esta vazia\n");
    } else {
        printf("A fila e: ");

        while(atual!=NULL) {
            printf("%c  ",atual->dado);
            atual=atual->prox;
        }

        printf("NULL\n\n");
    }
}

A: Tem alguns erros pequenos no código:

*

*A comparação no fila_Vazia está feita só com um = assim:
return head=NULL;

*Na função insere_Fila a alocação do novo nó não está correta:
novo = (no_pont*)malloc(sizeof(no_pont));

Pois aloca um ponteiro para o nó em vez de o nó em si.

*Ainda na função insere_Fila não está a modificar o tail apropriadamente

*O printf no imprime_Fila está %c quando o dado é do tipo int.
A função fila_Vazia e insere_Fila deveriam ficar assim:
int fila_Vazia(no_pont head) {
    return head==NULL; //agora com ==
}

void insere_Fila(no_pont *head, no_pont *tail, int valor) {
    no_pont novo;
    novo = (no_pont)malloc(sizeof(criano)); //alocação de criano em vez de no_pont

    if(novo!=NULL) {
        novo->dado=valor;
        novo->prox=NULL;

        if(fila_Vazia(*head)) {
            *head=novo;
        } else {
            (*tail)->prox=novo;
        }

        *tail = novo; //modificação do tail para o ultimo nó, que é o novo

    } else {
        printf("%d nao inserido. Nao ha espaco na memoria\n",valor);
    }
    tam++;
}

Veja o código a funcionar no Ideone
Sugestão
Uma vez que está a utilizar tam para o tamanho e tail para a cauda da lista seria boa ideia usar uma outra estrutura que representa a lista, com esses 3 campos.
Exemplo:
struct lista {
    no_pont head,
    no_pont tail,
    size_t tam
};


text:
Q: How to get data from a biography of an instagram profile with BeautifulSoup I'm using the book "Web Scraping with Python by Ryan Mitchell" as a reference.
I'm trying to create a crawler that only grabs the bio content of an Instagram profile with the BeautifulSoup module in Python 3.10.
I made this script based on the examples given in the book:
from urllib.request import urlopen
from bs4 import BeautifulSoup

userpage = urlopen("https://instagram.com/{}/".format("tarantinoxx"))
bs = BeautifulSoup(userpage, "lxml")
bio = bs.find_all('div', {'class':'_aacl _aacp _aacu _aacx _aad6 _aade'})
print(bio)

The code returns an empty list, as if there is no specified class, and this class is the same one shown in different profiles when inspecting by the browser.
How can I get this information?
I tried to register with the Instagram API but I got extremely lost.

A: if you are looking for a div with bs on that particular site, it is found like this:
from urllib.request import urlopen
from bs4 import BeautifulSoup

userpage = 'https://instagram.com/tarantinoxx'

userpage = urlopen("https://instagram.com/{}/".format("tarantinoxx"))
bs = BeautifulSoup(userpage, 'html.parser')
bio = bs.find_all('div')
print(bio)

Which returns this:
[

,
<img height="80px" src="data:image/png;base64,[encoded data, 6912 characters]" style="position:absolute;top:50%;left:50%;margin:-40px 0 0 -40px" width="80px"/><img height="37px" src="data:image/png;base64,[encoded data, 7712 characters]" width="72px"/>
]

So you can inspect the above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge value of 1 array to another array where keys are the same I have 2 arrays and I want to push a value from one array to another where keys values equal each other.
1st array
    $retail_rates=[
    {
        "supplier": "ALAMO",
        "rateTotalAmount": 293.44,
        "estimatedTotalAmount": 495.34, //i want to add this AS retailTotalAmount
        "numDays": 9 // i want to add this
    },
    {
        "supplier": "HERTZ",
        "rateTotalAmount": 317.16,
        "estimatedTotalAmount": 537.43,
        "numDays": 9
    }
]

2nd array
    $net_rates =[
    {
        "reference_number": "COMPEKYP7537400-2401",
        "supplier": "HERTZ",
        "rateTotalAmount": 203.01,
        "estimatedTotalAmount": 291.21
    },
    {
        "reference_number": "REF_ID:867692955",
        "supplier": "ALAMO",
        "rateTotalAmount": 147,
        "estimatedTotalAmount": 225.58
    }
]

What I want to end up with
    $final_array=[
    {
        "reference_number": "COMPEKYP7537400-2401",
        "supplier": "HERTZ",
        "rateTotalAmount": 203.01,
        "estimatedTotalAmount": 291.21,
        "retailTotalAmount": 537.43,
         "numDays": 9
    },
    {
        "reference_number": "REF_ID:867692955",
        "supplier": "ALAMO",
        "rateTotalAmount": 147,
        "estimatedTotalAmount": 225.58,
        "retailTotalAmount": 495.34
         "numDays": 9
    }
         // and so on all the way through

]

I have tried several loops but can't seem to fill it properly. Please help if you can

A: Iterate one time over the first array and create an assoc array with the supplier as the key. Then iterate over the second array and append it to the first one.
$final_array = [];
foreach ($retail_array as $item) {
    $final_array[$item['supplier']] = $item;
}

foreach ($net_array as $item) {
    if (isset($final_array[$item['supplier']])) {
        $final_array[$item['supplier']] = $item + $final_array[$item['supplier']];
    } else {
        $final_array[$item['supplier']] = $item;
    }
}

A: Try this
$result = [];
foreach ($net_rates as $net_key => $net_rate) {
    foreach ($retail_rates as $retail_key => $retail_rate) {

        if ($retail_rate['supplier'] != $net_rate['supplier']) {
            continue;
        }

        $data = $net_rate;
        $data['retailTotalAmount'] = $retail_rate['estimatedTotalAmount'];
        $data['numDays'] = $retail_rate['numDays'];
        $result[] = $data;

        unset($retail_rates[$retail_key]);
        unset($net_rates[$net_key]);
        break;
    }
}
$result = array_merge($result, $retail_rates);
$result = array_merge($result, $net_rates);
dd($result);

result is
array:2 [▼
  1 => array:6 [▼
    "reference_number" => "COMPEKYP7537400-2401"
    "supplier" => "HERTZ"
    "rateTotalAmount" => 203.01
    "estimatedTotalAmount" => 291.21
    "retailTotalAmount" => 537.43
    "numDays" => 9
  ]
  0 => array:6 [▼
    "reference_number" => "REF_ID:867692955"
    "supplier" => "ALAMO"
    "rateTotalAmount" => 147
    "estimatedTotalAmount" => 225.58
    "retailTotalAmount" => 495.34
    "numDays" => 9
  ]
]


text:
Q: Intermittent type error when trying to split an array into an array of characters So I have an array of "phrases" for a game show app project. I'm trying to generate a random number, to select a phrase within that array, then split the phrases characters.
When I return it with .split(), and call the function in the console, I get a type error, but it seems intermittent, if I call it several times, sometimes it works, others it throws a type error.
What seems to be the issue?
    const phrases = [
    'JavaScript is the best programming language',
    'I love CSS',
    'Check out Peer Reviews',
    'Stack Overflow',
    'This is in the phrases array'
    ];

    const getRandomPhraseAsArray = arr => {
    const randomNumber = arr[Math.floor(Math.random() * arr.length) +1];
    return randomNumber.split("");
    };

app.js:22 Uncaught TypeError: Cannot read property 'split' of undefined
    at getRandomPhraseAsArray (app.js:22)
    at <anonymous>:1:1

A: The problem with your code is that you are trying to add 1 to your Math.Random() This function gives a value between 0 to 1 and after you multiply whatever value it gives with the array length you are good to go but when you add +1 to it, It sometimes exceeds the array length. the proper fix should be:
  const phrases = [
    'JavaScript is the best programming language',
    'I love CSS',
    'Check out Peer Reviews',
    'Stack Overflow',
    'This is in the phrases array'
    ];

    const getRandomPhraseAsArray = arr => {
   //removed the +1 here
    const randomNumber = arr[Math.floor(Math.random() * arr.length)];
    return randomNumber.split("");
    };

Hope this helps!


text:
Q: How to write an assembly sorting program 8086 with works with 6 digits numbers? im new to assembly language and i know many codes.
However im working with 8086 emulator with only works with 16 bit numbers.
this is a home work that im  really stuck in :
How can i write an assembly code with do the following :
1-get 20 , maximum 6-digits decimal numbers and store them in an array.

2- sort the array in ascending order.

its really hard for me to understand how to manage registers and stack for this long numbers.
every help will be appreciated in advance .

A: In order to sort 32bit numbers (or broader) with 16bit registers you have to compare the upper part of each number separately.
Assume we have these random two 32 bit numbers (shown in hex) 4567afdf and 321abc09.
Now when you look at them as 16 bit values they look like this:
4567 afdf
321a bc09

As you can easily see, the upper 16 bits you can compare individually.
If the upper 16 bits are higher or lower, then you know that the lower part doesn't matter anymore and you sort them accordingly.
If the upper 16 bits are equal, then you compare the lower 16 bits and if they are also equal, both numbers are equal => no sort needed, otherwise you shuffle them accordingly. Since the upper 16 bits are also equal, you don't even need to shuffle them.
If the upper 16bits are different, you still have to shuffle the lower 16 bits accordingly, as they might be different.
The basics of this approach can be used for an arbitrary number of bits not just 32bits. Generally when you have a seemingly hard problem, you should try to think of the easy examples and how you can solve it. Then you can extend it to more complicated cases.
EDIT:
An alternative approach would be, if you have strings of decimal numbers and you want to sort them based on the string representation instead of the numbers.
In this case, you can do it as follows

*

*If the length of the two number strings are differnt, the shorter one is the lower number.

*if the length is equal, then you can look at each digit individually (starting with the first digit) until you hit a non-equal digit or the string end. If you reaced the end of the string, the numbers are the same, otherwise you kn ow which one is higher/lower.


text:
Q: Integrating modular function $f(x,y)=|xy|$ in the area of the circle $x^2+y^2=a^2$ I need to solve the integral $$\iint_\omega |xy|\,dx\,dy$$ where $\omega:x^2+y^2=a^2$ I created the following integral and I have no idea how can I integrate modular function:
$$\int_{-a}^a dy\int_{-\sqrt{a^2-y^2}}^\sqrt{a^2-y^2} |xy|\,dx$$The only thing that I do know is that $\int |x|\,dx=\frac{x|x|}{2}+C$, but later on I face the next problem: $$\int_{-a}^a|y|\cdot|\sqrt{a^2-y^2}|\cdot \sqrt{a^2-y^2}\,dy$$
Could anyone help me?

A: Why not convert to polar coordinates?
With $x=r\cos(\theta)$ and $y=r\sin(\theta)$. The area element becomes $rdrd\theta$. Then the integral over the area of the circle becomes
\begin{align}
I &=\int_0^a\int_0^{2\pi}r^2|\cos(\theta)\sin(\theta)|rdrd\theta=\int_0^ar^3dr\int_0^{2\pi}|\cos(\theta)\sin(\theta)|d\theta\\
&=\frac{a^4}{4}\frac{1}{2}\int_0^{2\pi}|\sin(2\theta)|d\theta
=\frac{a^4}{8}\int_0^{2\pi}|\sin(2\theta)|d\theta=\frac{a^4}{4}\int_0^{\pi}|\sin(2\theta)|d\theta\\
&=\frac{a^4}{2}\int_0^{\pi/2}\sin(2\theta)d\theta=\frac{a^4}{2}
\end{align}

A: You can break your integral into four parts (corresponding to four quadrants) and can integrate easily using polar coordinates.
$$\iint_\omega |xy|dxdy = \int_{r=0}^a\int_{\theta = 0}^{2\pi} f(r, \theta) \ r\  dr\  d\theta$$
$$= \int_{r=0}^a\int_{\theta = 0}^{\pi/2 } r^3 cos\theta \ sin \theta \ dr \ d\theta \ + $$
$$ \quad \ \int_{r=0}^a\int_{\theta = \pi/2}^{\pi } r^3(- cos\theta \ sin \theta) \ dr \ d\theta \ + $$
$$ \int_{r=0}^a\int_{\theta = \pi}^{3\pi/2 } r^3 cos\theta \ sin \theta \ dr \ d\theta \ + $$
$$ \int_{r=0}^a\int_{\theta = 3\pi/2}^{2\pi } r^3(- cos\theta \ sin \theta) \ dr \ d\theta \  $$

A: Without using polar coordinates, we can evaluate the integral of interest $I$ given by
$$I=\int_{-a}^a \int_{-\sqrt{a^2-y^2}}^{\sqrt{a^2-y^2}}|xy|\,dx\,dy$$
Exploiting even symmetry reveals
$$\begin{align}
I&=4\int_{0}^a \int_0^{\sqrt{a^2-y^2}}xy\,dx\,dy\\\\
&=4\int_0^a y\int_0^{\sqrt{a^2-y^2}}x\,dx\,dy\\\\
&=4\int_0^a y\left(\frac12 (a^2-y^2)\right)\,dy\\\\
&=\int_0^a (a^2-y^2)\,d(y^2) \\\\
&=a^4-\frac12 a^4\\\\
&=\frac12 a^4
\end{align}$$
as expected!


text:
Q: Finding the spinor norm of an element using a proposition in 'The Maximal Subgroups of the Low-Dimensional Finite Classical Groups'. Let $F=\mathbb{F}_{q}$, where $q$ is an odd prime power. Let $e,f,d$ be a standard basis for the $3$-dimensional orthogonal space $V$, i.e. $(e,e)=(f,f)=(e,d)=(f,d)$ and $(e,f)=(d,d)=1$. I have an element $g\in SO_{3}(q)$ defined by: $g: e\mapsto -e$, $f\mapsto \frac{1}{2}e -f +d$, $d\mapsto e+d$. I would like to determine the spinor norm of this element using Proposition 1.6.11 in the book 'The Maximal Subgroups of the Low-Dimensional Finite Classical Groups' by Bray, Holt and Roney-Dougal.
The proposition is quite long to state so it would be handy if someone who can help already has a copy of the book to refer to. If not, then please let me know and I can post what the proposition says.
I have followed the proposition and have that the matrices
$$A:=I_{3}-g=\left( \begin{array}{ccc}
2 & -\frac{1}{2} & -1 \\
0 & 2 & 0 \\
0 & -1 & 0 \end{array} \right)$$
$$F= \textrm{matrix of invariant symmetric bilinear form =}\left( \begin{array}{ccc}
0 & 1 & 0 \\
1 & 0 & 0 \\
0 & 0 & 1 \end{array} \right).$$
If $k$ is the rank of $A$, the proposition says to let $B$ be a $k\times 3$ matrix whose rows form a basis of a complement of the nullspace of $A$. I have that $ker\, A=<(1,0,2)^{T}>$. Now by the way the proposition is stated it seems as if it does not make a difference as to what complement is taken. However, I have tried 3 different complements and I get contradictory answers each time.
Try 1) Orthogonal complement of $Ker\, A$, where $B=\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & -2 & 1  \end{array} \right)$. This gives me $det(BAFB^{T})=-25$.
Try 2) $B=\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0  \end{array} \right)$. This gives me $det(BAFB^{T})=-4$.
Try 3) $B=\left( \begin{array}{ccc}
0 & 0 & 1 \\
0 & 1 & 0  \end{array} \right)$. This gives me $det(BAFB^{T})=0$.
The problem is that whatever complement I take the determinants should all be non-zero squares at the same time, but this is not the case.
I am not sure if I have misunderstood how to use the proposition. Any help will be appreciated. Thanks.

A: The convention in the book is that matrices act on row vectors from the right. So the kernel of $A$ is $\langle (0,1,2) \rangle$ and Try 3) is not a complement. (You should never get $0$ for $\det(BAFB^T)$.)
Try 1) and Try 2) are either both squares or both nonsquares depending on whether $-1$ is a square.
Also, following the convention of the book, the matrix of $g$ would be the transpose of what you have, but that is not the cause of the problem!

A: In characteristic 5, Try (1) does not actually yield a complement. The bottom row, $(0,-2,1)=-2(0,1,2)$, is in the kernel in this case. So again, no contradiction.


text:
Q: how to change the hsv of texture in opengl Im having a three dimensional array of rgba texture and im displaying it on my viewport.
how can i change the color Hue, Saturation and value by input user gave . im new to opengl so need guidance to change the HSV according to user selection .

A: Get glm and look at the implementation in gtx/color_space.inl of these functions
template<typename valType >
detail::tvec3< valType >    hsvColor (detail::tvec3< valType > const &rgbValue)

template<typename valType >
detail::tvec3< valType >    rgbColor (detail::tvec3< valType > const &hsvValue)

prototyped in gtx/color_space.hpp


text:
Q: SVN Forced remote commit We are having distributed team, even after trying to follow practices many developers forget to commit during closing hours. Is it possible to have some way from server itself we can auto commit all files in particular folder branch at time from all clients. So even if developer(s) forgets to commit we can get the latest.

A: If everybody is running Windows then schedule a task at the required time that will run a batch file which simply does this:
svn ci -m "<your default commit message to indicate that this is an automatic commit done by the scheduled task>"
If it is a *nix environment then setup a cron job.


text:
Q: Is there a way to do a multi-item carousel with react-bootstrap? I've been trying to do a multi-item carousel with the react-bootstrap package and I succeded making just a single-item carousel. I am using the Instagram API to fetch some photos and the idea is to display a few of them, not just one.
I used the example I found in React docs of using a controlled component to render my images. I tried setting selectedIndex in handleSelect function to a default value of 3, which didn't work.
From what I understand activeIndex controls the visible slide so... I don't know what I am missing.
This is the link:
https://react-bootstrap.github.io/components/carousel/
Below is some code of my controlled carousel component:
import Carousel from 'react-bootstrap/Carousel'

export default class ControlledCarousel extends React.Component {
  constructor(props, context) {
    super(props, context);

    // this.handleSelect = this.handleSelect.bind(this);

    this.state = {
      index: 0,
      direction: null,
    };
  }

  handleSelect = (selectedIndex, e) => {
    this.setState({
      index: selectedIndex,
      direction: e.direction,
    });
  }

  render() {
    const { index, direction } = this.state;

    return (
      <Carousel
        activeIndex={index}

        direction={direction}
        onSelect={this.handleSelect}

      >

              {this.props.images.map((image) => {
                return <Carousel.Item key={image.id}>
                  <img className="d-block w-100" alt={image.tags[0]} src={image.images.standard_resolution.url} />
                </Carousel.Item>
              })}

      </Carousel>
    );
  }
}


text:
Q: Item in the ArrayList gets replaced instead of appending I am trying to bring all the items from the ArrayList getting saved in EditActivity to the MainActivity using SharedPreferences. But only the last entered data gets displayed in the ListView on the first MainActivity. How can I make all the text entered into the EditText get displayed as a different item in the ListView and not replace the earlier item.
Here is my Code:

MainActivity

public class MainActivity extends AppCompatActivity {

private ListView list;
private Button nextButton;

ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    list = (ListView) findViewById(R.id.list);
    nextButton = (Button) findViewById(R.id.nextButton);

        loadData();

    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
    list.setAdapter(adapter);
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            nextActivity();
        }
    });
}
public void nextActivity(){
    Intent intent = new Intent(this, EditActivity.class);
    startActivity(intent);
}

public void loadData(){
    SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sp.getString("list", null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    arrayList = gson.fromJson(json, type);

    if(arrayList == null){
        arrayList = new ArrayList<String>();
    }
}}

EditActivity

public class EditActivity extends AppCompatActivity {

private EditText input;
private Button addButton;

public ArrayList<String> list = new ArrayList<String>();
public ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);

    input = (EditText) findViewById(R.id.input);
    addButton = (Button) findViewById(R.id.addButton);

    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String getInput = input.getText().toString();
            adapter.addAll(getInput);
            saveData();
            input.setText(""); //clear the value in the edit text
        }
    });

}
public void saveData(){
    SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString("list", json);
    editor.apply();
}}

A: I think you forget to add item to list before save and thus the result is you are saving only the last item.
addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String getInput = input.getText().toString();
        list.add(getInput); //add this line
        adapter.addAll(getInput);
        saveData();
        input.setText(""); //clear the value in the edit text
    }
});


text:
Q: How do I change my .minecraft folder location to another drive? I would like to move my .minecraft folder to another drive. I have already copied it to the desired location, but I cannot find a way to change the folder location.
I tried running this script in the same folder as the minecraft launcher exe, but I cannot find it. It was not in the C:\Program Files (x86)\Minecraft Launcher\ or  C:\Program Files (x86)\Minecraft\ folders (Neither of which exist).
How can I do this?
New launcher btw.


text:
Q: Dynamic DataSource swap for UITableView in Swift I am new to iOS/Swift development, and having a problem with making a dynamic swap of DataSource work for a UITableView - note I am not swapping the Delegate, just the DataSource.
I have read other similar questions/responses on Stack Overflow, and not found one that's relevant to my situation. Typically they're about setting the DataSource on "viewDidLoad" (e.g. this one, and this one), whereas my situation is about swapping the DataSource when the user presses a button. The problems in the referenced questions don't exist in my code.
Here's outline of my code. I have the buttonPress method connected to the TouchUpInside event in the storyboard:
class ViewController: UIViewController, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    ...

    @IBAction func buttonPress(sender: UIButton) {

        ...

        self.tableView.dataSource = DummyDataSource()
        self.tableView.delegate = self
        self.tableView.reloadData()

    }

    ...

}

...and here's my datasource class:
import UIKit

class DummyDataSource: NSObject, UITableViewDataSource {

    let names = ["A", "B", "C"]

    func tableView(tableView: UITableView,
                     numberOfRowsInSection section: Int) -> Int {
        return names.count
    }

    func tableView(tableView: UITableView,
                     cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell?

        if ( cell == nil ) {
            cell = UITableViewCell( style: UITableViewCellStyle.Default,
                                reuseIdentifier: simpleTableIdentifier)
        }

        cell!.textLabel?.text = names[indexPath.row]
        return cell!

    }

}

When I press the button, I can see that the pressButton method is being called correctly, but the data doesn't show up in the tableView (no errors - just no data). Any ideas please? Thank you.

A: UITableView's dataSource property is either unsafe_unretained or weak, depending on which version of iOS.  Either way, as with any other delegate, it doesn't keep a strong reference.
So when you write a line like this:
self.tableView.dataSource = DummyDataSource()

Your newly instantiated DummyDataSource() property doesn't have any strong references pointing to it.  It is therefore immediately released by ARC.
We need to keep a strong reference to the data source if we want it to stick around.
My recommendation would be to add a data source property to your view controller which can keep the strong reference.  We will also use the didSet of this property to set the table view's data source property and reload its data.
var dataSource: UITableViewDataSource? {
    didSet {
        tableView?.dataSource = dataSource
        tableView?.reloadData()
    }
}

We use optional-chaining to protect against the data source being set before the view is loaded and the tableView property is populated.  Otherwise, we will get a fatal error for trying to unwrap nil.
We shouldn't need to be setting the data source property on the table view anywhere else.  And the only reason why we should need to called reloadData() anywhere else is if our data source itself can change the data it is representing.  However, it is important that reloadData() is called in sync with resetting the dataSource to protect against some likely index-out-of-bound crashes.


text:
Q: Can i dynamically add reviewers to Gerrit based on the files changed in the change-set? I have a mechanism where I commit my changes locally and then run "git push..." to publish the change-set to Gerrit. Now, if i want to add a reviewer if there are specific files that have changed (as part of the change-set), I would like to add a reviewer. Is this possible ? Initial investigation points to git hooks as a possible solution, but it would help if someone could give a detailed workflow in order to achieve the above objective.

A: Take a look at the reviewers plugin, it can be configured to add reviewers based on standard Gerrit filter expressions, including file names. Pre-built plugin binaries are available here.

A: I was able to resolve this by using the git pre-push hook. The steps are as follows:

*

*Obtain the change-id of the commit that needs to be pushed to Gerrit.

*Add logic to check if the commit does indeed have changes to files that need to be monitored.

*Use the set-reviewers command to add the appropriate user/group as a reviewer to the particular review (using the change-id obtained earlier).


text:
Q: How will OAuth be enabled/disabled and how will requests show up in the Google Cloud Console? As per an email I received from Google, the Google+ APIs will be shut down soon. Currently "Google Sign In" OAuth is represented as a Google+ API when you go to the Google Cloud Console dashboard, and you enable / disable OAuth by enabling / disabling the Google+ API "package" of APIs.
As I understand it, this endpoint is NOT going away:
https://www.googleapis.com/oauth2/v2/userinfo
But if the name / concept of Google+ APIs is going away, where will I find our utilization (where will the requests be represented) in the Google Cloud Console, and under what name will the above endpoint be enabled / disabled?


text:
Q: Ensure the user creates instance of a new subclass Let's say there is a base class
class Base
{
}

and the user has created a new subclass
class NewDerivedClass : public Base
{
}

There is also a enum for all the subclasses:
enum SubclassId
{
    Derived1_Id,
    Derived2_Id,
    ...
    NewDerivedClass_Id  // User has to add this line
}

Now, there is also a factory which creates derived instances based on the SubclassId:
class SubclassFactory
{
    Base* CreateSubclassInstance(SubclassId subclassId)
    {
        switch(subclassId)
        {
            case SubclassId::Derived1_Id:
                return new Derived1(params);
            case SubclassId::Derived2_Id:
                return new Derived2(params);
             ...

            // User has to add the following lines:
            case SubclassId::NewDerivedClass_Id:
                return new NewDerivedClass(params);
        }
    }
}

*

*How can I force the user of my Base class to add new Id in enum?

*How can I force the user of my Base class to create it's instance in SubclassFactory?

In the best case I would like to see a compile-time error. Unit test solution to this problem is also acceptable.

Additional information.
1. Users of the Base class create new subclasses in the client side.
2. My code operates in the backend. I get the subclass id remotely and use Factory to make instances of the subclasses created by client programmers.


text:
Q: Give caller ownership of local variables that depend on each other Here's a fairly minimal reproduction of my problem:
fn str_to_u8(s: &str) -> &[u8] {
    let vector = s.chars().map(|c| c as u8).collect::<Vec<u8>>();
    let slice = vector.as_slice();
    slice
}

The compiler says that vector doesn't live long enough, which makes sense. Is there a way to force vector to "move" into slice so that when the caller takes ownership of slice it also takes ownership of vector?

A: (Copied from my answer to a related but still slightly different question.)
You're trying to return a borrow to something which was created in and is owned by the function. This is impossible. No, there is no way around it; you can't somehow extend the lifetime of vector, returning vector as well as the borrow won't work. Really. This is one of the things Rust was specifically designed to absolutely forbid.
If you want to transfer something out of a function, one of two things must be true:

*

*It is being stored somewhere outside the function that will outlive the current call (as in, you were given a borrow as an argument; returning doesn't count).
To expand on this, you could change the function to fn str_to_u8<'a, 'b>(s: &'a str, vector: &'b mut Vec<u8>) -> &'b [u8].  This would allow the vector to survive the function and let you to safely return a slice into it.

Note: Another somewhat code-smelly alternative is to leak the vector.  This involves forgetting vector and unsafely casting the slice to &'static [u8] (i.e. promise the compiler it will live forever).  This, obviously, will leak the heap allocation.
You could also store vector in a global or something, but that should be your option of absolute last resort; Rust hates globals.

*You are returning ownership, not just a borrowed reference.  So, your function would just return the Vec<u8>, which the caller would then slice.


text:
Q: BufferedWriter and OutOfMemoryError: Java heap space I am retrieving some data from server for around 500 objects and storing it in a HashMap and when all the data for 500 objects have been collected, I used to write it to simple plain text files as Strings using BuffrerdWriter. But I was getting OutOfMemoryError only in the last thread.
So I decided to break-up data collection and rather than collecting data for 500 objects, I started collecting data for 50 objects at a time in a loop populating hashmap locally so that it can be garbage collected in the next iteration and kept BufferedWriter open for the whole time rather than opening and closing it in the end at once.
Now I am getting OutofMemoryError in more threads, rather than in just last thread.
Note: The application is multithreaded and there are 5-10 threads each collecting data for 500 objects and having their own BUfferedWriter in their call method.
public String call(){
    BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));

    try {
        List<String[]> objectList = sPoller.getobjects(Keyword.HTTP);
        for(String[] objectNameArray : objectList){
            if(objectNameArray.length>0){
                HashMap<String, TreeMap<Long, ArrayList<String>>> statMap = new HashMap<String, TreeMap<Long, ArrayList<String>>>();
                HashMap<String, String> objectMap = sPoller.getobjectNamesIDMap();

                /**
                *code for getting data from server
                *
                **/

                /**
                *code for populating hashmaps
                *
                **/

            }
            writeHTTPStats(statMap);
        }
    }catch(Exception e){
            e.printStackTrace();
    }finally{
        writer.closeStream();
    }
}


text:
Q: Incrementing a variable triggers EXIT in bash 4, but not in bash 3 Consider this (exemplary) bash script:
#!/bin/bash -e
errorExit() {
    echo "" >&2
    echo "ERROR (${var_scriptfilename}):" >&2
    echo "An unhandled error occurred." >&2
    intentionalExit 1
}
intentionalExit () {
    trap - EXIT # Unregister the EXIT trap
    exit $1
}
trap errorExit EXIT # Trap script errors
var_scriptfilename="$(basename "$0")"
# ==== START OF TEST ====
var_counter=0
((var_counter++))
echo "var_counter is $var_counter" >&2
# ===== END OF TEST =====
intentionalExit 0

If I run it in Cygwin's bash it produces the intended output:
var_counter is 1

However, if I run it on my Debian Squeeze box, which is its intended destination, I end up in the EXIT trap:
ERROR (test.increment.sh):
An unhandled error occurred.

...Why is that?
If I remove the -e option it works as expected on both systems, but I want to keep -e in use, obviously.
The slightly more cumbersome "universal" variant, var_counter=$(($var_counter+1)), works with -e being set on both shells, but I would prefer to use the first notation (or something similar-looking) since it clearly sticks out as an increment operation when reading the code.
bash --version on the Cygwin bash says:
GNU bash, version 3.2.51(24)-release (i686-pc-cygwin)
Copyright (C) 2007 Free Software Foundation, Inc.

On Debian, it is:
GNU bash, Version 4.1.5(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.

I am intrigued as to why this is that way. Does anybody know the cause of this behavior?
Also, does anybody know of a similar-looking way to increment a variable in bash that I could use?

A: From the bash4 manpage on Debian:
((expression))
    The expression is evaluated according  to  the  rules  described
    below  under ARITHMETIC EVALUATION.  If the value of the expres‐
    sion is non-zero, the return status is 0; otherwise  the  return
    status is 1.  This is exactly equivalent to let "expression".

and also ...
-e      Exit  immediately  if a pipeline (which may consist of a
        single simple command),  a subshell command enclosed  in
        parentheses,  or one of the commands executed as part of
        a command list enclosed by  braces  (see  SHELL  GRAMMAR
        above) exits with a non-zero status.

So what is happening is ((var++)) increments var from 0 to 1 and returns
0, causing the overall expression to return non-zero, which triggers
errexit.
Now for the difference between the two different bash versions: this change
in (( behavior seems to have occurred between 4.0 and 4.1.  In 4.0 ((
apparently did not trigger errexit.  See this NEWS file for the details.
You'll have to scroll down to line 135 or so.  The Changelog from the source
distribution seems to confirm this.
If you just want a variable incremented without using the exit status,
there's multiple ways to do it.  Maybe some other people could give advice
on which is the best, but some possibilities are:

*

*var="$((var+1))", the portable POSIX sh method

*((var++)) || true, forcing the statement to always have a zero
exit status (bash only)


text:
Q: Plotting markers using leaflet and rCharts from a data frame with lat and lon values I am trying to learn the Leaflet functionality with rCharts and would like to plot multiple markers and popups garnered from a data.frame object in R
df <- data.frame(location = c("White House", "Impound Lot", "Bush Garden", "Rayburn", "Robertson House", "Beers Elementary"), latitude = c(38.89710, 38.81289, 38.94178, 38.8867787, 38.9053894, 38.86466), longitude = c(-77.036545, -77.0171983, -77.073311, -77.0105317, -77.0616441, -76.95554))
df
          location latitude longitude
1      White House 38.89710 -77.03655
2      Impound Lot 38.81289 -77.01720
3      Bush Garden 38.94178 -77.07331
4          Rayburn 38.88678 -77.01053
5  Robertson House 38.90539 -77.06164
6 Beers Elementary 38.86466 -76.95554

I tried modifying the code from the example on Ramnanth's rCharts page. This is my modification:
map <- Leaflet$new()
map$setView(c(38.89710, -77.03655), 12)
map$tileLayer(provider = 'Stamen.TonerLite')
map$marker(c(df$latitude, df$longitude), bindPopup = df$location)

This code does not produce any markers. I am looking for a solution whereby I can plot the lat and lon for each observation and have a marker with a popup populated by the value in the location column.

A: That won't work because df$latitude returns a vector with all the latitudes from your dataframe:
df$latitude
## [1] 38.89710 38.81289 38.94178 38.88678 38.90539 38.86466
df$longitude
##b[1] -77.03655 -77.01720 -77.07331 -77.01053 -77.06164 -76.95554

You'll need to add you markers in a loop:
for (i in 1:nrow(df)) {
    map$marker(c(df[i, "latitude"], df[i, "longitude"]), bindPopup = df[i, "location"])
}

Note: did this quickly, freehand, just starting out with R and am unable to test this at the moment.


text:
Q: OWIN OAuth2 middleware with %23 (# fragment) in redirect uri I'm using the ASP.NET OWIN/Katana OAuthAuthorizationServer middleware and have run into a snag.
I have some sites trying to get authorization tokens and created an /oauth/authorize endpoint. However, these requests are coming from a SPA (Angular) and will often have a fragment (#) in the redirect URL.
When the request is made, it will set the redirect_uri to that URL, but URL-encoded (so # changes to %23). However, whenever %23 comes across in the URL, the status is always set to 400 and I can't seem to prevent this in any way... Can't override anything and no Web.config reserved bad character changes, etc.
Thus, I tried to just replace it with some placeholder and then redirect back to itself.  This worked fine.  However, I can't seem to undo my URL change. I need to put # back in the URL and redirect to that, but the OWIN middleware completely ignores any attempts at changing the URL back...  Anyone have any ideas?

A: This is a limitation imposed by RFC 6749 Section 3.1.2:

The endpoint URI MUST NOT include a fragment component.

The OpenID Connect specification (and thus the popular IdentityServer3/4), which builds upon the OAuth2 spec, seems not to have this limitation, so you could either switch to OIDC or bend the OAuth2 spec a little bit :)
In the OWIN middleware the existence of the fragment is checked in OAuthAuthorizationServerHandler.
A work-around is to bypass this check by replacing the %23 denoting the fragment by a placeholder and patch the location redirect header before it gets send to the browser.
To replace the incoming %23 with a placeholder, you can override the providers MatchEndpoint method:
internal class OAuth2AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task MatchEndpoint(OAuthMatchEndpointContext context)
    {
        if (context.Request.Path.StartsWithSegments(context.Options.AuthorizeEndpointPath)
            && context.Request.QueryString.HasValue)
        {
            context.Request.QueryString = new QueryString(
                context.Request.QueryString.Value.Replace("%23", "__fragment__"));
        }

        return base.MatchEndpoint(context);
    }
}

The other part is trickier as you can't seem to do it by default from the provider class because the redirectUri is kept internally on the OAuthValidateClientRedirectUriContext.
A hacky way is to use reflection and modify this RedirectUri in the providers ValidateClientRedirectUri method:
public override async Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
    // Test if the redirect uri is allowed, if not call context.SetError("invalid_client");

    var redirectUri = context.RedirectUri.Replace("__fragment__", "#");
    var setter = context.GetType().GetProperty(nameof(context.RedirectUri))?.GetSetMethod(true);
    setter?.Invoke(context, new[] { redirectUri });
    context.Validated(redirectUri);
}

Another way is to add a simple middleware to the chain (before the OAuth2 middleware) that monitors the response (so after awaiting the next middleware) and patches the Location header where needed. This is less tricky than setting a private property, but now the patch is spread over 2 different places which is less maintainable.
With above work-around a redirect URI like
https://server.com/#spa/path/123

note that you will pass a URL-encoded version to the authorize endpoint redirect_uri param
will result in a redirect to
https://server.com/#spa/path/123&access_token=<the_access_token>

A: Part after hash sign https://en.wikipedia.org/wiki/Fragment_identifier never to be sent to server - see for example Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)? and many similar questions here.
What you can do is to post-process your placehodler on client-side via Java Script rather than trying to redirect to URL with # in it.


text:
Q: Can we swap the endianness of a data buffer, which is a fixed sized array, before mapping it to its eventual data structure? Scenario: A remote machine (big endian) sends a message to a local machine (little endian) over RS422.
The local machine gets the message as a buffer, i.e. dataBuffer which is an array of 4 16-bit ints. This buffer data eventually be mapped to a MainType data somewhere in the program but this is not our concern. We need a function that swaps the bytes (change the endianness) using the swapData() method.
Question: Given the fact that MainType has exactly 4 data members each 16 bits AND dataBuffer is array of size 4 and each data is 16 bits, can we just swap the data in the buffer WITHOUT mapping it to MainType data structure (as below)?
Constraints:

*

*The dataBuffer  needs to be global in the program,

*Swapping needs to be taken care of in swapData() function,

*The data will be filled in some other method such as useData()
Here is the code:
...

typedef unsigned short int USINT16;

typedef struct {
    USINT16  a : 1;
    USINT16  b : 1;
    USINT16  c : 1;
    USINT16  d : 1;
    USINT16  e : 1;
    USINT16  f : 1;
    USINT16  g : 1;
    USINT16  h : 2;
    USINT16  i : 3;
    USINT16  j : 4;
} OtherType; // 16 bits

typedef struct {
    USINT16   X;
    USINT16   Y;
    USINT16   Z;
    OtherType W;
} MainType;

...

unsigned short dataBuffer[4]; // available in global scope

...

void swapData() {
    receiveData(&dataBuffer); // data buffer is filled

    int i;
    for (i = 0; i < 4; i++) {
        dataBuffer[i] = __builtin_bswap16(dataBuffer);
    }
    // The data is little endian now ?
}

...

void useData() {
    MainType data; // map the swapped buffer to data

    // use the data etc.
    ....
}

A: If the remote machine behavior is frozen, you can investigate and determine what is the encoding of bit-fields on that platform and translate the buffer received on the local machine appropriately.
Byte swapping all 16 bit entries, including W, is a good initial step, you might have to change the struct definition for OtherType to fit the order in which it is defined by the compiler for the remote machine.  You can determine that by transmitting samples from the remote machine where only 1 field is set to all bits one and the others stay 0 and print the 16 bit value received.
Byte-swapping W is advisable because W.h most likely falls on a byte boundary with 1 bit in each byte.  For its bits to be adjacent in the local machine, the bytes in W should be swapped.  If the bit order on the remote machine is a b c d e f g h1 h0 i2 i1 i0 j3 j2 j1 j0 for the whole 16 bit word in W, when stored in memory on the remote machine, it becomes <a b c d e f g h1> <h0 i2 i1 i0 j3 j2 j1 j0> and subsequently transmitted as bytes and loaded in a 16 bit register on the local machine, it would become h0 i2 i1 i0 j3 j2 j1 j0 a b c d e f g h1 if you dont swap the bytes, because the first byte is loaded in the low order bits of the register.  Byte swapping prevents this but you still may have a problem with the bit-field order in the local machine as your current definition might be encoded as j3 j2 j1 j0 i2 i1 i0 h1 h0 g f e d c b a if the bit-fields are likely allocated from the lowest to the highest bit positions.
If you know some assembly language, generate the assembly for code that manipulate the bit-fields on both platforms and check if the fields are placed differently.


text:
Q: NDSolve point animation not working The below code plots the path of a ball bouncing but loses 90% of its velocity each time it bounces. (adapted from https://reference.wolfram.com/language/ref/WhenEvent.html).
sol = NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,
WhenEvent[y[t] == 0, y'[t] -> -0.9 y'[t]]}, y, {t, 0, 10}];

Plot[y[t] /. sol, {t, 0, 10}]

Manipulate[
 Graphics[
  Point[{0, y[t] /. sol}], PlotRange -> {{-.1, .1}, {5.1, -.1}}],
 {t, 0, 10}]

The plot function works as expected,

however, the manipulate function, which shows a point that bounces like the ball should, does not. It returns an error
Coordinate {0, {5.}} should be a pair of numbers, or a Scaled or Offset form.
What am i doing wrong with this code?

A: As explained in the comment. The sol yields {y[t]->...}. This argument will be evaluated in Plot but not with Point. If the aim is just to see bounce on vertical line you just have to take first part of sol (e.g First[sol]. If you want to plot y v time he is one of many ways:
sol = y[t] /.
   First@NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,
      WhenEvent[y[t] == 0, y'[t] -> -0.9 y'[t]]}, y, {t, 0, 10}];
f[p_] := Plot[sol, {t, 0, 10},
   Epilog -> {Red, PointSize[0.02], Point[{p, (sol /. t -> p)}]},
   Frame -> True, Background -> Black];
Animate[f[p], {p, 0, 10}]


text:
Q: Runtime Error Cannot find module "angular" I am practicing App development in Ionic 3(Latest Version) and getting the error as follows:

Runtime Error Cannot find module "angular"

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import {AngularFireModule} from 'angularfire2';

import { MyApp } from './app.component';
import { ShoppingListPage } from '../pages/shopping-list/shopping-list';
import { FIREBASE_CREDENTIALS } from './firebase.credentials';

@NgModule({
  declarations: [
    MyApp,
    ShoppingListPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),

    //Initialize AngularFire with credentials from the dashboard
    AngularFireModule.initializeApp(FIREBASE_CREDENTIALS)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ShoppingListPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

app.component.ts
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = 'ShoppingListPage';

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

shopping-list.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage({})
@Component({
  selector: 'page-shopping-list',
  templateUrl: 'shopping-list.html',
})
export class ShoppingListPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ShoppingListPage');
  }

}


text:
Q: Send SMS using phone from computer I need my computer program to be able to send and receive SMS messages. The software has to run independent of the Internet so using a web based SMS gateway is not the solution.
The software should be running from a linux or a Windows machine. Windows is more important for my usecase. My program is in Java but I guess there may be solutions independent of the programming language.
I am considering one of the following options.
Kannel http://www.kannel.org/ Although supported for Linux I guess I could find a way to compile it in windows like done here: http://www.ddj.co.za/kannel-for-windows
The other one seems a more lightweight option http://smsj.sourceforge.net/
Which of these or something else that you have in mind could be a better way of sending SMS via computer without an internet connection?
I am considering using these libraries so I don't have to program all the AT Commands.
Also how do I connect my phone to the computer? For example will it be fine if I just connect my phone with a USB cable when using kannel.
Update:
I need to use simple GSM phones and not depend on IOS or Android specific features.

A: Perhaps not want you needed or wanted, but maybe useful for others: When I had my iPhone jailbroken there was an Cydia app I used to send SMS from my computer through my phone, BiteSMS.
You had to ssh in and then something similar to:
/Applications/biteSMS.app/biteSMS -send -carrier 077xxxxxx "The message goes here"

Obviously you replace 077xxx with the number you want to send to.
It looks like it is fairly similar process with Android, check out this question on doing this through Android. Again this requires a ssh connection to the phone. Also have a google on 'Sending sms from commandline' there are other resources available.
As for other methods, I can't see any viable options without attaching a phone to your computer and accessing the OS and ssh seems the easiest way to do this.

A: Try smslib.org + some GSM modem.


text:
Q: How can I run sudo hidd --search without a password? If I run hidd --search it says HID create error 13 (Permission denied)
If I run as sudo it connects fine.
I want this script to run on login.  I saw how to edit sudoers, but will it create a security weakness if I add
%MYNAME ALL = NOPASSWD: /usr/bin/hidd
Is there a group I can add myself to that means I can run this command without sudo?

A: You can run it without a password by editing the /etc/sudoers file as you mentioned.  One step further would be to append alias hidd='sudo hidd' to your  ~/.bashrc file.
I don't know of any other way besides sudo.
If it needs root to run, I do believe groups won't help you.  However, if it has a daemon running as root [Like wicd], groups might help you out, but I would tend to doubt it.


text:
Q: Program shuts off without anything C# using System;

namespace Zadacha
{
    class Zadacha
    {
        static int Read(int x, int y)
        {
            Random rnd = new Random();
            Console.WriteLine("Vuvedete minimalna velichina");
            string MinValue = Console.ReadLine();
            Console.WriteLine("Vuvedete maximalna velichina");
            string MaxValue = Console.ReadLine();
            int.TryParse(MinValue, out x);
            int.TryParse(MaxValue, out y);
            int value = rnd.Next(x, y);
            Console.WriteLine("Proizvodnoto chislo e: " + value);
            Console.ReadKey(true);
            return value;
        }
        static void Main()
        {

        }
    }
}

This is my code, program just starts and shutdowns after a second with no text in the console app. Everything seems fine and i do not know what is wrong. It is a uni task.

A: You don't do anything in your Main method - you need to call your Read(x,y) method at least, and/or Console.ReadLine(); in order for something to happen.
For example
static void Main()
{
   Read(1,2);
}

A: Is this what you are trying to achieve? Console apps start from Main() so you'll have to put something in there for the program to work. I guess you don't actually want to feed Read() two int you want to get the users input?
using System;

namespace Zadacha
{
    class Zadacha
    {
        static int Read()
        {
            int x = 0;
            int y = 0;
            Random rnd = new Random();
            Console.WriteLine("Vuvedete minimalna velichina");
            string MinValue = Console.ReadLine();
            Console.WriteLine("Vuvedete maximalna velichina");
            string MaxValue = Console.ReadLine();
            int.TryParse(MinValue, out x);
            int.TryParse(MaxValue, out y);
            int value = rnd.Next(x, y);
            Console.WriteLine("Proizvodnoto chislo e: " + value);
            Console.ReadKey(true);
            return value;
        }

        static void Main()
        {
            Read();
        }
    }
}


text:
Q: Instancing maya objects with a sequential suffix, object name string not seen by cmds.instance I have a question about string usage in lists in python for Maya. I am writing a script meant to take a selected object, then instance it 100 times with random translate, scale, and orient attributes. The script itself works and does what it's meant to, however I'm not being able to decipher how to instance the objects with the original object name, and then add a suffix that ends with "_instance#", where # assigns 1, 2, 3, etc. in order to the copies of the original mesh. This is where I'm at so far:
#Capture selected objects, sort into list
    thing = MC.ls(sl=True)
    print thing

#Create instances of objects
    instanceObj = MC.instance(thing, name='thing' + '_instance#')

This returns a result that looks like "thing_instance1, thing_instance2".
Following this, I figured the single quote around the string for the object was causing it to just name it "thing", so I attempted to write it as follows
MC.instance(thing, name=thing + '_instance1'

I guess because instance uses a list, it's not accepting the second usage of the string as valid and returns a concatenate error. I've tried rewriting this a few times and the closest I get is with
instanceObj = MC.instance(thing)

which results in a list of (pCube1,2,3,4), but is lacking the suffix.
I'm not sure where to go from here to end up with a result where the instanced objects are named with the convention "pCube1_instance1, pCube1_instance2" etc.
Any assistance would be appreciated.

A: It is not clear if you want to use only one source object or more. In any case the
MC.ls(sl=True)

returns a list of strings. And concatenating a list and a string does not work. So use thing[0] or simply
MC.ls(sl=True)[0]

If you get errormessages, please always include the message in your question, it helps a lot to see what error appears.


text:
Q: Javascript mini validation script I'm new to js. trying to create mini validation function which will check fields if they're empty or not.
What i wanna do is, to call func like that checkIfEmpty("fullname, email,..."), then inside function, check each field seperated by comma, collect empty fields to one array, and check at the end if this array is empty or not. Tried something like following func, but don't know all alternatives of php functions in js. Please help me to realize my idea..
function checkIfEmpty(fields)
{
    var emptyFields=new Array();
    fields=fields.split(',');
    foreach(fields as field)
    {
        if (!field.val()) {
            field.attr('class', 'invalid');
            emptyFields[] = field;
        }
        }
        if(emptyFields.length()==0){return true;}
        else {return false;}
}

A: Seems like you want something like this:
$("input:text").each(function(i, field) {
     if (!field.val()) {
         field.addClass('invalid');
     }
});
return ($("input.invald").length > 0); // return true if invalid fields

A: You could also set a class on each input that not suppose to be empty, then on form submission check each input that has this class.
$('#form_id').submit(function() {
    $('.required').each(function() {
        // if a input field that's required is empty
        // we add the class '.invalid'
        if(!$(this).val()) {
           $(this).addClass('invalid');
        }
    });

    // prevent the submission if number
    // there is required fields still empty
    return ($('input.invalid').length == 0);
});

This is an example form with one required field called email:
<form method="POST">
  <input type="text" name="email" class="required" />
  <input type="text" name="firstname" />
  <input type="text" name="lastname" />
  <input type="submit" value="SEND" />
</form>


text:
Q: What is the XSSAttack option_name for in the options table? I am working on eliminating malware from a site and reviewed the entries in the options table. Found an "option_name" of XSSAttack with an "option_value" of 1.
Lots of searches on google and on the Wordpress.org site as well as others. Cannot find any information on this.
Is it something I should leave there, or is it something entered by malware?


text:
Q: Annotate NSArray * in Objective-C so that it is bridged to Array Is there a way to annotate an NSArray of NSNumber:
@property (nonatomic) NSArray<NSNumber *> *myProperty

in Objective-C, so that it will be imported in Swift as
var myProperty: [Int] instead of var myProperty: [NSNumber]?
I know of NS_SWIFT_NAME, but that does not allow changing the type.

A: Unfortunately you can't change the static type when importing a symbol from Objective-C.
But you can assign a Swift Int array without any type cast (assuming foo is an instance of the ObjC class). However the type doesn't change.
foo.myProperty = [1, 2, 3, 4, 5]
print(type(of: foo.myProperty)) // Optional<Array<NSNumber>>

On the other hand to get a distinct [Int] type you have to cast the type
let mySwiftProperty = foo.myProperty as! [Int]
print(type(of: mySwiftProperty)) // Array<Int>


text:
Q: how to include shared object in python I want to access from within python to a precompiled library: tecio.so, (found at http://www.tecplot.com/downloads/tecio-library/) to write binary file from within python. I am very new to this, and I am not a real expert of c++, my in my understanding, with cython or ctypes it should be possible to use those function from python.
How can I do that?
The following example show how the library is used in c++ code, if it helps.
/* This example creates a simple set of IJ-ordered zones */
/* DOCSTART:ij_ordered.txt*/
#include "TECIO.h"
#include "MASTER.h" /* for defintion of NULL */

int main()
{
    INTEGER4 Debug      = 1;
    INTEGER4 VIsDouble  = 0;
    INTEGER4 FileType   = 0;
    INTEGER4 FileFormat = 0; // 0 == PLT, 1 == SZPLT
    INTEGER4 I          = 0; /* Used to track return codes */

    /*
     * Open the file and write the tecplot datafile
     * header information
     */
    I = TECINI142((char*)"IJ Ordered Zones", /* Name of the entire
                                              * dataset.
                                              */
                  (char*)"X Y P",  /* Defines the variables for the data
                                    * file. Each zone must contain each of
                                    * the variables listed here. The order
                                    * of the variables in the list is used
                                    * to define the variable number (e.g.
                                    * X is Var 1).
                                    */
                  (char*)"ij_ordered.plt",
                  (char*)".",      /* Scratch Directory */
                  &FileFormat,
                  &FileType,
                  &Debug,
                  &VIsDouble);

    float X1[4];
    float Y1[4];
    float P1[4];
    float X2[4];
    float Y2[4];
    float P2[4];

    INTEGER4 ICellMax                 = 0;
    INTEGER4 JCellMax                 = 0;
    INTEGER4 KCellMax                 = 0;
    INTEGER4 DIsDouble                = 0;
    double   SolTime                  = 360.0;
    INTEGER4 StrandID                 = 0;      /* StaticZone */
    INTEGER4 ParentZn                 = 0;
    INTEGER4 IsBlock                  = 1;      /* Block */
    INTEGER4 NFConns                  = 0;
    INTEGER4 FNMode                   = 0;
    INTEGER4 TotalNumFaceNodes        = 1;
    INTEGER4 TotalNumBndryFaces       = 1;
    INTEGER4 TotalNumBndryConnections = 1;
    INTEGER4 ShrConn                  = 0;

    /*Ordered Zone Parameters*/
    INTEGER4 IMax = 2;
    INTEGER4 JMax = 2;
    INTEGER4 KMax = 1;

//    X1[0] = .125;
//    Y1[0] = .5;
//    P1[0] = 5;

//    X1[1] = .625;
//    Y1[1] = .5;
//    P1[1] = 7.5;

//    X1[2] = .125;
//    Y1[2] = .875;
//    P1[2] = 10;

//    X1[3] = .625;
//    Y1[3] = .875;
//    P1[3] = 7.5;

//    X2[0] = .375;
//    Y2[0] = .125;
//    P2[0] = 5;

//    X2[1] = .875;
//    Y2[1] = .125;
//    P2[1] = 7.5;

//    X2[2] = .375;
//    Y2[2] = .5;
//    P2[2] = 10;

//    X2[3] = .875;
//    Y2[3] = .5;
//    P2[3] = 7.5;

    /*  Ordered Zone */
    INTEGER4 ZoneType = 0;
    I = TECZNE142((char*)"Ordered Zone",
                  &ZoneType,
                  &IMax,
                  &JMax,
                  &KMax,
                  &ICellMax,
                  &JCellMax,
                  &KCellMax,
                  &SolTime,
                  &StrandID,
                  &ParentZn,
                  &IsBlock,
                  &NFConns,
                  &FNMode,
                  &TotalNumFaceNodes,
                  &TotalNumBndryFaces,
                  &TotalNumBndryConnections,
                  NULL,
                  NULL,
                  NULL,
                  &ShrConn);
    INTEGER4 III = IMax * JMax * KMax;
    I   = TECDAT142(&III, X1, &DIsDouble);
    I   = TECDAT142(&III, Y1, &DIsDouble);
    I   = TECDAT142(&III, P1, &DIsDouble);

    I = TECZNE142((char*)"Ordered Zone2",
                  &ZoneType,
                  &IMax,
                  &JMax,
                  &KMax,
                  &ICellMax,
                  &JCellMax,
                  &KCellMax,
                  &SolTime,
                  &StrandID,
                  &ParentZn,
                  &IsBlock,
                  &NFConns,
                  &FNMode,
                  &TotalNumFaceNodes,
                  &TotalNumBndryFaces,
                  &TotalNumBndryConnections,
                  NULL,
                  NULL,
                  NULL,
                  &ShrConn);

    I   = TECDAT142(&III, X2, &DIsDouble);
    I   = TECDAT142(&III, Y2, &DIsDouble);
    I   = TECDAT142(&III, P2, &DIsDouble);

    I = TECEND142();
    return 0;
}
/* DOCEND */

Edit:My humble attempts with ctypes (but, again, I was not sure of what I were doing):
import ctypes
lib=ctypes.CDLL("libtecio.so")
lib.tecini142(ctypes.c_char_p("IJ Ordered Zones"),ctypes.c_char_p("X Y P"),ctypes.c_char_p("ij_ordered.plt"),ctypes.c_char_p("."),ctypes.c_void_p(0),ctypes.c_void_p(0),ctypes.c_void_p(1),ctypes.c_void_p(0))
Segmentation fault (core dumped)

I am pretty sure that my attempt doesn't add any value to the question.


text:
Q: How can I set a NSTimer based on what button is pressed? I have a game where I set a timer.
-(void)setTimer{
self->mTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self   selector:@selector(buttonNotPushed) userInfo: nil repeats:NO];
}

-(void)resetTimer{
[self->mTimer invalidate];
self->mTimer = nil;
}

Currently, when a user hits the Play button, the timer will be 5 seconds. There are other buttons which every time they are pressed I run
- (IBAction)buttonPressed:(id)sender {

if ([condition]) {
[self resetTimer];
[self setTimer];
}
else ([self gameOver]);
}

I would like to create a practice/kid mode where the timer is 10 seconds. Is there a shorter way I can do this besides replicating the whole game again on another viewController and setting the timer?

A: Rather than using an explicit 5.0 in setTimer, create an integer property and reference that. So, create interval in your @interface
@property (nonatomic) CGFloat interval;

And then set it to 5.0 or 10.0 as appropriate. And then your setTimer is merely:
- (void)setTimer {
    mTimer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(buttonNotPushed) userInfo: nil repeats:NO];
}


text:
Q: gnome-panel messed up after installing ATI driver After installing the proprietary ati driver, the gnome-panel in the gnome3 shell is completely messed up. uninstalling the driver doesn't work, any ideas?

A: I managed to install the 11.9 driver manually what overwrites the driver (11.8). Download the new Catalyst Driver here http://support.amd.com/, then change to the directory where the driver is located, then:
sudo sh ati-driver-installer....run --buildpkg Ubuntu/oneiric

install the *.deb's with
sudo dpkg -i *.deb

reboot. Now it should be overwritten. Gnome Shell still has graphic bugs though, but it runs.


text:
Q: Django translation escape % sign I'm trying to translate some text that contains a percent sign like so:
{% trans "100% butterfly" %}
When I run the makemessages command, I get the following output in my german .po file:
#: .\appName\templates\appName\butterflies.html:54
#, fuzzy, python-format
#| msgid ""
#| "100% butterfly"
msgid ""
"100%% butterfly"
msgstr ""
"100% shmetterling"

Which when compiled, fails to translate the text to German. I've tried doing {% trans "100%% butterfly" %}, but this causes the pages to display "100%% butterfly" when viewed in both german and english. I've also tried using blocktrans tags instead to translate the text, with the same result.
Manually erasing the extra % in the .po file, along with the #, fuzzy, python-format line works, but I'd rather not have to do this for every % sign I'm trying to translate.
How do I escape this in my HTML so that Django stops generating a fuzzy translation in the .po file and doesn't get confused thinking I'm trying to do some python formatting?

A: According to this comment in Django's Trac, adding a translator comment to deactivate python format above the string that you want to translate can fix / workaround this issue.
If the text to translate is in your Python code, use:
# Translator: xgettext:no-python-format
_('100% butterfly')

For trans template tag, you can try:
{# Translators: xgettext:no-python-format #}
{% trans "100% butterfly" %}

as explained in the doc.

A: I think the better way is to use the html code : %
It is the most elegant way for dealing with django translation for example.

A: Turns out this is a Django problem with a fix possibly coming in Django 1.9.
One workaround is to do:
{% blocktrans with percent="%" %}100{{percent}} butterfly{% endblocktrans %}
Which essentially embraces the python formatting it thinks you're trying to do when you put a % symbol in your trans text. It's verbose and sucks, but it works.


text:
Q: when I every refresh page load button_click events run too I have code Page_Load and btnGonder_Click.I records the some data to database when I click the btnGonder.And I get and show data in the datalist the code which inside the page_load.The problem is that  When I every refresh the page,it runs btn_Gonder_Click events and so it records the same data to database.my code is below.
 protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
{
        Cevap cevaplar = new Cevap();
        int soru_id = Convert.ToInt32(Request.QueryString["Soru_Id"]);
        cevaplar.soru_id = soru_id;
        DataTable dtcvp = new DataTable();
        dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
        datalistcevaplar.DataSource = dtcvp;
        datalistcevaplar.DataBind();
}
}

 protected void btnGonder_Click(object sender, EventArgs e)
{
        Users kullanicim = new Users();
        HttpCookie bilgiler = Request.Cookies["Kullanicicookie"];
        kullanicim.mail = bilgiler["mail"];
        int donenkullaniciid = kullanicim.Kullanici_Id_Donder();
        cevaplar.cvpveren_id = donenkullaniciid;
        Sorular sorular = new Sorular();
        sorular.Cevap_Sayisi_Artir(soru_id);
        bool durum = cevaplar.Cevap_Ekle();
        if (durum)
        {
            lblDurum.Text = "Cevabınız Eklenmiştir";
        }
        else
        {
            lblDurum.Text = "Cevabınız Eklenmemiştir";
        }
        DataTable dtcvp = new DataTable();
        dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
        datalistcevaplar.DataSource = dtcvp;
        datalistcevaplar.DataBind();
}

A: Page refresh re-fires the same event which has caused the previous postback , so if you refresh the page after clicking the button then button click event will fire. Now to avoid that you have gor multiple solutions. see here

A: Use this.IsPostBack inside btnGonder_Click() to check the status of submission and return

A: If you don't want to resubmit the page on refresh then from btnGonder_Click you need to redirect to the same page instead of directly binding data. As this is the basic problem with the Asp.net application.
Do Response.Redirect and pass the name of the page.

A: If you have already clicked on a button which caused a post back. Next onwards pressing F5, the browser will ask you RESEND which means click the button again. This is normal browser behaviour

A: Basically you need a workaround to check if it is a page refresh or an actual  button click. You can do as below:
The key here is ViewState["IsPageRefresh"] & Session["IsPageRefresh"].  Note that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden field may be used.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["IsPageRefresh"] = Session["IsPageRefresh"];
}
protected void btnPost_Click(object sender, EventArgs e)
{
if (Session["IsPageRefresh"].ToString() == ViewState["IsPageRefresh"].ToString())
{
//Put your database INSERT code here
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}

One simple trick but may be not a standard practice  I too agree is below:
Don't disable the button in the server side. After the page has finished  loading the button works as usual.
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function checkButton() {
            var btn = document.getElementById("btnGonder");
            btn.disabled = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btnGonder" runat="server" onclick="btnGonder_Click"
         OnClientClick="checkButton();" />
    </div>
    </form>
</body>


text:
Q: how to auto refresh div value when add/edit value in Sql table? I'm using MVC 5 .net with Entity Framework.
I want to design client dashboard with list out latest data from sql database.
so how to call ajax method or refresh particular table/div value whenever any value add/edit from other source in database.
I want to call function/ajax method only when any value add/edit in database from any other source without unnecessary auto refresh using setInterval function.
please help, thanks in advance.

A: There are several ways of accomplishing this.

*

*Easiest is to simply poll the data at set intervals from the server. And when it changes update. To the user this will look like changes are getting pushed out. This will also not require you to do anything special besides calling what you are already doing except in a setInteraval

*You could implement websockets. This enables you to literally push data from the server to a javascript function. The support for this is pretty widespread, and there are many great tutorials for this.

*Implement a framework like SignalR. This is your most complete and most bakward compatible solution. If there is support for websockets it will be used otherwise it will fall back to simple ajax calls.
Personally Id opt for option 1. unless you have some major traffic or the queries are super heavy to compute on the server. You could even implement a second API that you can call to check for updates very frequently, the second api might return an integer, if that integer is higher than last time we know there is an update and we should make the big heavy query. If this dosent work go for signalR or something similar. https://www.reddit.com/r/dotnet/comments/68rgxq/signalr_alternatives/


text:
Q: how to open mysqld.log file I am unable to start mysql on centos vmware.
I am trying to see the log file but I cant figure out how to  open the file and see any error messages in it. Can someone show how to open the log file
the file does exist and returned this when I ran
 ls -l mysqld.log

-rw-r-----. 1 mysql mysql 1279 Apr 21 08:12 mysqld.log
however, when I do this
gedit mysqld.log

I get this error message in gedit window.
"Could not open the file /var/log.mysqld.log"
"you dont have the permissions n ecessary to open the file."
so how to view contents of this file
here are the contents of my.cnf file if it helps
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

A: Have you tried "sudo" command?
(if you have the super user permission.)
I mean:
$ sodu gedit mysqld.log

and then input your password.


text:
Q: Java "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable" I'm trying to implement a sorted list as a simple exercise in Java. To make it generic I have an add(Comparable obj) so I can use it with any class that implements the Comparable interface.
But, when I use obj.compareTo(...) anywhere in the code I get "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable" from the compiler (with -Xlint:unchecked option). The code works just fine but I can't figure out how to get rid of that annoying message.
Any hints?

A: Using an interface like Comparable as a method parameter doesn't make your class generic, declaring and using  generic type parameters is how you make it generic.
Quick-n-dirty answer: You are receiving the warning because you are using Comparable, which is a generic interface, as a raw type, rather than giving it a specific type arguments, like Comparable<String>.
To fix this, make add() generic by specifying type parameters:
<T extends Comparable<? super T>> add(T obj) { ... }

But this quick fix won't fix the general problem that your class is unsafe. After all, shouldn't all the objects in your list be of the same type?  This add method lets you still different types into the same list.  What happens when you try to compare heterogeneous types (how do you compareTo an Object instance to an Number instance, or to a String instance)? You can depend on the user of the class to do the right thing and ensure they only stick 1 kind of thing in your list, but a generic class will let the compiler enforce this rule.
The better approach: The proper fix is that your sorted list class should be probably be generic overall, just like the other collection classes in java.util.
You would probably like something like:
public class SortedList<T extends Comparable<? super T>>
implements Iterable<T> {
    ...
    public void add(T item) { ... }
    public Iterator<T> iterator() { ... }
    ...
}

Note that when the class is generic, the add method uses the classes formal type parameter rather than declaring its own formal type parameter.
There should be plenty of tutorials on the web on how to create a generic class, but here's a quick example:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ002
class Pair<X,Y>  {
  private X first;
  private Y second;
  public Pair(X a1, Y a2) {
    first  = a1;
    second = a2;
  }
  public X getFirst()  { return first; }
  public Y getSecond() { return second; }
  public void setFirst(X arg)  { first = arg; }
  public void setSecond(Y arg) { second = arg; }
}

A: In essence, this warning says that Comparable object can't be compared to arbitrary objects. Comparable<T> is a generic interface, where type parameter T specifies the type of the object this object can be compared to.
So, in order to use Comparable<T> correctly, you need to make your sorted list generic, to express a constraint that your list stores objects that can be compared to each other, something like this:
public class SortedList<T extends Comparable<? super T>> {
    public void add(T obj) { ... }
    ...
}

A: You need to "check" or define the Comparable object like so:
add(Comparable<Object> obj)


text:
Q: How to add items from a textbox to an array? C# I want to add items from 13 textboxes to the 13 elements of an array.  All at one time using a button.  How would I go about that?
    List<double> scoreArray = new List<double>();
        TextBox[] textBoxes = { week1Box, week2Box, week3Box, week4Box, week5Box, week6Box, week7Box, week8Box, week9Box, week10Box, week11Box, week12Box, week13Box };
            for (int i = 0; i < textBoxes.Length; i++)
        {
         scoreArray.Add(Convert.ToDouble(textBoxes[i].Text));
        }

A: Put an event handler on the button's Click event.
In the handler, extract the textbox values and set them into the values of the array.
Easy peasy!


text:
Q: Express view engine not recognizing data sent to front end I am making a website and I am trying to set up a review option. I query the reviews from my Mysql DB and res.send the data to the ".pug" file. The data does not show. However it does show if I put type out the data manually. such as
{review: "this is a review"}

this works just fine but when I try to access the data directly it does not.
var review;
app.get('/', function(req,res) {
con.query("SELECT * FROM reviews.eatingReviews", function(err, rows) {
    review = rows[0].Review;
    console.log(review)
    if (err) throw err;
});
res.render('test',
    {review: review});

pug file
   extends layout
   block content
      p= review

Data
 RowDataPacket {
 Name: 'James Laskey',
 Email: 'james.laskey23@gmail.com',
 Review: 'This book is classic!',
 Rating: 5 }

I need to get this information to be recognized by the html. It keeps showing as undefined. I tried JSON.parse on the object and that did not work either. Any thoughts on how to get around this?

A: The view is empty because res.render is executed before con.query finish fetching your data from database. con.query is a async function.
As workaround, you must put res.render inside con.query:
con.query("SELECT * FROM reviews.eatingReviews", function(err, rows) {
    review = rows[0].Review;
    console.log(review)
    if (err) throw err;

    res.render('test',
      {review: review});
});


text:
Q: Lenovo X201 screen - black now green My trusty Lenovo X201 (running Ubuntu 14.10) has developed a problem with the screen. The colour black is now green. Initially, I could make the problem go away by moving the screen back and forth but now the problem is permanent. Here is a picture of it against a laptop on the left that properly displays colours. It also now has some problems with screen brightness.
What I want to know is whether this is a problem with the screen or the graphics chipset. I want to repair it myself but don't want to buy a new screen only to find it was the graphics chipset. Is there a simple way of knowing for sure? An external monitor works fine. It seems like this must be a screen problem but would like to know for sure.

A: It seems to me that your problem is caused by a failing screen cable. This kind of failures manifests itself by flickering lines or distorted colors that initially go away after moving the lid, but then get worse and worse until becoming permanent.
Such cables are easily available and a bit cheaper than screens (which in your case is probably fine). Replacing them requires some manual skills, though: laptop are quite hard to disassemble. I recommend you to find a service manual or a disassembly video online, they are often helpful.

A: If it went away when you moved the screen back and forth, that points to some sort of physical problem in the connection between the keyboard and the screen.


text:
Q: Take first non-0 value or last 0 value if that's all there is Ciao,
Here is my replicating example.
HAVE <- data.frame(ID=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6),
                   ABSENCE=c(NA,NA,NA,0,0,0,0,0,1,NA,0,NA,0,1,2,0,0,0),
                   TIME=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))

WANT <- data.frame(ID=c(1,2,3,4,5,6),
                   ABSENCE=c(NA,0,1,0,1,0),
                   TIME=c(NA,3,3,2,2,3))

The tall data file HAVE is the one I need to convert to WANT. So essentially for each ID I need to identify the first non-zero value and that value goes into the data file WANT. If all values of absence is NA than TIME is NA. If all values of ABSENCE is 0 then I report the last possible row in WANT (as reflected in the TIME variable)
This is my attempt:
WANT <- group_by(HAVE,ID) %>% slice(seq_len(min(which(ABSENCE > 0), n())))

but I do not know how to take the last of the 0 rows if there are only 0s.

A: library(data.table)
setDT(HAVE)

res = unique(HAVE[, .(ID)])

# look up first ABSENCE > 0
res[, c("ABSENCE", "TIME") := unique(HAVE[ABSENCE > 0], by="ID")[.SD, on=.(ID), .(ABSENCE, TIME)]]

# if nothing was found, look up last ABSENCE == 0
res[is.na(ABSENCE), c("ABSENCE", "TIME") := unique(HAVE[ABSENCE == 0], by="ID", fromLast=TRUE)[.SD, on=.(ID), .(ABSENCE, TIME)]]

# check
all.equal(as.data.frame(res), WANT)
# [1] TRUE

   ID ABSENCE TIME
1:  1      NA   NA
2:  2       0    3
3:  3       1    3
4:  4       0    2
5:  5       1    2
6:  6       0    3

I'm using data.table since the tidyverse does not and never will support sub-assignment / modifying only rows selected by a condition (like the is.na(ABSENCE) here).
If there two rules can be made more consistent with each other, this should be doable in a left join or a single group_by + slice as the OP attempted, though. Okay, here's one way, though it looks impossible to debug:
HAVE %>%
  arrange(ID, -(ABSENCE > 0), TIME*(ABSENCE > 0), -TIME) %>%
  distinct(ID, .keep_all = TRUE)

  ID ABSENCE TIME
1  1      NA    3
2  2       0    3
3  3       1    3
4  4       0    2
5  5       1    2
6  6       0    3

A: Using data.table as well, based on subsetting the .I row counter:
WANT <- HAVE[
  HAVE[,
    if(all(is.na(ABSENCE))) .I[1] else
    if(!any(ABSENCE > 0, na.rm=TRUE)) max(.I[ABSENCE==0], na.rm=TRUE) else
    min(.I[ABSENCE > 0], na.rm=TRUE),
    by=ID
  ]$V1,
]
WANT[is.na(ABSENCE), TIME := NA_integer_]

#   ID ABSENCE TIME
#1:  1      NA   NA
#2:  2       0    3
#3:  3       1    3
#4:  4       0    2
#5:  5       1    2
#6:  6       0    3

A: Here are two approaches using dplyr and custom functions. Both rely on the data being sorted by TIME.
Filter Approach
# We'll use this function inside filter() to keep only the desired rows
flag_wanted <- function(absence){

  flags <- rep(FALSE, length(absence))

  if (any(absence > 0, na.rm = TRUE)) {
  # There's a nonzero value somewhere in x; we want the first one.

    flags[which.max(absence > 0)] <- TRUE

  } else if (any(absence == 0, na.rm = TRUE)) {
  # There's a zero value somewhere in x; we want the last one.

    flags[max(which(absence == 0))] <- TRUE

  } else {
  # All values are NA; we want the last row

    flags[length(absence)] <- TRUE

  }
  return(flags)
}

# After filtering, we have to flip TIME to NA if ABSENCE is NA
HAVE %>%
  arrange(ID, TIME) %>%
  group_by(ID) %>%
  filter(flag_wanted(ABSENCE)) %>%
  mutate(TIME = ifelse(is.na(ABSENCE), NA, TIME)) %>%
  ungroup()

# A tibble: 6 x 3
     ID ABSENCE  TIME
  <dbl>   <dbl> <dbl>
1    1.     NA    NA
2    2.      0.    3.
3    3.      1.    3.
4    4.      0.    2.
5    5.      1.    2.
6    6.      0.    3.

The filter() step reduces the dataframe to the rows you need. Since it doesn't modify the TIME values, we need to mutate() as well.
Summarize Approach
# This function captures the general logic of getting the value of one variable
# based on the value of another
get_wanted <- function(of_this, by_this){

  # If there are any positive values of `by_this`, use the first
  if (any(by_this > 0, na.rm = TRUE)) {

    return( of_this[ which.max(by_this > 0) ] )

  }

  # If there are any zero values of `by_this`, use the last
  if (any(by_this == 0, na.rm = TRUE)) {

    return( of_this[ max(which(by_this == 0)) ] )

  }
  # Otherwise, use NA
  return(NA)
}

HAVE %>%
  arrange(ID, TIME) %>%
  group_by(ID) %>%
  summarize(TIME = get_first_nz(of_this = TIME, by_this = ABSENCE),
            ABSENCE = get_first_nz(of_this = ABSENCE, by_this = ABSENCE))

# A tibble: 6 x 3
     ID  TIME ABSENCE
  <dbl> <dbl>   <dbl>
1    1.   NA      NA
2    2.    3.      0.
3    3.    3.      1.
4    4.    2.      0.
5    5.    2.      1.
6    6.    3.      0.

The order of summarization matters because we're overwriting variables, so this approach is risky. It only produces the output WANT if you summarize TIME and then ABSENCE.


text:
Q: Difference between junction points in old schematic What's the difference between the black circle and the white one in this old schematic? Of course the black ones are junctions, but are the white circles a pin, or an input of some kind? I'm trying to redraw the circuit in KiCad but I can't find a way to express the "white" junction.
The attached picture is a Tone assembly of a vintage amplifier from the 70s.

A: Notice that the hollow circles are only on the potentiometer connections. If the potentiometers are mounted off-board separate wires will be attached to those points.

Figure 1. Off-board potentiometer wiring example. Image source: blog.mklec.com
Guitar Effects Pedal Offboard Wiring demystified. (This seems to be offline now.)
On your PCB design I would use a pin connector symbol - maybe a pin header.

A: This complements Transistor's correct answer.
As Transistor says, the white circles represent potentiometer terminals.
They happen to be "on board" in this case but that is not obvious from the diagram.
The manuals linked below show the correspondence between diagram and physical reality.
Here is an image of the PCB copper and component layout, plus your circuit.
[If you have this information available or any related information then providing it would help us greatly]. I have produced a negative image to make the tracks somewhat (but not very) more visible.
This is from the bottom of page 12 of
Marantz - Mara 00177 - Service Manual 1072/1050
Also a less good version here
The diagram is smaller but possibly more legible here
The potentiometers are in the four corners.
I have outlines RF10 & CF06 on both images to show how a series connection of 2 components is depicted on the circuit diagram.


text:
Q: Building a 2D XNA Game Engine I'd like to build an engine in XNA, primarily for a 2D RPG. At first, I began abstracting out some classes and built a Sprite class which wrapped a Vector2 and a Texture2D, and tried loading in content from the Sprite class' constructor. However, this didn't work. Now, it appears that I have to load all of the sprites within the Game class' LoadContent method. Is there anyway around this? I'd like to separate the actual Game Content from the inner workings of the engine, if possible.

A: Yes, you can pass the ContentManager as a parameter to your constructor so you can use this in your class. e.g.
public class MyClass
{
    ContentManager content;
    Texture2D sprite;

    public MyClass(ContentManager content)
    {
        this.content = content;
    }

    public void LoadSprite(string filename)
    {
        sprite = this.content.Load<Texture2D>(filename);
    }
}

public class Game1
{
    ContentManager content;

    public void LoadContent()
    {
         MyClass myclass = new MyClass(content);
    }

}


text:
Q: Align vertical 3 plots in 2 rows in cowplot package in R I would like to align vertical plot from row 1 and plot from row 2. It didn't matter how hard I try, but it did not let me align.

Any ideas?

library(dplyr)
library(forcats)
library(ggplot2)
library(cowplot)

city_mpg <- mpg %>%
  mutate(class = fct_lump(class, 4, other_level = "other")) %>%
  group_by(class) %>%
  summarize(
    mean_mpg = mean(cty),
    count = n()
  ) %>% mutate(
    class = fct_reorder(class, count)
  )

p1 <- ggplot(city_mpg, aes(class, count)) +
  geom_col() +
  ylim(0, 65) +
  coord_flip()

p2 <- ggplot(city_mpg, aes(mean_mpg, count)) +
  geom_point()

p3 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point()

first <- plot_grid(p1, p2, align = 'h', axis = 'l',rel_widths = c(2,1))
second <- plot_grid(p3)
plot_grid(first, second,ncol = 1, align = 'v', axis = 'l',rel_heights = c(2,1))

A: The terminology here in terms of ggplot would be that the plots align just fine - it's the panels that do not align.  The "panel" represents the area between the x and y axes, and the "plot" is considered the entire area taken up by the panel + the axis ticks, axis text, and axis titles.
Why is this important?  Well, plot_grid() aligns all plots, but not the panels.  Since p1 has longer y axis text than the y axis text of p3, the area to the left of the panel in p1 is also wider.  When you align the left side of p1 and p3, it means the panel of p3 is to the left of p1.
The simple fix for this is to just add a bit of a margin to p3.  By using theme(plot.margin), we can add some room to the left of p3 so that the area to the left of the panel in p3 is roughly similar to that in p1.  The unfortunate thing is that it's not really very straightforward to do this in any other way than trial and error.  You have to add some margin and plot again to see if it was too much or too little.  In the end, the result works though.  Similarly, I added some margin to the right side of p3 to get the right part of that panel aligned with the right side of the p2 panel.
To fix, the code for p3 now looks like this:
p3 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  theme(plot.margin = margin(l=44, t=0, b=0, r=6, 'pt'))


text:
Q: The git push stops at writing objects 99% I created a new branch from master branch.
But after I changed something and git add and commit, I did git push origin HEAD, but the log showed:
Counting objects: 117, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (91/91), done.
Writing objects:  99% (116/117), 1.30 MiB | 7.00 KiB/s

Some people tell me to try:
git config --global http.postBuffer 524288000

But I tried it on the ~ location, but no use.
So how to fix this?

A: Check your git remote -v output for 'origin': it depends on the protocol used (https or ssh)
HTTPS would involved an HTTPS listener on the remote side, which can be limited on the size it accepts (no matter how big you set http.postBuffer on your client side)
You can switch to SSH and see if that helps.

A: It might simply be taking a long time to upload the added file. The log shows the upload is happening at 7KiB/s. At that speed an 804Mb file will take around 31 hours!
Git's progress indicator Writing objects:  99% (116/117) seems to be based only on the number of objects, it doesn't account for their size. So it's common for it to appear to freeze when the operation gets to a large file.

A: Maybe, it is because my VPN, when I close the Global mode and open the Auto mode, the push will run fast.


text:
Q: Failed to establish connection with 'nominatim.openstreetmap.org'. Max retries exceeded with url For some reason I cannot establish connection with nominatim.openstreetmap.org. Error texts says Max retries exceeded with url but it works fine on my Jupyter Notebook. The issue comes when I run my code in visual studio.
def get_zip_code(self,x):
    geolocator = geopy.geocoders.Nominatim(user_agent="check")
    location = geolocator.reverse("{}, {}".format(x['LATITUDE'],x['LONGITUDE']))
    return location.raw['address']['postcode']

This is the error I get.
geopy.exc.GeocoderUnavailable:HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /reverse?lat=38.75246&lon=-90.37342&format=json&addressdetails=1 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000029697ED9670>: Failed to establish a new connection: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted'))

I have tried closing all the connections with port 443 but did not work. I do not fully understand where this error comes from?


text:
Q: C# Date/Numerical Axis Scale I'm developing a histogram container class and I'm trying to determine where the cut off points should be for the bins.  I'd like the cutoff points to be nice looking numbers, in much that same way that graphs are scaled.
To distill my request into a basic question: Is there a basic method by which data axis labels can be determined from a list of numbers.
For example:
Array{1,6,8,5,12,15,22}

It would make sense to have 5 bins.
Bin Start    Count
0              1
5              3
10             2
15             0
20             1

The bin start stuff is identical to selecting axis labels on a graph in this instance.
For the purpose of this question I don't really care about bins and the histogram, I'm more interested in the graph scale axis label portion of the question.
I will be using C# 4.0 for my app, so nifty solution using linq are welcome.
I've attempted stuff like this in the distant past using some log base 10 scaling stuff, but I never got it to work in great enough detail for this application.  I don't want to do log scaling, I just used base 10 to round to nearest whole numbers. I'd like it to work for large numbers and very small numbers and possibly dates too; although dates can be converted to doubles and parsed that way.
Any resources on the subject would be greatly appreciated.

A: You could start with something simple:
NUM_BINS is a passed argument or constatn (e.g. NUM_BINS = 10)
x is your array of x-values (e.g. int[] x = new int[50])

int numBins = x.Length < NUM_BINS ? x.Length : NUM_BINS;

At this point you could calc a histogram of xPoints, and if the xPoints are heavily weighted to one side of distribution (maybe just count left of midpoint vs. right of midpoint), then use log/exp divisions over range of x[].  If the histogram is flat, use linear divisions.
double[] xAxis = new double[numBins];
double range = x[x.Length-1] - x[0];
CalcAxisValues(xAxis, range, TYPE);  //Type is enum of LOG, EXP, or LINEAR

This function would then equally space points based on the TYPE.