text:
Q: MySQL execute query only if a statement is verified I have this query working well:
SELECT
    Disciplina,
    Categoria,
    IF (MAX(`London 2012`) > 0, 'yes', 'no') AS 'London 2012',
    IF (MAX(`Beijing 2008`) > 0, 'yes', 'no') AS 'Beijing 2008',
    IF (MAX(`Athens 2004`) > 0, 'yes', 'no') AS 'Athens 2004',
    IF (MAX(`Sydney 2000`) > 0, 'yes', 'no') AS 'Sydney 2000',
    IF (MAX(`Atlanta 1996`) > 0, 'yes', 'no') AS 'Atlanta 1996',
    IF (MAX(`Barcelona 1992`) > 0, 'yes', 'no') AS 'Barcelona 1992',
    IF (MAX(`Seoul 1988`) > 0, 'yes', 'no') AS 'Seoul 1988',
    IF (MAX(`Los Angeles 1984`) > 0, 'yes', 'no') AS 'Los Angeles 1984',
    IF (MAX(`Moscow 1980`) > 0, 'yes', 'no') AS 'Moscow 1980',
    IF (MAX(`Montreal 1976`) > 0, 'yes', 'no') AS 'Montreal 1976',
    IF (MAX(`Munich 1972`) > 0, 'yes', 'no') AS 'Munich 1972',
    IF (MAX(`Mexico 1968`) > 0, 'yes', 'no') AS 'Mexico 1968',
    IF (MAX(`Tokyo 1964`) > 0, 'yes', 'no') AS 'Tokyo 1964',
    IF (MAX(`Rome 1960`) > 0, 'yes', 'no') AS 'Rome 1960',
    IF (MAX(`Melbourne / Stockholm 1956`) > 0, 'yes', 'no') AS 'Melbourne / Stockholm 1956',
    IF (MAX(`Helsinki 1952`) > 0, 'yes', 'no') AS 'Helsinki 1952',
    IF (MAX(`London 1948`) > 0, 'yes', 'no') AS 'London 1948',
    IF (MAX(`Berlin 1936`) > 0, 'yes', 'no') AS 'Berlin 1936',
    IF (MAX(`Los Angeles 1932`) > 0, 'yes', 'no') AS 'Los Angeles 1932',
    IF (MAX(`Amsterdam 1928`) > 0, 'yes', 'no') AS 'Amsterdam 1928',
    IF (MAX(`Paris 1924`) > 0, 'yes', 'no') AS 'Paris 1924',
    IF (MAX(`Antwerp 1920`) > 0, 'yes', 'no') AS 'Antwerp 1920',
    IF (MAX(`Stockholm 1912`) > 0, 'yes', 'no') AS 'Stockholm 1912',
    IF (MAX(`London 1908`) > 0, 'yes', 'no') AS 'London 1908',
    IF (MAX(`St Louis 1904`) > 0, 'yes', 'no') AS 'St Louis 1904',
    IF (MAX(`Paris 1900`) > 0, 'yes', 'no') AS 'Paris 1900',
    IF (MAX(`Athens 1896`) > 0, 'yes', 'no') AS 'Athens 1896'
FROM
    (
        SELECT
            Disciplina,
            Categoria,
            IF (Olimpiade = 'London 2012', 1, 0) AS 'London 2012',
            IF (Olimpiade = 'Beijing 2008', 1, 0) AS 'Beijing 2008',
            IF (Olimpiade = 'Athens 2004', 1, 0) AS 'Athens 2004',
            IF (Olimpiade = 'Sydney 2000', 1, 0) AS 'Sydney 2000',
            IF (Olimpiade = 'Atlanta 1996', 1, 0) AS 'Atlanta 1996',
            IF (Olimpiade = 'Barcelona 1992', 1, 0) AS 'Barcelona 1992',
            IF (Olimpiade = 'Seoul 1988', 1, 0) AS 'Seoul 1988',
            IF (Olimpiade = 'Los Angeles 1984', 1, 0) AS 'Los Angeles 1984',
            IF (Olimpiade = 'Moscow 1980', 1, 0) AS 'Moscow 1980',
            IF (Olimpiade = 'Montreal 1976', 1, 0) AS 'Montreal 1976',
            IF (Olimpiade = 'Munich 1972', 1, 0) AS 'Munich 1972',
            IF (Olimpiade = 'Mexico 1968', 1, 0) AS 'Mexico 1968',
            IF (Olimpiade = 'Tokyo 1964', 1, 0) AS 'Tokyo 1964',
            IF (Olimpiade = 'Rome 1960', 1, 0) AS 'Rome 1960',
            IF (Olimpiade = 'Melbourne / Stockholm 1956', 1, 0) AS 'Melbourne / Stockholm 1956',
            IF (Olimpiade = 'Helsinki 1952', 1, 0) AS 'Helsinki 1952',
            IF (Olimpiade = 'London 1948', 1, 0) AS 'London 1948',
            IF (Olimpiade = 'Berlin 1936', 1, 0) AS 'Berlin 1936',
            IF (Olimpiade = 'Los Angeles 1932', 1, 0) AS 'Los Angeles 1932',
            IF (Olimpiade = 'Amsterdam 1928', 1, 0) AS 'Amsterdam 1928',
            IF (Olimpiade = 'Paris 1924', 1, 0) AS 'Paris 1924',
            IF (Olimpiade = 'Antwerp 1920', 1, 0) AS 'Antwerp 1920',
            IF (Olimpiade = 'Stockholm 1912', 1, 0) AS 'Stockholm 1912',
            IF (Olimpiade = 'London 1908', 1, 0) AS 'London 1908',
            IF (Olimpiade = 'St Louis 1904', 1, 0) AS 'St Louis 1904',
            IF (Olimpiade = 'Paris 1900', 1, 0) AS 'Paris 1900',
            IF (Olimpiade = 'Athens 1896', 1, 0) AS 'Athens 1896'
        FROM SummerTotalMedals
        WHERE Sport='Athletics'
    ) AS Games
GROUP BY Disciplina, Categoria
ORDER BY Disciplina ASC, Categoria ASC

I'd like to obtain from this single query, two types of queries.
1) First one to obtain the same information but only for that Disciplina ='yes' at London 2012
2) Second one to obtain the same information for that Disciplina = 'no' at London 2012.
Could I do this? I tried myself but with poor results.

A: I'm not saying anything about this database design... ;)
Why don't you just add a filter in the inner query like this:
1) First one to obtain the same information but only for that Disciplina ='yes' at London 2012
SELECT
    Disciplina,
    Categoria,
    IF (MAX(`London 2012`) > 0, 'yes', 'no') AS 'London 2012',
    IF (MAX(`Beijing 2008`) > 0, 'yes', 'no') AS 'Beijing 2008',
    IF (MAX(`Athens 2004`) > 0, 'yes', 'no') AS 'Athens 2004',
    IF (MAX(`Sydney 2000`) > 0, 'yes', 'no') AS 'Sydney 2000',
    IF (MAX(`Atlanta 1996`) > 0, 'yes', 'no') AS 'Atlanta 1996',
    IF (MAX(`Barcelona 1992`) > 0, 'yes', 'no') AS 'Barcelona 1992',
    IF (MAX(`Seoul 1988`) > 0, 'yes', 'no') AS 'Seoul 1988',
    IF (MAX(`Los Angeles 1984`) > 0, 'yes', 'no') AS 'Los Angeles 1984',
    IF (MAX(`Moscow 1980`) > 0, 'yes', 'no') AS 'Moscow 1980',
    IF (MAX(`Montreal 1976`) > 0, 'yes', 'no') AS 'Montreal 1976',
    IF (MAX(`Munich 1972`) > 0, 'yes', 'no') AS 'Munich 1972',
    IF (MAX(`Mexico 1968`) > 0, 'yes', 'no') AS 'Mexico 1968',
    IF (MAX(`Tokyo 1964`) > 0, 'yes', 'no') AS 'Tokyo 1964',
    IF (MAX(`Rome 1960`) > 0, 'yes', 'no') AS 'Rome 1960',
    IF (MAX(`Melbourne / Stockholm 1956`) > 0, 'yes', 'no') AS 'Melbourne / Stockholm 1956',
    IF (MAX(`Helsinki 1952`) > 0, 'yes', 'no') AS 'Helsinki 1952',
    IF (MAX(`London 1948`) > 0, 'yes', 'no') AS 'London 1948',
    IF (MAX(`Berlin 1936`) > 0, 'yes', 'no') AS 'Berlin 1936',
    IF (MAX(`Los Angeles 1932`) > 0, 'yes', 'no') AS 'Los Angeles 1932',
    IF (MAX(`Amsterdam 1928`) > 0, 'yes', 'no') AS 'Amsterdam 1928',
    IF (MAX(`Paris 1924`) > 0, 'yes', 'no') AS 'Paris 1924',
    IF (MAX(`Antwerp 1920`) > 0, 'yes', 'no') AS 'Antwerp 1920',
    IF (MAX(`Stockholm 1912`) > 0, 'yes', 'no') AS 'Stockholm 1912',
    IF (MAX(`London 1908`) > 0, 'yes', 'no') AS 'London 1908',
    IF (MAX(`St Louis 1904`) > 0, 'yes', 'no') AS 'St Louis 1904',
    IF (MAX(`Paris 1900`) > 0, 'yes', 'no') AS 'Paris 1900',
    IF (MAX(`Athens 1896`) > 0, 'yes', 'no') AS 'Athens 1896'
FROM
    (
        SELECT
            Disciplina,
            Categoria,
            IF (Olimpiade = 'London 2012', 1, 0) AS 'London 2012',
            IF (Olimpiade = 'Beijing 2008', 1, 0) AS 'Beijing 2008',
            IF (Olimpiade = 'Athens 2004', 1, 0) AS 'Athens 2004',
            IF (Olimpiade = 'Sydney 2000', 1, 0) AS 'Sydney 2000',
            IF (Olimpiade = 'Atlanta 1996', 1, 0) AS 'Atlanta 1996',
            IF (Olimpiade = 'Barcelona 1992', 1, 0) AS 'Barcelona 1992',
            IF (Olimpiade = 'Seoul 1988', 1, 0) AS 'Seoul 1988',
            IF (Olimpiade = 'Los Angeles 1984', 1, 0) AS 'Los Angeles 1984',
            IF (Olimpiade = 'Moscow 1980', 1, 0) AS 'Moscow 1980',
            IF (Olimpiade = 'Montreal 1976', 1, 0) AS 'Montreal 1976',
            IF (Olimpiade = 'Munich 1972', 1, 0) AS 'Munich 1972',
            IF (Olimpiade = 'Mexico 1968', 1, 0) AS 'Mexico 1968',
            IF (Olimpiade = 'Tokyo 1964', 1, 0) AS 'Tokyo 1964',
            IF (Olimpiade = 'Rome 1960', 1, 0) AS 'Rome 1960',
            IF (Olimpiade = 'Melbourne / Stockholm 1956', 1, 0) AS 'Melbourne / Stockholm 1956',
            IF (Olimpiade = 'Helsinki 1952', 1, 0) AS 'Helsinki 1952',
            IF (Olimpiade = 'London 1948', 1, 0) AS 'London 1948',
            IF (Olimpiade = 'Berlin 1936', 1, 0) AS 'Berlin 1936',
            IF (Olimpiade = 'Los Angeles 1932', 1, 0) AS 'Los Angeles 1932',
            IF (Olimpiade = 'Amsterdam 1928', 1, 0) AS 'Amsterdam 1928',
            IF (Olimpiade = 'Paris 1924', 1, 0) AS 'Paris 1924',
            IF (Olimpiade = 'Antwerp 1920', 1, 0) AS 'Antwerp 1920',
            IF (Olimpiade = 'Stockholm 1912', 1, 0) AS 'Stockholm 1912',
            IF (Olimpiade = 'London 1908', 1, 0) AS 'London 1908',
            IF (Olimpiade = 'St Louis 1904', 1, 0) AS 'St Louis 1904',
            IF (Olimpiade = 'Paris 1900', 1, 0) AS 'Paris 1900',
            IF (Olimpiade = 'Athens 1896', 1, 0) AS 'Athens 1896'
        FROM SummerTotalMedals
        WHERE Sport='Athletics'
        AND Olimpiade = 'London 2012' AND Disciplina='yes'
    ) AS Games
GROUP BY Disciplina, Categoria
ORDER BY Disciplina ASC, Categoria ASC

The second, well you just need to change the Disciplina='no'.
Is this what you're expecting of didn't I understand the question?


text:
Q: Using a variable to indicate object type The use of instanceof or getClass() is largely considered code smell. Is using a variable to indicate the type of object you're using also considered code smell?
Suppose if I had an enum called WeaponType:
public enum WeaponType {
    ReloadableWeapon // -- imagine more weapon types
}

and Weapon class:
public abstract class Weapon
{
    private WeaponType wt;

    public Weapon(WeaponType wt)
    {
       this.wt = wt;
    }
}

public ReloadableWeapon extends Weapon{

     public ReloadableWeapon()
          super(WeaponType.ReloadableWeapon);
     {

     }
}

In this example, I'm using an enum to determine the type of weapon, essentially, I'm doing with the enum what I can do with instanceof or getClass().
I can check if the weapon is a certain type and proceed, for example, suppose in my game I allow the player to view their weapons based on type in a quick view while under attack.
I can collect all the weapons like so:
List<Weapon> reloadableWeapons = new ArrayList<Weapon>();

for (Weapon weapon : inventory){
     if weapon.istypeof(WeaponType.ReloadableWeapon){
          reloadableWeapons.add(weapon);
     }
}

// code to render reloadableWeapons to UI

Of course this doesn't have to be an enum, it could be any variable, String or int but it's purpose is to indicate what type of object you have.
Notice, I'm not using the enum to check the Weapon and downcast, or controlling behavior. I simply want to single out weapons of a specific type and perform an action, in this case, display in a UI.

A: When your weapon types enum just mirrors the class hierarchy, then this is a blatant violation of the DRY principle - you encode the same information, the type of a weapon redundantly in two places - one place is the class name itself, one place the enum. That's definitely not just a code smell, that is bad code.
Introducing such a type just to avoid instanceof formally does not make your code better - quite the opposite, you just "reinvent" instanceof and call it istypeof, with all the same drawbacks of the former: whenever you add a new Weaponsubclass, you have to check all places in code with an istypeof statement, if the code is still correctly dealing with the new type. There is no difference in this as if you would use instanceof for it, just an additional disadavantage: whenever you add a new subclass, you will also have to make sure you don't forget to extend the enum.
The situation may be different when you use the enum differently, for example, for modeling types of weapons in a finer or coarser granularity than your class hierarchy (or if you do not use a class hierarchy at all, just a type field). But in general, I recommend trying to achieve orthogonality, your code stays more maintainable if enums do not have implicit, hidden dependencies to something like a class hierarchy, that will become error prone sooner or later.

A: Your example is different from using getClass, you have but one generic class and you enum is just a member that tells the type of weapon (not the type of class). If your weapon/game is simple enough (your weapon just strikes) this is a valid approach.
It gets different when you start adding weapon type specific behavior to your generic weapon and you get lots of if statements and switch statements, checking your enum to get to the desired behavior.

A: Like anything, it becomes a code smell when it starts to make the code harder to understand and maintain. It can be OK in small doses, or where there is some useful differentiating feature. For example, if some types of weapons can be composed of other types of weapons, but some can't, then it might make sense to have an enum, string, or method that says, "contains sub weapons" or something like that. In most cases anything you can do to a weapon, you can also do to a weapon composed of other weapons. But there are things you can't do with a non-composed weapon (such as break it down into its components) that you can do with a composed weapon.
It might be better to use polymorphism for this case. You could have a base class that does something like this, for example:
public abstract class Weapon
{
    public reloadWeapon()
    {
        /* Do nothing in the base class */
    }
};

public class ReloadableWeapon extends Weapon
{
    public reloadWeapon()
    {
        /* Do whatever is necessary here */
    }
};

For non-reloadable weapons, the base class simply returns. For reloadable weapons, it reloads them as necessary.

A: The "right" way to do it in OOP world is the Visitor pattern.
Otherwise I agree with Doc Brown's answer that introducing explicit variable adds other points of failure, but does not give any benefit. Particularly, it does not remove the code smell which is explicit request for the object type. So I think you should not do it. An important exception would be the case when you have to interoperate with another language, reflecting the hierarchy, in which case you may have to introduce the enum anyway.

A: This is pretty much the same as checking the class, and has the same problems.
What will you do when you add more classes of weapons? Say you have Weapon, ReloadableWeapon (guns), MeleeWeapon (swords), ConsumableWeapon (bombs) and PlaceableWeapon (laser turrets).
If you go with an enum-based or class-based approach to distinguishing them, you will find yourself adding endless combination classes, and then forgetting to check them. You may wish to add cattle prods as a new class ReloadableMeleeWeapon, but then forget to check for ReloadableMeleeWeapon in the reloading code. Or you add it to the reloading code, but then forget to update the code that spawns weapons so that they start full of ammo, so that reloadable weapons start full of ammo, but reloadable melee weapons don't.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The Seven Dwarves (of Snow White fame) The seven dwarves have seven beds in a dormitory room. One night, Sleepy is so tired that he falls asleep on the first bed that he sees. This has happened before, so the other dwarves follow a standard procedure as they enter the dormitory room later that night: if a dwarf can sleep in his own bed, he does so, but if not, he selects a random bed and uses that one. On the night in question, Grumpy is the fourth dwarf to enter the room to go to bed. What's the probability that he sleeps in his own bed?

A: Suppose that there are $n$ dwarfs, $D_1,\dots,D_n$, and they enter in reverse order (i.e., $D_n$ first and $D_1$ last). I claim that the probability that $D_k$ gets his own bed is $\frac{k}{k+1}$ for every $k<n$; in the present problem $k=4$, so the answer is $\frac45$.
When $D_k$ enters the room, there are $k$ beds still free. Since each dwarf except $D_n$ takes his own bed if it's available, the beds belonging to $D_{k+1},\dots,D_{n-1}$ must all be occupied, and the free beds must be $k$ of the $k+1$ beds belonging to $D_1,\dots,D_k$, and $D_n$. When a dwarf picks a bed at random, the beds are in effect indistinguishable, so each of the $k+1$ beds belonging to these $k+1$ dwarfs is equally likely to be the one that's already occupied. In particular, the probability that $D_k$'s bed is already occupied is $\frac1{k+1}$, so the probability that he gets his own bed is $\frac{k}{k+1}$.

A: At each point in time, consider $W =$ the number of beds that (a) belong to a still-awake dwarf, and (b) are already occupied. $W$ is always either $1$ or $0$, and once it reaches $W=0$ it never goes back to $W=1$. On ther other hand $W$ goes from $1$ to $0$ exactly when a dwarf finds his own bed taken and happens to choose the one rightfully belonging to the first dwarf.
When $W=1$, then because of symmetry the wrongly-occupied bed is uniformly distributed among those belonging to still-awake dwarfs. So if we can compute the probability of $W=1$ before the fourth dwarf enters, that probability multiplied by $\frac{1}{4}$ is the probablity the fourth dwarf will have to choose a different bed.
Let $P_n$ be the probablity that $W=1$ when there are still $n$ dwarfs awake.
We then have $P_6=\frac{6}{7}$ because the first dwarf chooses randomly.
Now $P_5 = P_6\times (1-\frac{1}{6^2})$, because $W$ only decreases if the next dwarf can't get his own bed (which happens with probability $\frac{1}{6}$) and he randomly chooses (for a second factor of $\frac{1}{6}$) the bed that could make $W$ decrease.
Similarly $P_4 = P_5 \times (1-\frac{1}{5^2})$.
At this time the fourth dwarf enters, and the probability that his bed is already taken is $ P_4 \times \frac{1}{4} $.
You do the arithmetic.


text:
Q: Upload documents from Amazon s3 to CloudSearch using AWS Java SDK How to upload document from Amazon S3 to Cloud Search using AWS Java SDK and make it indexable as well?

A: I does not found any direct way within the SDK to index document from S3 to Cloud Search. So i use like this.


text:
Q: Input type Radio checked not work if open in new window My planing is click on button in link.html page (exp: Check option 2 in radio.html),
it will go to radio.html page and checked the option 2 radio.
I can checked the radio by click on button in radio.html page.
But if click button on link.html, i can't checked the radio when open the radio.html page.
I get a idea is use windows.open to open the radio.html, then use window.onload & document.getElementById to checked the radio.
But failed. Is my idea wrong?
Please help, TQVM.

Here is the radio.html code:

<input type="radio" name="option"  id="opt1">
Option 1
<input type="radio" name="option"  id="opt2">
Option 2
<input type="radio" name="option"  id="opt3">
Option 3
<input type="radio" name="option"  id="opt4">
Option 4

<button onclick="check1()">Check Option 1</button>

<button onclick="check2()">Check Option 2</button>

<button onclick="check3()">Check Option 3</button>

<button onclick="check4()">Check Option 4</button>

Here is the link.html code:

<button onclick="opencheck2()">Check Option 2 in radio.html</button>

<button onclick="opencheck3()">Check Option 3 in radio.html</button>

A: The simplest way to do this seems to be to add an event listener to the window that you are opening so that when it loads then the code can be triggered. Here's an example that will open this current SO page and replace the content with the word test (you would have to run this from the console as code snippets seem unable to open new windows):
var mywindow = window.open(document.URL);
mywindow.addEventListener('load', function() {
  mywindow.document.getElementById('content').innerText = 'TEST';
});

Here's a modified version of your code that takes advantage of the same behaviour. I've also reduced it into one function where the buttons now pass a number representing the checkbox to be ticked rather than having multiple functions:

<button onclick="opencheck(2)">Check Option 2 in radio.html</button>

<button onclick="opencheck(3)">Check Option 3 in radio.html</button>


text:
Q: How to remove query string using mod_rewrite I'm trying to make the following redirection (301) using .htaccess (apache 2.2)
*/?q=/shop/ to *
The string is on the end.
My code on the sandbox is:

RewriteEngine    On
RewriteCond      %{QUERY_STRING}    ^q=/shop/$
RewriteRule      (.*)               $1?     [R=permanent]

And the result in the sandbox has /%3F?q=/shop/ on the end.
The htaccess on my website with apache 2.2 is not working too.
What is wrong?


text:
Q: Project architectures differences for Django + Vuejs (or other) integration I'm currently looking at project setups for a Django + Vuejs project (though I guess the question is likely just as valid for other frontends, react, svelte etc.).
It seems that there are mainly 2 approaches that come up often, resulting in the following project structure:
The frontend embedded within the Django project (perhaps as a git submodule):
root
├── djangoapp
├── djangoproject
├── manage.py
├── requirements.txt
├── static
├── venv
└── vueproject
    ├── node_modules
    ├── package.json
    ├── public
    └── src

Another approach is to have them at the same level from project root, as 2 seperate projects actually (or I guess both could be git submodules to a "wrapper" project), so essentially:
root
├── djangoproject
│   └── <django files & folders>
└── vueproject
    └── <vue files & folders>

With the 2nd approach, it seems you basically just see Django as an API. Stuff like collectstatic does not (?) come into play. In development, you need a server up to serve Django's api, and a dev server for the vue frontend.
With the 1st approach (if I understand correctly), seems that you build the Vue static files, and then manage all of that with Django's collectstatic/static files management.
Seems the 2nd approach is a better decoupling of the 2 components. With the 1st, you need to configure vue (or vite) rather specifically and Django's static files as well. What we gain by doing this isn't obvious to me - the more I think about it, the more it seems clear that the 2nd approach is better.
What potential advantages would there be in the 1st approach? Dev conveniences I'm not seeing? Easier deployment? Or is it just a somewhat outdate approach that still lingers the web?


text:
Q: Trouble with understanding how TensorFlow receives and processes data I have recently begun studying Deep Learning and am confident of my understanding of both the theory and the in-depth practical implementations of RNNs and LSTMs. I have written a very simple RNN which learns to add together two binary numbers, using only numpy. I am now trying to become familiar with the TensorFlow API so that I no longer have to build my models from scratch.
Despite my confidence in my understanding of NNs and in my programming ability, I am becoming very frustrated as I keep hitting walls when it comes to understanding the high-level that TensorFlow abstracts the models, and how data to be used should be structured. An example of a wall I have hit is in the code below, where I am attempting to implement a simple RNN that takes in a list of lists/sequences of integers, and will then learn how to classify a single sequence as either increasing or decreasing. generate_data() outputs two lists:

*

*data is in the form on [[1, 2, 3], [9, 8, 7]] and is the input sequences.

*labels is a list of either 1s or 0s - a 1 meaning the corresponding sequence is increasing, and a 0 for decreasing.

x is the placeholder for the input sequences and y is the placeholder for the corresponding labels. My thought process is for each input sequence to be received by the RNN as x, a single column tensor with each row being a single integer of the sequence - a single time step in the unrolled RNN. The RNN will then output a single integr (0 or 1) after each full forward propogation of the RNN (after one entire x tensor has been processed.
I am getting an error that on the last line that inputs must be a sequence. I am failing to understand how this single column tensor is not considered a sequence, and how it needs to be shaped in order for it to be a sequence.
As a side note, the next biggest misunderstanding I have is that in all the theoretical explanations I have read of RNNs, there are 3 weighted matrices - one from input to hidden state, one from hidden state to output, and one between the hidden states of each time step. All coded examples I have seen using TensorFlow only seem to have a single weighted matrix. How is this so? How does TensorFlow use this single matrix as an abstraction of the 3 deep levels ones? And am I shaping this matrix correctly in the line W = tf.Variable(tf.random_normal([sequence_len, output_dim]))?
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
import random

sequence_len = 5        # Input Dimension
max_num = 1000          # Must be >= than (sequence_len - 1)
output_dim = 1
hidden_dim = 16
batch_size = 1000

def generate_data(sample_size, seq_len=sequence_len, max = max_num):
    data = []
    labels = []
    for _ in range(sample_size):
        type = (1 if random.random() < 0.5 else 0)
        temp = []
        if type == 1:
            labels.append(1)
            temp.append(random.randint(0, max_num - seq_len + 1))
            for i in range(1, seq_len):
                temp.append(random.randint(temp[i - 1] + 1, max_num - seq_len + i + 1))
            data.append(temp)
        if type == 0:
            labels.append(0)
            temp.append(random.randint(0 + seq_len - 1, max_num))
            for i in range(1, seq_len):
                temp.append(random.randint( 0 + seq_len - i - 1, temp[i - 1] - 1))
            data.append(temp)
    return data, labels

input_data, labels = generate_data(100000)

x = tf.placeholder(tf.int32, [None, sequence_len])
y = tf.placeholder(tf.int32, [None, output_dim])

W = tf.Variable(tf.random_normal([sequence_len, output_dim]))
b = tf.Variable(tf.random_normal([output_dim]))

cell = rnn.BasicRNNCell(hidden_dim)
outputs, states = tf.nn.static_rnn(cell, x, dtype=tf.int32)

A: tf.static_rnn expects a list of Tensors as per documentation so it can determines the length of your RNN (note that this must be determined before runtime and this is why you need to pass a python list of Tensors and not a Tensor):

inputs: A length T list of inputs, each a Tensor of shape [batch_size, input_size], or a nested tuple of such elements.

outputs, states = tf.nn.static_rnn(cell, [x], dtype=tf.int32) should work.
Regarding your side question, part of the answer can be found in the implementation of BasicRNNCell:
def call(self, inputs, state):
    """Most basic RNN: output = new_state = act(W * input + U * state + B)."""
    output = self._activation(_linear([inputs, state], self._num_units, True))
    return output, output

but it really depends on the RNNCell you choose to use. This is the part of your model which will implements the input to state, the state to state and the state to output logics.


text:
Q: System Boot Order not found I have installed Ubuntu 20.04 through a USB pen drive. I had Windows 7 prior to installation of Ubuntu 20.04. Ubuntu Installation did not complete successfully. Gave error while installing GRUB and installation failed. I tried by running Boot Repair Tool. It completed by showing Boot Repair completed successfully. Still I am getting the same error while booting that " System Boot Order not found". After sometime Ubuntu is loaded. But I am not able to access Windows 7. Mine is Legacy BIOS.
How to fix this error?

A:
from a terminal window in your ubuntu do "sudo update-grub".
It should be able to find your windows 7 installation.
After that  you should be able to see a grub menu on boot with both Ubuntu and Windows 7 options.


text:
Q: why vscode wants to run python scripts with gcc? i decided to learn C. I did set up vscode to start writing C programs. I installed Mingw and gcc.
when I went back to one of my older python projects vscode wants to run it with gcc and i tried closing-reopening it .
Can someone help me solve this problem? Also I'm not sure if this is the right place but I didn't find a better place in all sites in stack exchange.

A: Do you have this line in your launch.json file?
"preLaunchTask": "Task",

You need to annotate this line.


text:
Q: kaggle kernel can't install python package I'm a kaggle kernel beginner, and I want to use kaggle kernal's free GPU to learn tensorflow 2.0, but I can't install tensorflow 2.0 by !pip install tensorflow-gpu==2.0.0-alpha0.

A: The problem is I not enable the kaggle kernel internet.
so the detail solution is:
kernel settings > internet > on
and it works!


text:
Q: NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: [](0)) I am trying to create an application and this application gets information from the open-meteo API. I keep on encountering some errors that don't know how to fix. Would appreciate any help!!
title: Text(snapshot.data[i].longitude), //This is the line that is producing the error
import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
Future getUserData() async {

var response = await http.get(Uri.parse( 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m'));
var jsonData = jsonDecode(response.body);
List<User> users = [];

for (var u in (jsonData)) {
  User user = User(u['longitude'], u['latitude'], u['hourly'], u['time'],u['temperature']);
  users.add(user);
}

print(users.length);
return users;
}

@override

Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
   title: Text('Rangers Tool'),
),
 body: Container(
 child: Card(
   child: FutureBuilder(
 future: getUserData(),
 builder: (context, AsyncSnapshot snapshot) {
return ListView.builder(
              itemCount: snapshot.data?.length,
              itemBuilder: (context, i) {

 return ListTile(
  title: Text(snapshot.data[i].longitude),
  subtitle: Text(snapshot.data[i].latitude),
);
});
}

},

))), ); } }

class User {

final String longitude, latitude, hourly, time, temperature;

User(this.longitude, this.latitude, this.hourly, this.time, this.temperature); }

}

A: You need to add a condition to make sure that data is there by checking the status of the snapshot before using it to build your list.  Similar to this:
FutureBuilder(
    future: _fetchListItems(),
    builder:(context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
         } else if (snapshot.hasError) {
              SnapshotError(snapshot.error),
         } else {
            return ListView.builder(
              itemCount: snapshot.data?.length,
              itemBuilder: (context, i) {

           return ListTile(
           title: Text(snapshot.data[i].longitude),
           subtitle: Text(snapshot.data[i].latitude),
           );
         }
     }
)


text:
Q: Swift index out of range when refreshing so ive been tring to solve this on my own for a few hours now. When ever i pull to refresh its crashes saying index out of range. Some people say its because of removing the arrays data before getting it and all that but only confused me further
here is my code
    @objc fileprivate func fetchPostsWithUser() {

    houses.removeAll()
    myJobs.removeAll()

    let ref = Database.database().reference().child("posts")
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let dictionaries = snapshot.value as? [String: Any] else { return }
        dictionaries.forEach({ (key, value) in
            guard let dictionary = value as? [String: Any] else { return }

            var post = Post(dictonary: dictionary)
            post.id = key

            Database.database().reference().child(key).observeSingleEvent(of: .value, with: { (snapshot) in
                if post.pickedUserId == Auth.auth().currentUser?.uid {
                    self.myJobs.append(post)
                } else if post.hasPicked == true && post.pickedUserId != Auth.auth().currentUser?.uid  {
                    print("taken out")
                } else {
                    self.houses.append(post)
                }
                self.houses.sort(by: { (p1, p2) -> Bool in
                    return p1.creationDate.compare(p2.creationDate) == .orderedDescending
                })
                self.tableView.reloadData()
            }, withCancel: { (err) in
                print("Failed to fetch like info for post:", err)
            })
        })

    }) { (err) in
        print("Failed to fetch posts:", err)
    }
}

A solution to this error will be greatly appreciated, thank you.


text:
Q: Is there a way to fire JQuery .when on the moment that one of a list of deferred functions finishes? I want to build a pseudo queue using ajax.
And then I want to fire five calls at a time.
The pseudo code would look something like:
For each item in list as ajaxN{
FuncToRun.push(ajaxN);
If(count(FuncToRun)==5){
    .when (FuncToRun).onefinishes{
        FuncToRun.pop(success Func)
    }
}
}

Is this possible?

A: It sounds rather like you want jQuery.Callbacks.
However, a Callbacks object doesn't offer a length property so you need to contrive some mechanism for monitoring the number of functions in the queue and for firing it when your threshold (5) is reached.
For example, you could wrap a Callbacks object in a little namespace with a handful of custom methods and properties.
var FunctionList = (function() {
    var list = $.Callbacks(),
        length = 0,
        threshold = 5;
    function add(fn) {
        if(fn  && $.isFunction(fn)) {
            list.add(fn);
            if(++length >= threshold) {
                list.fire().empty();
                length = 0;
            }
        }
        else {
            throw new TypeError("FunctionList.add() must be passed a function");
        }
    }
    function getLength(x) { return length; }
    function setThreshold(x) { threshold = x; }
    function getThreshold() { return threshold; }
    return {
        add: add,
        getLength: getLength,
        setThreshold: setThreshold,
        getThreshold: getThreshold
    };
})();

As written, FunctionList is very basic and meets the minimum requirements of the question. It could be taken much further to expose more of the Callbacks API (eg. flags, .disable(), .fireWith(), .has(), .lock(), .remove()).  You could also refactor the namespace as a constructor, allowing more than one FunctionList to be used simultaneously.
How you populate FunctionList is up to you. FunctionList.add(...) could certainly be called in response to AJAX success, which is what you appear to want.


text:
Q: Spring MVC - Ehcache best practices I have a question about best pratices using spring and ehCache.
For example if I have two methods annotated with @Cacheable that are using the same parameter value, ehcache will  return the latest cache value.
@Cacheable(value="imagesCache",key="#id_image")
public Image getUserImage(id_image){ //stuff }

//and

@Cacheable(value="imagesCache",key="#id_image")
public Image getProductImage(id_image){ //stuff }

If I first call getUserImage(10) and then getProductImage(10), ehcache will return same value for both methods because they have the same key.
I tought that ehcache, indexes the cache value using key and method name, so that if two methods have the same #key(10 in my example) it will look at the method name.
I know that the easiest solution is to create two caches ("userImagesCache" and "productImagesCache") but in this context I want to avoid this.
How to solve this?
Thank you.

A: According to @Cacheable javadoc key is a SpEL expression, so you might to make smth like that:
@Cacheable(value="imagesCache",key="'user' + #id_image")
public Image getUserImage(id_image){ //stuff }

//and

@Cacheable(value="imagesCache",key="'product' + #id_image")
public Image getProductImage(id_image){ //stuff }


text:
Q: AC bias circuit for a tape recorder I was wondering if I can "upgrade" a DC biased tape recorder to AC bias with a simple circuit.
I found some schematics for AC bias circuits, but they were all very different, and I'm not sure which one is suitable for tape recorders. I was thinking maybe there's an IC for that available, but again, I'm not sure on that one.
I'd like the most simple solution, which could be easily put on a daughter board and hidden in the tape recorder. I was thinking using a 70kHz oscillator, and adding it to the signal somehow (before the DC bias, as in, removing the DC bias parts).
This is just a little project to play around, nothing serious. I'm not planning to make "professional" recordings on the tape recorder that will emerge at the end of the project. I just want a proof of concept type of thing.
OK, this is how far I've got:
Consider this circuit of the LA4160:

This is a screenshot of the datasheet, page 4.
Now as you can see in the lower left corner, there is a device "Bias OSC". Given the rest of the Datasheet, I might be able to locate the point where this oscillator has to go.
But how exactly do I build this thing? Or is it an IC that eludes me?
Would be nice if someone could take a look at the datasheet I've linked, and maybe point out a thing or two, if I missed something.
Now, the oscillator needs to be a sine wave, but that's pretty much all I know. I don't know which peak-to-peak level, and I'm not entirely sure what frequency. I think somewhere around 100kHz makes the most sense.

A: *

*Check the type of your recorder erasing head. It's likely just a permanent magnet that saturates the magnetic tape in one direction. It's OK to record to such tape with DC bias, but I don't know how it is suitable for AC-bias recording. Anyway, it's better to replace it with a ferrite erasing head because it demagnetizes the tape and prevents it from producing low-frequency saturation noise.

*The bias current is several times higher than the recording current and also its frequency is higher. The head's resistance is primarily inductive at such frequencies, so it makes the AC bias voltage many times higher than the recording voltage or even the amplifier's supply voltage. It means you need a separate bias generator anyway.

*The simpliest bias generator circuits contain one transistor, a transformer, and several capacitors and resistors. An erasing head is commonly attached to the generator directly, and a secondary winding of the transformer is capacitively coupled to the recording amplifier output.

*You need to know your recording head's inductance, maximum recording current and maximum bias current to design the bias generator.

A: It might be no more difficult than making a 70kHz signal and adding it to your "normal" record signal that feeds the tape head. It might be as simple as mixing those two signals using resistors.
On the other hand, it may not work because the "simple" resistor circuit above may cause the amplifier producing the regular record signal (the audio) to clip and distort. You may have to use a transformer to couple the two signals together and this still may cause the regular amplifier some issues.
It's a bit like when someone asks if you can fix their TV - I always reply "get me the circuit diagrams and I'll have a look (sometime)".
The bottom line is try it and see and if it doesn't work then no harm done.


text:
Q: What different between Master node gateway and other node gateway in elasticsearch? Both of them store meta data, isn't it? What different between Master node gateway and other node gateway in elasticsearch?  Both of them store meta data, isn't it?
Meta data, elasticsearch called, what information we can get from it?

A: The master node is the same as any other node in the cluster, except that it has been elected to be the master.
It is responsible for coordinating any cluster-wide changes, such as the addition or removal of a node, creation, deletion or change of state (i.e. open/close) of an index, and the allocation of shards to nodes. When any of these changes occur, the "cluster state" is updated by the master and published to all other nodes in the cluster. It is the only node that may publish a new cluster state.
The tasks that a master performs are lightweight. Any tasks that deal with data (eg indexing, searching etc) do not need to involve the master. If you choose to run the master as a non-data node (ie a node that acts as master and as a router, but doesn't contain any data) then the master can run happily on a smallish box.
A node is allowed to become a master if it is marked as "master eligible" (which all nodes are by default).  If the current master goes down, a new master will be elected by the cluster.
An important configuration option in your cluster is minimum_master_nodes. This specifies the number of "master eligible" nodes that a node must be able to see in order to be part of a cluster.  Its purpose is to avoid "split brain" ie having the cluster separate into two clusters, both of which think that they are functioning correctly.
For instance, if you have 3 nodes, all of which are master eligible, and set minimum_master_nodes to 1, then if the third node is separated from the other two it, it still sees one master-eligible node (itself) and thinks that it can form a cluster by itself.
Instead, set minimum_master_nodes to 2 in this case (number of nodes / 2 + 1), then if the third node separates, it won't see enough master nodes, and thus won't form a cluster by itself. It will keep trying to join the original cluster.
While Elasticsearch tries very hard to choose the correct defaults, minimum_master_nodes is impossible to guess, as it has no way of knowing how many nodes you intend to run.  This is something you must configure yourself.


text:
Q: Spline Spawn in Unreal I'm starting with Unreal Engine and I would like to know if there is a way to instantiate a spline from point A (Caster) to B (receiver) and how to do it?

A: You should be able to do it by adding a spline component and then set up 2 points on the desired locations like this:

As you can see, there's a way to instantiate it and the only way I can imagine can work is to add 2 points and set up the position as you want.


text:
Q: Would old version of mysql(5.1) caused performance issue in Django(1.11) I'm rewritting a web application using Django 1.11. When i hooked up to my test mysql database (version 5.7), the performance is amazing. The page renders within 1 second. However, when I connect to the existing production mysql (version 5.1), the page takes more than 10 seconds.
I installed the debug toolbar, and I found out the the query time is actually not the issue. Most of the time are in the CPU.
I've eliminated the possibility of mysql performance issue by directly running the query on the database. It's not network issue either since my ping is just fine.
I am wondering whether the Django is having issues with older mysql version when Django receives the data and try to map it to objects via ORM.


text:
Q: ngx-disqus module in ionic v3 only displays one thread I want to use this npm-module in my Ionic 3 Progressive Web App: https://www.npmjs.com/package/ngx-disqus
I have imported it to the page.module.ts like this:

import { DisqusModule } from 'ngx-disqus';

@NgModule({
  declarations: [
    SzenarioerstellungPage,
  ],
  imports: [
    IonicPageModule.forChild(SzenarioerstellungPage),
    DisqusModule.forRoot('my_shortname'),
  ],
  exports: [
    SzenarioerstellungPage
  ]
})
export class SzenarioerstellungPageModule {}

This is how I use it in mypage.html file:

<disqus  [identifier] = "pageId" ></disqus>

And this is how I set the pageId:

ionViewDidLoad() {
    this.szenarioProvider.getUserID().then( UID => {
      this.pageId = UID;
    });

  }

As you can see, I want to use the unique ID of the user (which he got from firebase authentification) to display a unique discus-thread on his page.
The problem is now that no matter what user gets to this page, discus only shows one and the same thread, instead of individual threads for each user.
Note: no matter what user enters the mentioned page, it always has the same URL (ionic does it like this.): http://localhost:8100/#/szenarioerstellung
But I thought, that the unique [indentifier] would solve this problem.
Do you know, what I did wrong or what I need to add/ have in mind?

A: DISQUS does NOT work when the # is used in the router.
for example the URL http://localhost:8100/#/szenarioerstellung is read as http://localhost:8100/, so no matter how the URL changes, it will still look the same on DISQUS side.
There are 2 solutions:
1 - Find a way to configure your router to use the hashbang #! instead of #
2 - Disable the HashLocationStrategy from the Router so it becomes like the standard URL http://localhost:8100/szenarioerstellung.
Read the requirement section in Using Disqus on AJAX sites


text:
Q: Best java twitter library? The twitter API site lists 4 java twitter libraries.

*

*Twitter4j

*java-twitter

*jtwitter

*twittered
Do you know others? What are your experiences in support, ease of use, stability, community, etc.

A: I use Twitter4J and have yet to have a problem with it. I actually like it a lot.
The OAuth example they give on their website is the biggest nuisance -- it's not helpful. Here's my OAuthServlet code if you're interested (or anyone else). I know this question is rather old, so I'm putting it in here more for search results.
package com.example.oauth;

import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import twitter4j.*;
import twitter4j.http.*;

@SuppressWarnings("serial")
public class OAuthServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        HttpSession sess = req.getSession(true);
        RequestToken requestToken = (RequestToken) sess.getAttribute("requestToken");

        if (sess.getAttribute("twitter_user_id") != null) {
            resp.setContentType("text/plain");
            PrintWriter out = resp.getWriter();
            if (req.getRequestURI().indexOf("logout") > 3) {
                sess.removeAttribute("twitter_user_id");
                out.println("You're now logged out.");
            } else {
                out.println("You're already logged in!");
            }
        } else if (req.getRequestURI().indexOf("callback") > 3 && req.getParameter("oauth_token").length() > 0 && requestToken != null) {

            handleCallback(req, resp, sess);
            if (sess.getAttribute("oauth_previous") != null) {
                resp.sendRedirect((String) sess.getAttribute("oauth_previous"));
                sess.removeAttribute("oauth_previous");
            }

        } else {

            sendToTwitter(resp, sess);
            sess.setAttribute("oauth_previous", req.getHeader("Referer"));
        }

    }

    private void sendToTwitter(HttpServletResponse resp, HttpSession sess) throws IOException {

        RequestToken requestToken = (RequestToken) sess.getAttribute("requestToken");

        try {
            Twitter twitter = new TwitterCnx().registerOAuth().get();

            requestToken = twitter.getOAuthRequestToken();
            sess.setAttribute("requestToken", requestToken);

            resp.sendRedirect(requestToken.getAuthorizationURL());

        } catch (TwitterException e) {
            PrintWriter out = resp.getWriter();
            out.println(e.getStackTrace());
        }
    }

    private void handleCallback(HttpServletRequest req, HttpServletResponse resp, HttpSession sess) throws IOException {

        RequestToken requestToken = (RequestToken) sess.getAttribute("requestToken");
        sess.removeAttribute("requestToken");
        String secret = req.getParameter("oauth_token");

        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();

        try {
            Twitter t = new TwitterCnx().registerOAuth().get();

            AccessToken accessToken = t.getOAuthAccessToken(requestToken.getToken(), secret);
            long id = (long) t.verifyCredentials().getId();

            storeAccessToken(id, accessToken,sess);
            sess.setAttribute("twitter_user_id", id);

            out.println("You're now logged in!");

        } catch (TwitterException e) {
            out.println("Something went wrong. Sorry about that. Please try again.");
        }

    }

    private void storeAccessToken(Long id, AccessToken at, HttpSession sess) {
        //you probably want to persist this somewhere other than in sessions.
        sess.setAttribute("secret", at.getTokenSecret() );
        sess.setAttribute("token", at.getToken());
        //also, don't forget to persist the user id alongside the token.
    }
}

I use the class TwitterCnx as a wrapper for twitter4j.Twitter. TwitterCnx defines my OAuth consumer stuff and returns a Twitter object. It's a final class with static methods so I don't produce more than one Twitter object per app instance.

A: I just took a look at them.
JTwitter definitely looks like the weakest of the three. It doesn't appear to have been updated lately, doesn't cover much of the Twitter API, and doesn't appear to have any releases besides the initial one. On the upside, it's LPGL licensed, comes packaged with what little extra code it needs, and looks small and simple to understand.
The other two, java-twitter and Twtter4J look much closer in quality. Both cover the core API, and both have all the accouterments of normal open-source projects: publicly available source code repository, on-line docs, active mailing lists, and recent development activity.
However, Twitter4J looks to be the leader. From the docs, its API coverage appears to be more complete. The mailing list is definitely more active. The docs are much better. And most importantly to me, the releases have been more frequent. java-twitter has one release up, the "0.9-SNAPSHOT" release about 4 months ago. Twitter4J has had several releases in that time period, including 2.0.0 and incremental releases up through 2.0.8, fixing issues and adding support for new Twitter APIs.
I'm going to start with Twitter4J; if you don't hear back, assume it was just great for me.

A: I think Twitter4j is good one it is most upto date API

A: For anyone still looking at this question, it's worth mentioning that the only API that Twitter currently lists on its website for Java is Twitter4J. So, if you needed any more convincing that this was the one to use, well, here you go!

A: Ahem; JTwitter is actively maintained, regularly updated (version 1.6.2 released today), and covers most of the Twitter API.
It's missing only a method for setting your profile image and a few other profile settings. Other than that, it's pretty complete. Status updates, timelines, friendships, lists, searches, streaming, etc.
It's also fast and robust. Twitter can be flaky in places and JTwitter has work-arounds and informative exceptions to make your life easier.
As the main JTwitter developer, I am rather biased! But the feedback from developers using JTwitter is also very positive.

A: I have selected Twitter4j because a lot of people are working on it. And its easy to find out some contents on Internet about it.

A: There's also TweetStream4J which is a Java binding for the Twitter Streaming API. It's pretty simple, and unlike the last time I used it, the author has updated it to include a pom.xml file so you can build it. It's pretty simple and quick when I last used it (from Scala).


text:
Q: How do I initialize the size of a Hash in Ruby? I would like to specify an initial size for my Hash in Ruby.  I know I am going to be adding tens of millions of entries in the hash and a lot of time is wasting rehashing the data every time Ruby decides it needs a larger hash.
Other languages support something like a "reserve" call to pre-size the hash.  Can this be done in Ruby?

A: Ruby's Hash doesn't have any way to do that.  It should still be relatively performant either way, but you might want to consider other data storage methods, such as a database or key/value store like Memcached or Redis, for data sets of that magnitude.


text:
Q: Subtract two strings in python I should calculate the difference between elements two different list. This is my code :
import operator
a   = ['5', '35.1', 'FFD']
b    = ['8.5', '11.3', 'AMM']
difference = [each[0] - each[1] for each in zip(b, a)]
print difference

I need this output:

b-a = ['3.5','-23.8','AMM-FFD']

I receive the following error:

unsupported operand type(s) for -: 'str' and 'str'

I don't want to use any class like numpy or pandas

A: You need to convert numbers to floats, and if the elements cannot be converted to numbers, insert a '-' between them.
diffs = []
for i, j in zip(a, b):
    try:
        diffs.append(str(float(j) - float(i)))
    except ValueError:
        diffs.append('-'.join([j, i]))

>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']

Since python is strongly typed (not to be confused with static vs. dynamic) it does not implicitly perform arithmetic on the numeric interpretation of strings if it encounters an arithmetic operator between strings. There is no obvious behavior of the minus operator with regard to strings the way there is an obvious behavior of plus (i.e., concatenate).  Would you expect it to remove instances of the second string from the first string?  If so, there's already a more explicit str.replace method you can use.  Or would you expect it to remove the second string from the first only if the first string ends with the second string?  The expected behavior isn't 100% obvious, so the python authors did not include __sub__ method support for strings.
Also, the operator module isn't used in your code, so no need to import it.


text:
Q: C++ Efficiency of Classes vs Structs In C++, I'm trying to decide whether or not to use a struct or class. So far I understand that both are more or less identical, but a class is used more often when private variables are needed or to group the concept of an object that performs actions.
But what I'm wondering is: Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
Here is an example
class Vector2D {
    public:
        int x;
        int y;
        Vector2D();
        getMagnitude();
        Normalize();
}

vs.
struct Vector2D {
    int x;
    int y;
}

// Some functions defined separately
getMagnitude(Vector2D v);
Normalize(Vector2D v);

And if I have a bunch of other vector functions, say, adding two of them together and I have a vector class, is it better if those are included in the class, so you have a function like addToVector(Vector2D v2) or to keep these multi vector functions outside of the class so that you'd have an addToVector(Vector2D v, Vector2D v2)?
I understand the second question might lean towards opinion, but if there is a "best practice" defined way, I'd like to know.
Thank you

A:
C++ Efficiency of Classes vs Structs

Structs are classes. There is zero efficiency between one and the other.

Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?

No. There is no practical difference between "memory requirements" of member functions and non-member functions.
Also, structs can have member functions. All classes can have member functions, and structs are classes.


text:
Q: Add saved searches The ability to save custom searches and load them at will in the mobile app would be really nice. I frequently search for specific tags when I log on to answer new questions (e.g. [java] -[android] on StackOverflow).
Maybe add a "default search" setting as well; I usually use the same search filters every time I go to answer questions on SO, as I am not yet extensively proficient in multiple languages.


text:
Q: Why do I need a scope.$apply when compiling a directive from another? Why do I need a scope.$apply for the scope on the compiled directive to be bound to its template?
Relevant plunker is here:
http://plnkr.co/edit/t3zF1A0BviItmbx9J7ii?p=preview

A: It's not that you need a scope.$apply on the myDirective, it's that you're using a jQuery / jqLite function (append) to add a new directive and Angular has no idea it needs to fire off another digest cycle.
See my change here where I moved the scope.$apply to cover the append method in your first directive and the result is the same:
http://plnkr.co/edit/fAAHOj?p=preview

A: there are two things:

*

*Events occured inside the angular environment, you do not need to apply these changes as Angular will itself fire a digest cycle and then apply the changes.

*When you do some changes from outside the environment of Angularjs, then in this case angular will be required to be explicitly told that a change has occured. Hence we write, $scope.$apply();
Even in directive, if it is a change using angular functions there is no need of apply. But in case you used some other library to cause the events, then you need to apply the changes.


text:
Q: Modular properties of weight $\frac{3}{2}$ theta functions Define the theta-functions $g(z) = - \sum_{n \in \mathbf{Z}} \left(n + \frac{1}{6} \right) e^{3 \pi i \left( n + \frac{1}{6} \right)^2 z}$. How can I show that $$g(z + 1) = e^{\frac{1}{24}2 \pi i} g(z)$$ and $$g\left(-\frac{1}{z} \right) = - (-i z)^{\frac{3}{2}} \sum_{n \in \mathbf{Z}} (-1)^n \left(n + \frac{1}{3} \right) e^{3 \pi i \left( n + \frac{1}{3} \right)^2 z}$$
This example is from S. Zweger's paper "Mock Theta Functions and Real Analytic Modular Forms", where he states that this can be shown "using standard-methods". I don't know those standard-methods, so I'd appreciate some help.
Thanks!

A: This is very late, but I stumbled across this while looking for something else.
Let $a(n) := -(n+1/6)$ for ease of notation.
For the first identity, we have
\begin{align*}
g(z+1) &= \sum_{n \in \mathbb{Z}} a(n)e^{3\pi i( n + 1/6)^{2}z}e^{3\pi i(n + 1/6)^{2}} \\
&= \sum_{n\in \mathbb{Z}}a(n)e^{3\pi i(n + 1/6)^{2}z}e^{3\pi i\left( \frac{6n+1}{6} \right)^{2}}\\
&= \sum_{n \in \mathbb{Z}} a(n)e^{3\pi i(n + 1/6)^{2}z}e^{2\pi i(6n+1)^{2}/24}\\
&= \sum_{n \in \mathbb{Z}} a(n)e^{3\pi i(n + 1/6)^{2}z}e^{3\pi in^{2}}e^{\pi i}e^{2\pi i/24}\\
&= e^{2\pi i/24}g(z).
\end{align*}
For the second part, use Poisson summation.


text:
Q: Edit static tableView cell sections I have a static tableView with some custom cells. What I wan't to do is change the section titles programmatically. As far as I know, because the cells are static, I can't use methods like cellForRowAtIndexPath and so on, so my question is, is it possibly to change them like.
self.tableView.section1.text = @"title1"; // something like this?

I've tried to create an IBOutlet of the section but I get the following error:
Unknown type name 'UITableViewSection': did you mean 'UITableViewStyle?'

What I can do is edit the content of the cells, but not the header.
Thanks!

A: Use viewForHeaderInSection method.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

        UILabel *label1 = [[UILabel alloc] init];
        label1.frame = CGRectMake(0, 0, 190, 20);
        label1.textColor = [UIColor blackColor];
        // label1.font = [UIFont fontWithName:@"Helvetica Bold" size:16];
        [label1 setFont:[UIFont fontWithName:@"Arial-BoldMT" size:14]];
        label1.textAlignment = UITextAlignmentCenter;

        label1.text =[NSString stringWithFormat:@"Title %d",section];
// If your title are inside an Array then Use Below Code

       label1.text =[titleArray objectAtindex:section];

        label1.textColor = [UIColor whiteColor];
        label1.backgroundColor = [UIColor clearColor];

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [view addSubview:label1];

    view.backgroundColor = [UIColor orangeColor];
         return view;

    }

if You want to use titleForHeaderInSection then use below code.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

return [NSString stringWithFormat:@"Title %d",section];
// If your title are inside an Array then Use Below Code

       return [titleArray objectAtindex:section];
}

A: You can use the UITableViewDelegate Protocol method tableview:titleForHeaderInSection:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    NSString *sectionTitle = @"";

    switch (section) {

        case 0: sectionTitle = @"Section 1"; break;
        case 1: sectionTitle = @"Section 2"; break;
        case 2: sectionTitle = @"Section 3"; break;

        default:
            break;
    }

    return sectionTitle;
}

Make sure you declare your <UITableViewDelegate> in your .h file:
@interface SettingsViewController : UITableViewController <UITableViewDelegate> {

}

A: If you need to change the headers when the view is displayed 'live' you can do so like this:
int sectionNumber = 0;
[self.tableView headerViewForSection:sectionNumber].textLabel.text = @"Foo Bar";

But doing so doesn't seem to change the size of the label frame.  I just made mine larger in advance.  More details here.


text:
Q: How to generate alert or js function after generic handler I have written a function which basically takes some input as text and set of files. And using Generic handler i save the files and text all works fine. The issue is after the process i want to some some alert or success message how can i achieve that?
JS:
 var appID = $("#hidden_applicationID").val();
        var messageText = escape($("#screeningFeedback").val());

        var files = $("#fileScreening").get(0).files;
        var fileData = new FormData();

        for (var i = 0; i < files.length; i++) {
            fileData.append("fileInput", files[i]);
        }

        fileData.append("uniqueapplicationID", appID);
        fileData.append("messageText", messageText);

         $.ajax({
            url: "ScreeningUpload.ashx",
            data: fileData, type: "POST",
            processData: false,
            contentType: false,
            cache: false,
            dataType: "json",
             success: function (mydata) {
                 alert("hello");
                //$("#screeningFeedback").val();
                //showtoaster("Thank you for your submission!");

            }

        });

C#
 public void ProcessRequest(HttpContext context)
{ // DOING SOMETHING

    context.Response.Clear();
    context.Response.Write("<script type='text/javascript'>alert('Hello, world');</script>");

 }

How can i achieve the above tried many things but no luck.
Thank you

A: If you are sending JavaScrip as response from backend then add that response in DOM. Browser will execute it.
$.ajax({
        url: "ScreeningUpload.ashx",
        data: fileData, type: "POST",
        processData: false,
        contentType: false,
        cache: false,
        dataType: "json",
        success: function (mydata) {

             $(document.body).append(mydata);
        },
        error: function(jqXHR, textStatus, errorThrown){
           alert("Status:"+textStatus+"\nError:"+errorThrown);
        }
    });


text:
Q: Update query not working in mysql workbench I have a MySql query, which is given below:
UPDATE signup SET lastname='Lastname', password='123'
WHERE firstname='Firstname';

I am using MySql Workbench to execute the query.
But it's not updating the row and shows this error:

You are using safe update mode and you tried to update a table without
  a WHERE that uses a KEY column To disable safe mode, toggle the option
  in Preferences -> SQL Editor and reconnect.

A: In mysql workbench the safe mode is enabled by default, so if your WHERE clause doesn't have a key it will prevent running the query. Try disabling that using these steps -
Edit > Preferences > Sql Editor > uncheck the "Safe Updates"
Note - try reconnecting the server (Query > Reconnect to Server) and than run your query again.

A: MySQL helps you particularly avoid updating/deleting multiple rows in one shot. To achieve that, it doesn't allow you to run UPDATE queries without passing the ID parameter. This is called as the SAFE UPDATES mode.
As said by @ManojSalvi, you can set it permanently from the settings.
In case you want to temporarily disable the SAFE UPDATE mode, you can try the following:-
SET SQL_SAFE_UPDATES = 0;
UPDATE signup SET lastname='Lastname', password='123'
WHERE firstname='Firstname';
SET SQL_SAFE_UPDATES = 1;

A: [edit]
@ManojSalvi got it, workbench related
MySQL error code: 1175 during UPDATE in MySQL Workbench

Work fine for me...
SQL Fiddle
MySQL 5.6 Schema Setup:
CREATE TABLE t
    (`firstname` varchar(6), `lastname` varchar(14), `password` varchar(3))
;

INSERT INTO t
    (`firstname`, `lastname`, `password`)
VALUES
    ('Pramod', 'Alfred', '***'),
    ('test', 'hello h.', '***')
;
UPDATE t SET lastname='Alfred Schmidt', password='123' WHERE firstname='Pramod';

Query 1:
select * from t

Results:
| firstname |       lastname | password |
|-----------|----------------|----------|
|    Pramod | Alfred Schmidt |      123 |
|      test |       hello h. |      *** |

A: "Safe mode" is on by default in MySQL workbench. You can change it go to mysqlworkbench at the top left –> preferences–> sql editor –> uncheck the safe mode and then try reconnecting. Or you can just type
SET SQL_SAFE_UPDATES = 0;
This will do the same.

A: I don't think it has anything to to with the SAFE UPDATES since you have clearly stated WHERE you wanted to make changes.
I had the same issue, but I tried wrapping the column's name in backticks ` and it worked. You can find backticks to the left of number 1 on the keyboard.
One other thing you can try is to SELECT the table and double click on the item you want to UPDATE then apply the changes at the bottom right of the window.


text:
Q: How to count word occurrences without being constrained to only exact matches I have a file which has content like below.
Someone says; Hello; Someone responded Hello back
Someone again said; Hello; No response
Someone again said; Hello waiting for response

I have a python script which counts number of times a particular word occurred in a file. Following is the script.
#!/usr/bin/env python

filename = "/path/to/file.txt"

number_of_words = 0
search_string = "Hello"

with open(filename, 'r') as file:
    for line in file:
        words = line.split()
        for i in words:
            if (i == search_string):
                number_of_words += 1

print("Number of words in " + filename + " is: " + str(number_of_words))

I am expecting the output to be 4 since Hello occurs 4 times. But I get the output as 2? Following is the output of the script
Number of words in /path/to/file.txt is: 2

I kind of understand that Hello; is not considered as Hello because of the word not being exactly the one searched for.
Question:
Is there a way I can make my script pick Hello even if it was followed by a comma or semi-colon or a dot? Some simple technique which doesn't require to look for substrings again within the found word.

A: Regex would be a better tool for this, since you want to ignore punctuation. It could be done with clever filtering and .count() methods, but this is more straightforward:
import re
...
search_string = "Hello"
with open(filename, 'r') as file:
    filetext = file.read()
occurrences = len(re.findall(search_string, filetext))

print("Number of words in " + filename + " is: " + str(occurrences))

If you want case-insensitivity, you could change search_string accordingly:
search_string = r"[Hh]ello"

Or if you want explicitly the word Hello but not aHello or Hellon, you could match the \b character beforehand and afterwards (see the documentation for more fun tricks):
search_string = r"\bHello\b"

A: You can use regex and Counter from collections module:
txt = '''Someone says; Hello; Someone responded Hello back
Someone again said; Hello; No response
Someone again said; Hello waiting for response'''

import re
from collections import Counter
from pprint import pprint

c = Counter()
re.sub(r'\b\w+\b', lambda r: c.update((r.group(0), )), txt)
pprint(c)

Prints:
Counter({'Someone': 4,
         'Hello': 4,
         'again': 2,
         'said': 2,
         'response': 2,
         'says': 1,
         'responded': 1,
         'back': 1,
         'No': 1,
         'waiting': 1,
         'for': 1})

A: You can use regular expressions to find the answer.
import re
filename = "/path/to/file.txt"

number_of_words = 0
search_string = "Hello"

with open(filename, 'r') as file:
    for line in file:
        words = line.split()
        for i in words:
            b = re.search(r'\bHello;?\b', i)
            if b:
                number_of_words += 1

print("Number of words in " + filename + " is: " + str(number_of_words))

This will check if either "Hello" or "Hello;" specifically are in the file. You can expand the regex to fit any other needs (such as lowercase).
It will ignore things such as "Helloing" which other examples here may.
If you prefer not using regex... You can check if taking off the last letter makes it a match such as below:
filename = "/path/to/file.txt"

number_of_words = 0
search_string = "Hello"

with open(filename, 'r') as file:
    for line in file:
        words = line.split()
        for i in words:
            if (i == search_string) or (i[:-1] == search_string and i[-1] == ';'):
                number_of_words += 1

print("Number of words in " + filename + " is: " + str(number_of_words))


text:
Q: Passing log4net ConfigurationFile to a new AppDomain What I need to do is get hold of the the :
<param name="File" value=".\MyExe.exe.log"/>

value but when I try to access the appender using the following :-
var rootAppender = ((Hierarchy)LogManager.GetRepository())
    .Root.Appenders.OfType<RollingFileAppender>()
    .FirstOrDefault();
var myFilePath = rootAppender != null ? rootAppender.File : string.Empty;

I find all I get is null. So how do I access my path?
This is my log4net config section :-
<log4net threshold="All">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value=".\MyExe.exe.log"/>
      <param name="AppendToFile" value="true"/>
      <param name="ImmediateFlush" value="true"/>
      <param name="RollingStyle" value="size"/>
      <param name="MaxSizeRollBackups" value="5"/>
      <param name="MaximumFileSize" value="1MB"/>

      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
      </layout>

      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    </appender>

    <logger name="MYLOGGER">
      <level value="All"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </logger>

  </log4net>

Thanks

A: The reason you can't find the file name is that you are querying the root logger - but you don't have a root logger defined in your config, and the default root does not have any appenders linked to it.
You would need to run this code instead which uses your defined logger to get the filename:
var loggerAppender = LogManager.GetLogger("MYLOGGER").Logger.Repository
                               .GetAppenders()
                               .OfType<RollingFileAppender>()
                               .FirstOrDefault();

var myFilePath = loggerAppender != null ? loggerAppender.File : string.Empty;


text:
Q: Casting a specific element of an array - java I have an array as:
String letters [] = {a, b, c, d, e};
Can I cast a specific element let's say "a" ? I want to get its ascii value, so I did this but it is not working:
for (int i = 0; i < letters.length; i++) {
    Integer iDecimal = (int) a[0];    // the a[0] is wrong!!

    System.out.print(iDecimal);
}

Any ideas about how to cast in such cases?

A: You are trying to cast a[0] which doesn't exist, to access your array you need to do letters[0] and then try working with it. I suggest changing type of your array to char and then casting it, you can't do that with String.

A: Declare the array as object array, but be aware that this is bad coding style, since you are mixing different types in one array.
Object letters [] = {5, "b", 'c'};

The object array contains an integer, a string, and a character you may then iterate over the array and test what object type you have.
The integer element is autoboxed to an Integer-Object.
But again i would not recommend doing so, since element testing is expensive.
for (int i = 0; i < letters.length; i++) {
    if (a[i]) instanceof Integer)
      Integer iDecimal = (Integer) a[i];
}

A: Assuming you want just the ASCII code for the first character in each string in your array, then you can can access that char then cast it to an int.
for (int i = 0; i < letters.length; i++) {
    int iChar = (int) letters[i][0];

    System.out.print(iChar);
}

letters[i] is the ith string in the letters array.
letters[i][0] is the first character of the ith string in the letters array, and will be of type char.
(int)letters[i][0] is the integer value equivalent to the first character of the ith string in the letters array.
Strictly this will give the first UTF-16 word in the string, but for values <127 it will be the same as the ASCII value.
ints are not decimal values, so don't call them decimals. The BigDecimal type is used for decimal values.


text:
Q: Mitm proxy using on Windows I have installed and run mitm proxy (on a Windows machine). Now I want to get the SSL key of the proxy. So anybody know where mitm proxy store this key?
Thanks in advance
Jelena

A: On Windows you can find the generated Mitm root certificate in the user profile after you have run mitmproxy for at least one time:
%USERPROFILE%\.mitmproxy

Alternatively you can simply browse to http://mitm.it using a web browser that is configured to use Mitmproxy. This web page is generated by your mitmproxy instance and allows to download the generated Mitm root CA certificate.

A: Go to http://mitm.it and then from there try to download the certificate for your specific Operating System


text:
Q: Python - Way to encode foreign characters in format Python can work with? I'm working with large files in French and German. Basically, writing strings of characters from one file to another, collecting data from them, and so forth. Unfortunately, I have no idea what to import in order to let Python handle these characters.
Even when collecting data from files that Python has already converted (in french you get weird things like écouteur ça), I get key errors when checking dicts for things that I know have already been placed in that dict, but only when the items have special characters in them like in the example of écouteur ça.
For example, when the tuple ('écouteur', 'ça') has been added to a dict which collects the frequency that any given pair of words occur together, you get a key error when probing that dict for the tuple ('écouteur', 'ça'), but not when probing the dict for other tuples that don't contain the wacky characters.
Does anyone know a quick way to get around this issue at every level?
Best,
Georgina

A: "Unicode in Python, Completely Demystified"


text:
Q: Is there a downside to using foreign weapons? Is there a downside to making my dwarves use foreign weapons such as whips or two-handed swords? The wiki page on weapons Doesn't say of any downside, but I've seen advice to forbid them before. Right now I'm using them in traps, but I don't have any iron-bearing minerals as far as I can find, so a few extra iron weapons would be greatly appreciated by my military.
I've got some lashers so far, as the comments page indicates that whips are awesome in 2010. Is this a bad idea? What about all the other weapons the humans bring that are dwarf-sized, or at least are not marked as large.

A: There are two problems with Foreign Weapons:

*

*Your dwarves haven't actually made them. This means that their quality is generally lower. I don't believe it's possible to make foreign weapons via a mood, like you can with foreign clothing. This means that you're going to have generally lower quality for your weapons, and that they will only be made of iron or bronze. Sure, an Iron Longsword is nice, but can it really top a ☼Steel Short Sword☼ ?

*Foreign Weapons are not optimized for your dwarves in terms of size. If you see a dwarf holding a foreign weapon with the "multigrasp" note, that means they are using both hands to hold the item, and so cannot be assigned a shield.

That said, there is one very tangible benefit to Foreign Weapons:

*

*Whips are crazy OP. Scourges, even more so. Dwarf Fortress doesn't model elasticity yet, which means whips wind up behaving like tiny, supersonic hammers. Quite honestly, its hard for a solid whip-strike to not chip bone, regardless of quality or material.

That said, their is nothing inherently "wrong" with foreign weapons. Feel free to reclaim as many as needed for your dwarves - put the large weapons in weapon traps, and give the militia the rest.
"Fun" Note: Large Daggers (a foreign weapon) pierce armor more easily than any other weapon. Part of the reason why Kobolds can be so deadly.


text:
Q: Sinch SDK uses intranet or internet? I want to build an video calling application b/w raspberry pi and android through intranet Actually there is only a router in the medium which connects raspberry pi and android and no internet b/w them to place a video call.

A: I think they use INTERNET. I used one time and the connection was made by th UserID that the user get when log in on the app.
You can check the documentation here https://www.sinch.com/docs/video/android/
Maybe you can create a connection setting a fixed IP.


text:
Q: if we promote app using different technology . Do the user has to uninstall old App? or just update works? we have developed app using ionic which is on live in playstore and app store, now we have completely rewritten app using reactnative, so if we promote app which is developed using react native, Do the user has to uninstall old App? or just update works?

A: My understanding is that if it uses the same app identifier that it will just work for the user.
You can also see it here: Recreating an iOS App with the same Bundle ID, App name etc


text:
Q: How to prove the following convex cone property Suppose $A,B$ are closed cvx cones. $A^*,B^*$ are their dual cones respectively.
How to show $$ (A^*+B^*)^*\subset A \cap B$$
My idea is:
$$A^* = \{x_1|x_1^Tx \geq 0, \forall x \in A\}$$
$$B^* = \{y_1|y_1^Ty \geq 0, \forall y \in B\}$$
$$(A^*+B^*)^* = \{z|z^T(x_1+y_1) \geq 0, \forall (x_1+y_1) \in (A^*+B^*)\}$$
So, to show "$\subset A \cap B$", we have to show $z \in A \cap B$.
My question is:
I am confused about $A \cap B$, since we cannot say $z \in A \cap B$ by proving $x_1^Tz \geq0$ and $y_1^Tz \geq 0$. It is because such $z$ could be ou of $A \cap B$.
The other way is by contradiction. However, in this way we have to consider three case: since $z \notin A \cap B$, it could be in $A$ but not in $B$, or $B$ not in $A$ or neither $A$ nor $B$. A little bit cumbersome
How to use the property of $A \cap B$?

A: Let $x\in(A^*+B^*)^*$. So $\forall{y}\in A^*+B^*, (x,y)\ge0$. It means that  $\forall{y}\in A^*, (x,y)\ge0$ so $x\in A^{**}$. Since $A$ is closed $A^{**}=A$ and $x\in A$. Similarly we can show that $x\in B$. So $x\in A\cap B$


text:
Q: Using a standard localised data cryptography pattern with an ASP.NET MVC3 application I have been given the task to rejuvenate an existing Human Resources application from Access into ASP.NET. This is a strictly internal application, and I have no problems developing it within our standard ASP.NET environment. It does however pose it's own problems, both technically and ethically.
The HR app will be responsible for storing employee pay data, for which it is not appropriate for me, the developer, to see. It's essentially three fields (salary band, actual salary, comments) and four other values, calculated on the front end.
I'd like to go down the cryptography route to encrypt said data - cryptography with the .NET Framework is very easy to implement. I could "roll my own", which as we all know is a bad idea. However I was wondering if there was a more better way of doing it. Here are some points:

*

*For starters, we're all attached to the same domain.

*I've heard and read about Certificates, can they be useful here? (x.509?)

*The data will be stored in our local SQL Server, obviously the actual data here needs to be encrypted, so can SQL Server help me? Certificates again?

*If a user doesn't have the appropriate certificate, can the data just be null? (You can't see this matey!)

*This encryption problem doesn't have any relevance to usage of the system via a permissions model.

A: This sounds to me like the same issue as credit card data in pci certified systems. You as a developer and later on the sysadmins and support staff are not allowed to see the data. Read into how people solve that problem and it should solve yours.
It comes down (a really short description) to encrypting each row with different keys and an environmental key. The environmental key should be stored only on the app servers, the per row key can be stored in the database. This way, someone with only database access cannot decrypt it, someone with only appserver access cannot decrypt it. Make sure that production and dev/test are not using the same environmental keys. So, a production database going back to dev or test for debugging purposes cannot be decrypted because dev does not know the production key. Still you can reset all data in the database (production backup downloaded for testing) with a single sql update (point it to a single per row key and use the dev encryption key and set everything to the same encrypted value).
Have a tool to replace an environmental key (decrypt with old and encrypt with new the data) if it might be compromised (or an employee having access to it leaves.)
There are a lot of sites with information on these pci standards and implementations. Read into it and you will certainly get an implementation which would work for your problem.
The encryption algorithm itself does not really matter, as long it is a known strong method

A: Your comments indicate that you are "writing the system in its entirety which means I have access to everything".  Can you not lean on your IT team here?

*

*Ask a current user of the Access database to make a copy of it and replace everyone's salary with $10,000 (for instance).

*Develop the application on your workstation or on a development server.

*Provide a proper security model to ensure that the correct users (aka not you) can see what they need to see

*Provide a tool to allow an administrative user to enter the proper salaries

*Get IT to deploy the application and enable something like SQL Server's TDE on the production version

Additionally, using something like Microsoft's WIF or ADFS to provide single sign on is also a good idea given that you indicate your users are on the same domain.

A: If you just want to hide clear data from eyes - store encrypted information in database and decrypt it when necessary. You can use asymmetric alghoritm and store private key in file that can be accessible only for several users. This approach would require additional code to search/sort/filder the information, but it will be secure.


text:
Q: Count relationed items I have a query like this:
SELECT
*

FROM Product.Stock AS PS
INNER JOIN Product.Product AS P ON PS.ProductId = P.ProductId
INNER JOIN Product.ProductDetail AS PD ON P.ProductId = PD.ProductId
INNER JOIN Product.ProductSize AS PSI ON P.ProductId = PSI.ProductId

I want to know how many ProductsId with same SizeId I have, for example:

in this case I have two products with same ProductId and SizeId, so I wish get: 2 because I have 2 products with sizeId 1
ProductId comes from table: Product.Product
SizeId comes from table: Product.ProductSize
How can I achieve it? Regards

A: SELECT
PSI.SizeId, COUNT(DISTINCT P.ProductId)

FROM Product.Stock AS PS
INNER JOIN Product.Product AS P ON PS.ProductId = P.ProductId
INNER JOIN Product.ProductDetail AS PD ON P.ProductId = PD.ProductId
INNER JOIN Product.ProductSize AS PSI ON P.ProductId = PSI.ProductId
GROUP BY PSI.SizeId

I'm assuming that the SizeId column is in the Product.ProductSize table.

A: Use Having Count in order to just show sizes with multiple products and no need for inner joins, since you already have all the fields in one table:
SELECT  SizeId, COUNT(Distinct ProductId)
    FROM  Product.ProductSize
    GROUP BY SizeId
    Having Count(Distinct ProductId)> 1

A: Agree with @Jack's answer, still I think joins seem to be redundant here.
SELECT
SizeId, COUNT(DISTINCT ProductId)

FROM Product.ProductSize
GROUP BY SizeId


text:
Q: html/php form gives me 500 internal server error when adding more input fields Hi, I have a problem with my php and html form. What I am trying to do is just get a form with 7 input fields, 6 of these are input field or text area and one will be a checkbox. I have one hidden field, the first 3 boxes the hidden field the first name and message. The only problem I have is when I add a new input box it shows me the 500 error. My code is below:
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
  {
  ?>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

  <input type="hidden" name="subject" value="can you create me an account">

  Message: <textarea rows="10" cols="40" name="message"></textarea>

  first <input type="text" name="first_name" >
  <input type="submit" name="submit" value="Submit Feedback">
  </form>

<?php
  }
else
  // the user has submitted the form
  {
  // Check if the "subject" input field is filled out
  if (isset($_POST["subject"]))
    {
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $first = $_POST["first_name"];

    $message = wordwrap($message, 70);
    $first = wordwrap($first, 70);
    // send mail
    mail("summat@gmail.com",$subject,$message,$first,"subject: $subject\n");
    echo "Thank you for sending us feedback";

When I add a new input box my code looks like :
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
  {
  ?>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

   <input type="hidden" name="subject" value="can you create me an account">

   Message: <textarea rows="10" cols="40" name="message"></textarea>

   first <input type="text" name="first_name" >
   last <input type="text" name="last_name" >
   <input type="submit" name="submit" value="Submit Feedback">
  </form>

<?php
  }
else
  // the user has submitted the form
  {
  // Check if the "subject" input field is filled out
  if (isset($_POST["subject"]))
    {
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $first = $_POST["first_name"];
    $last = $_POST["last_name"];

    $message = wordwrap($message, 70);
    $first = wordwrap($first, 70);
    $last = wordwrap($last, 70);
    // send mail
    mail("summat@gmail.com",$subject,$message,$first,$last,"subject: $subject\n");
    echo "Thank you for sending us feedback";

Everything shows on the screen when I add them but when I press submit I get:

500 - Internal server error. There is a problem with the resource you
  are looking for, and it cannot be displayed.

and nothing gets submitted. Is it because it times out before it send or to much data or have I just missed something very basic?
Any help would be much appreciated.

A: The problem is that in the 2nd example you're trying to pass 6 variables to the mail() function when it accepts 5. Check here on how you can pass additional headers.

A: 6 Variables will result in:
Warning: mail() expects at most 5 parameters, 6 given in YOUR WEBSITE on LINE
Solution example:
    <?php
     //var_dump($_POST);
    if (isset($_POST["subject"]))
        {
        $subject = $_POST["subject"];
        $message = $_POST["message"];
        $first = $_POST["first_name"];
        $last = $_POST["last_name"];
        $name= "$first $last";
    }
        $message = wordwrap($message, 70);
        $first = wordwrap($first, 70);
        $last = wordwrap($last, 70);
        mail("summat@gmail.com",$subject,$message,$name,"subject: $subject\n");
        echo "Thank you for sending us feedback";
      ?>

Answer to your reply:
Php:
 <?php
 //var_dump($_POST);
if (isset($_POST["subject"]))
    {
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $first = $_POST["first_name"];
    $last = $_POST["last_name"];
    $company = $_POST["company"];
    $email = $_POST["email"];
    $telnr = $_POST["telnr"];
    $description = $_POST["description"];
    $therest = "First name= $first" . "\r\n" . "Last name= $last" . "\r\n" . "Last name= $last" . "\r\n" . "Company= $company" . "\r\n" . "Email= $email" . "\r\n" . "Telnr= $telnr" . "\r\n" . "Description= $description";

    //echo "$therest
";
    $message = wordwrap($message, 70);
    $first = wordwrap($first, 70);
    $last = wordwrap($last, 70);
    mail("Your Email Address Here",$subject,$name,$therest,"subject: $subject\n");
    echo "Thank you for sending us feedback";
}

HTML
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

   <input type="hidden" name="subject" value="can you create me an account">

   Message: <textarea rows="10" cols="40" name="message"></textarea>

   first <input type="text" name="first_name" >

   last <input type="text" name="last_name" >

   company <input type="text" name="company" >

   email <input type="text" name="email" >

   Telephone number <input type="text" name="telnr" >

   Description <input type="text" name="description" >

   <input type="submit" name="submit" value="Submit Feedback">
  </form>

Demo: here
It will send the mail to the mail your entered in the form


text:
Q: How to assign varibale in h tag in PHP I am trying to assign a PHP variable in h3 tag. Below is my tag:
'Summary' => [
  'data' => '

Scan Summary:

Total Found:<?php echo $totalFind ?>

Total Dir: 53

Planned Sync Files: 175

Actual Synced: 175

Missing Synced Files: 0

',
  'colspan' => 5, 'class' => array('foo', 'bar'),
],

But it does not allow me to do that, how can I assign a variable value?

A: You mean like this:

Total Found:<?php echo $totalFound ?>

?
After your edit:
'Summary' => [
  'data' => '

Scan Summary:

Total Found: '.$totalFind.'

Total Dir: 53

Planned Sync Files: 175

Actual Synced: 175

Missing Synced Files: 0

',
  'colspan' => 5, 'class' => array('foo', 'bar'),
],

A: 'Summary' => [
  'data' => '

Scan Summary:

Total Found:'.$totalFind.'

Total Dir: 53

Planned Sync Files: 175

Actual Synced: 175

Missing Synced Files: 0

',
  'colspan' => 5, 'class' => array('foo', 'bar'),
],


text:
Q: Why while loop keep asking to define a variable even if it's already defined? I'm practicing loops in VsCode and watching basic tutorials. I decided to run a very simple code that looks like this
x = 1
while x <= 100:
    print(x)
    x = x + 1

However I keep getting this error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined

According to all tutorials I saw it should work. But it doesn't. What could be the problem here?
========================================================================


text:
Q: Instance methods with default and variable length arguments I am trying to create a method that can be called in the following manner:
instance.respond('some command', 'command arg 1', 'command arg 2', 'command arg 3')
instance.respond(true, 'some command', 'command arg 1', 'command arg 2', 'command arg 3')
instance.respond(false, 'some command', 'command arg 1', 'command arg 2', 'command arg 3')

The true/false values indicate if the command should be sent immediately or buffered, respectively.
I tried to define the method as in the following example:
class Foo
    def bar1(arg1=true, arg2)
        puts 'this works'
    end

    def bar2(arg1, *args)
        puts 'this works as well'
    end

    def bar3(arg1=true, arg2, *args)
        puts 'but this fails'
    end
end

Running this gives the error:
/opt/dl/testcase.rb:10: syntax error, unexpected *
    def bar3(arg1=true, arg2, *args)
                               ^
/opt/dl/testcase.rb:13: syntax error, unexpected keyword_end, expecting end-of-input

Is there a way to resolve this, or to work around it?

A: Since you haven't specified which ruby version you are using, I'm going to assume that a version >= 2 is fine. If this question is just about fixing the syntax error, then you could write something like
class A
  def respond(flag = true, b = '', *args)
    "flag=#{flag}, b=#{b} args=#{args.join(',')}"
  end
end

However, there are some issues you'd encounter:
A.new.respond('some command', 'command arg 1', 'command arg 2', 'command arg 3')
#=> flag=some command, b=command arg 1 args=command arg 2,command arg 3

A.new.respond(true, 'some command', 'command arg 1', 'command arg 2', 'command arg 3')
#=> flag=true, b=some command args=command arg 1,command arg 2,command arg 3

A.new.respond(false, 'some command', 'command arg 1', 'command arg 2', 'command arg 3')
#=> flag=false, b=some command args=command arg 1,command arg 2,command arg 3

An approach that would make use of named arguments would be safer. You could for example do something like
class B
  def respond(flag: true, b:, **args)
    "flag=#{flag}, b=#{b} args=#{args.values.join(',')}"
  end
end

args = {
  c1: "command arg 1",
  c2: "command arg 2",
  c3: "command arg 3"
}

B.new.respond(b: 'some command', **args)
#=> flag=true, b=some command args=command arg 1,command arg 2,command arg 3

B.new.respond(flag: true, b: 'some command', **args)
#=> flag=true, b=some command args=command arg 1,command arg 2,command arg 3

B.new.respond(flag: false, b: 'some command', **args)
#=> flag=false, b=some command args=command arg 1,command arg 2,command arg 3

A: @simplaY has shown how named arguments can be used here. One has a few options if versions of Ruby prior to 2.0 (when named arguments made their debut) must be supported.
#1
def respond(*args)
  flag = true # default
  flag = args.shift if [true, false].include? args.first
  puts "flag = #{flag}"
  puts "args = #{args}"
  if flag
    # code
  else
    # code
  end
end

respond "dog", "cat"
flag = true
args = ["dog", "cat"]

respond false, "dog", "cat"
flag = false
args = ["dog", "cat"]

This of course requires that the permitted value of the first argument is true or false if and only if it is the value of flag.
#2
def respond(flag=true, args)
  if flag
    # code
  else
    # code
  end
end

called
respond ["dog", "cat"]
respond true, ["dog", "cat"]
respond true, ["dog", "cat"]

Whenever a method has a variable number of arguments the rule is that it will be unambiguous to Ruby if and only if it is unambiguous to you.
#3
def respond(options)
  flag = options.fetch(:flag, true)
  if flag
    # code
  else
    # code
  end
end

called
respond(arg1: 'dog', arg2: 'cat')
respond(flag: false, arg1: 'dog', arg2: 'cat')

This last approach, which was widely used prior to Ruby 2.0, has been largely supplanted by the use named arguments, in part because named arguments display the keys whose values are being passed, whereas in this last approach only the hash is identified among the method's arguments.


text:
Q: Python3 - reading a CSV file and making changes Write a function that reads a CSV file (textFile.csv), removes all whitespace and stores each word in a list
So far I have:
 fileobj = open('textFile.csv', 'r')

Unsure how to remove the whitespaces and store each word in a list


text:
Q: sqlite3 operational error when inserting new data I have a database wxpython GUI for my suppliers, within this insert new supplier function I am creating a new supplier contact. I cannot find what is causing this error.  The function is below along with where the error is occurring.
def insertNew(self,event):

        with con:
                cur = con.cursor()

                cur.execute("INSERT OR IGNORE INTO Suppliers (Supplier, Code, Commodity, Contact, Number, EmailContact, TechnicalContact, TechnicalContactEmail, Address,) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
                            (self.text_list[0].GetValue(), self.text_list[1].GetValue(), self.text_list[2].GetValue(), self.text_list[3].GetValue(), self.text_list[4].GetValue(),
                              self.text_list[5].GetValue(), self.text_list[6].GetValue(), self.text_list[7].GetValue(), self.text_list[8].GetValue()))
                con.commit()

The error is
Traceback (most recent call last):
  File "C:\Users\ONP1LDY\eclipse-workspace\WOrk\SupplierDB.py", line 169, in insertNew
    self.text_list[5].GetValue(), self.text_list[6].GetValue(), self.text_list[7].GetValue(), self.text_list[8].GetValue()))
sqlite3.OperationalError: near ")": syntax error

Can anyone see where the error is coming from?

A: you need to remove the comma after Adress, it's waiting for another column identifier:
cur.execute("INSERT OR IGNORE INTO Suppliers (Supplier, Code, Commodity, Contact, Number, EmailContact, TechnicalContact, TechnicalContactEmail, Address) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
                            (self.text_list[0].GetValue(), self.text_list[1].GetValue(), self.text_list[2].GetValue(), self.text_list[3].GetValue(), self.text_list[4].GetValue(),
                              self.text_list[5].GetValue(), self.text_list[6].GetValue(), self.text_list[7].GetValue(), self.text_list[8].GetValue()))