text:
Q: Python random seed not working with Genetic Programming example code I am trying to get reproducible results with the genetic programming code in chapter 11 of "Programming Collective Intelligence" by Toby Segaran. However, simply setting seed "random.seed(55)" does not appear to work, changing the original code "from random import ...." to "import random" doesn't help, nor does changing Random().  These all seem to do approximately the same thing, the trees start out building the same, then diverge.
In reading various entries about the behavior of random, I can find no reason, given his GP code, why this divergence should happen.  There doesn't appear to be anything in the code except calls to random, that has any variability that would account for this behavior.  My understanding is that calling random.seed() should set all the calls correctly and since the code isn't threaded at all, I'm not sure how or why the divergence is happening.
Has anyone modified this code to behave reproducibly? Is there some form of calling random.seed() that may work better?
I apologize for not posting an example, but the code is obviously not mine (I'm adding only the call to seed and changing how random is called in the code) and this doesn't appear to be a simple issue with random (I've read all the entries on Python random here and many on the web in general).
Thanks.
Mark L.

A: I had the same problem just now with some completely unrelated code. I believe my solution was similar to that in eryksun's answer, though I didn't have any trees. What I did have were some sets, and I was doing random.choice(list(set)) to pick values from them. Sometimes my results (the items picked) were diverging even with the same seed each time and I was close to pulling my hair out. After seeing eryksun's answer here I tried random.choice(sorted(set)) instead, and the problem appears to have disappeared. I don't know enough about the inner workings of Python to explain it.

A: This may help, to create a random object that won't be interfered with from elsewhere:
from random import Random
random = Random(55)
# random can be used like the plain module

If other libraries are calling random.seed for any reason, they won't affect the random object you've created for your program.

A: I added the following function to gp.py, changing nothing else:
def set_seed(n):
  import random
  random.seed(n)

I'm using the module based on the example on page 267 (Google books). I can confirm that I get divergent results for the following trial:
>>> import gp
>>> gp.set_seed(55)
>>> rf = gp.getrankfunction(gp.buildhiddenset())
>>> gp.evolve(2, 500, rf, mutationrate=0.2, breedingrate=0.1, pexp=0.7, pnew=0.1)

It starts to diverge as early as the 4th value printed. I'm restarting the interpreter between trials, so it's not any prior state that's causing the problem.
Edit:
I found the random element. It's the memory address of the trees. The rank function sorts the list of results, for which each item is a tuple of the score and tree. Between runs the addresses change, and so the relative sort order of trees with equal score isn't a constant. Fortunately Python has a stable sort, so the fix is simple enough. Just use a sort key to sort based on only the score:
def getrankfunction(dataset):
  def rankfunction(population):
    scores=[(scorefunction(t, dataset), t) for t in population]
    scores.sort(key=lambda x: x[0])
    return scores
  return rankfunction


text:
Q: android: checking and changing image of button in my application i'm checking image of button for 1sec.n changing it.what happen is when first time it checks n changes image of button.and the 2nd time its not changing the image.
here is the code-
myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {

                    Random rand=new Random();
                    int num = rand.nextInt(buttonIds.length);
                    int buttonId = buttonIds[num];
                    Button bb=(Button) findViewById(buttonId);

                    Drawable a=bb.getBackground();

                    if(getResources().getDrawable(R.drawable.happy).equals(a))
                    {
                    bb.setBackgroundResource(R.drawable.happy);
                    }
                    else
                     {
                    bb.setBackgroundResource(R.drawable.whoa);
                     }

                }
            });
        }

    },0, 1000);

first time image of button is happy(name of image file).
how can i change image of button and also check??
Thanku

A: I think your if condition is not correct, you a checking if the background image is happy, you are again setting happy..instead you should set whoa...

A: If I were you, I would use a boolean(isHappy) to notify if the picture is happy or not, it is easier and faster since you don't have to instance the current image and maybe it will solve your problem, I am not completely sure about "equals" works like that, but is only my guess.
Anyway I think your code has a small mistake, the condition makes the picture to be always happy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with ode system, using solve_ivp. ValueError: setting an array element with a sequence I'm trying to solve ODE system. It is simulation of vehicle movement which includes P regulator.
At this point I don't know what is exactly wrong.  Error occurs: ValueError: setting an array element with a sequence. I've tried to do it with ode.integrate but the results is the same.
Also I don't exactly know how to indicate some dependencies like position- velocity or di/dt - i where i is electric current, it's probably the reason.
Some code explanation: velocity is regulated by torque(T_m), which is regulated by electric current (i), which is regulated by voltage (U_m), voltage is equal to difference between current velocity and velocity from V(t) function. V(t) function is giving back interpolated velocity from CSV file.
import numpy as np
import matplotlib.pyplot as plt
import csv
from scipy.interpolate import interp1d
from scipy.integrate import solve_ivp

def F_t(y,p):
    if y[1]>0.1:
         return p[3]*(1+p[4]*y[1])
    else:
        return 0

def T_m(y,p):
    return y[3]*p[11]

def F_n(y,p):
    return T_m(y,p)*p[7]*p[13]/p[6] - F_t(y,p)

def U_m(t,y):
    return (V(t) - y[1])*p[10]

def carx(t, y, p):
    s, v, s_c, i = y
    p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16 = p # there is a lot of p's because later there will be more equations
    ds = v
    dv = F_n(y,p)/(p5*p3)
    ds_c = V(t)            # theoretical distance
    di = (U_m(y,p) - i*p8 - v*p12*p7/p6)/p9
    return np.array([ds, dv, ds_c, di])

y0 = np.array([0, 0, 0, 0])
t_span = np.linspace(0, 1801, 18000)
sol = solve_ivp(lambda t, y: carx(t, y, p), [t_span[0], t_span[-1]], y0, t_eval=t_span)

There is more code, but i don't think it's necessary to show importing CSV file.
I hope everything is clear. I did working code in Julia, so i can show if someone ask.


text:
Q: Django on_delete=CASCADE not working, can't delete parent row using raw SQL Django models:
class Parent (Model):

    name = CharField (max_length = _MAX_NAME_LENGTH, unique = True)

class Child (Model):

    name = CharField (max_length = _MAX_NAME_LENGTH, unique = True)

    parent = ForeignKey (Parent, on_delete = CASCADE)

Create some data:
p = Parent (name='parentname')
p.save ()

c = Child (name='childname', parent=p)
c.save ()

Delete parent, expecting child to be deleted via cascade:
DELETE FROM `basedb_parent` WHERE `basedb_parent`.`id` = 1

#1451 - Cannot delete or update a parent row: a foreign key constraint fails (idat_prealpha_0_1.basedb_child, CONSTRAINT basedb_child_parent_id_d6f3ee55_fk_basedb_parent_id FOREIGN KEY (parent_id) REFERENCES basedb_parent (id))

Although running p.delete() in the Python code does delete the Parent and Child rows. I know this is actually happening in the underlying MySQL database because the AUTO_INCREMENT table attribute increases (so it's not being shortcutted by any kind of fancy cache in Django).
Why doesn't my DELETE FROM query work, while p.delete() does work?


text:
Q: Probability distribution function expressed in terms of a divergent series I'm interested in finding the CDF and PDF of $U_i$ defined as follows,
$$U_i=\frac g{d^{\alpha}}$$
where $g$ is a gamma distributed random variable with shape $k$ and scale $\theta$, and $d$ is a random variable with distribution $f_d(x)=\frac {2x}{R^2}, 0\le x \le R$.
To find the CDF of  $U_i$
$$F_{U_i}(y)=P(U_i<y)=\int_0^R F_g(yx^\alpha)f_d(x)dx$$
where $F_g(y)$ is the CDF of gamma distributed random variable.
 After performing the integration, which requires the use of the expansion of incomplete gamma function, I came to the following CDF:
$$F_{U_i}(y)=\sum_{n=0}^\infty \frac {2(-1)^nR^{k\alpha+n\alpha}y^{k+n}}{\Gamma(k)n!\theta^{k+n}(k+n)(k\alpha+n\alpha+2)}$$
I want the CDF in this format because my ultimate goal is to find the CDF of $U=\sum_{i=1}^NU_i$ which requires me to find the Laplace transform of $F_{U_i}(y)$ and raise it to power $N$.
Now it's easy to find the PDF of $U_i$, i.e. $f_{U_i}(y)=\frac {d}{dy}F_{U_i}(y)$.
I'm looking for someone to clarify these points to me:

*
My derived $f_{U_i}(y)$ doesn't make sense to me, because it's based on a divergent series. How can it's integration from zero to infinity equals one?

*
In Matlab I took the $K^{th}$ elements of the series, and plotted it along with the histogram of 1000 $U_i$'s, the two plots are not related.

*
If you look at the definition of $U_i$, $U_i$ can take values from 0 to infinity, high values take less probability. This fact is not clear in the derived distribution $f_{U_i}(y)$. What is the domain of the derived PDF? What is the integration limit if I wannna find $F_\epsilon(\epsilon)=\int f(y)F_{U_i}(\epsilon(y+\sigma^2))dy$? where $f(y)$ is another density function.

*
How can I simulate the derived PDF in Matlab to check if it's really correlated with $U_i$

A: The series converges to a distribution function.  It can be evaluated in closed form.
Upon identifying the terms varying with $n,$ write your function in a simpler form as
$$\begin{equation*}
F_{U_i}(y)=\frac{2(R^{\alpha}y/\theta)^k}{\Gamma(k)}\sum_{n=0}^\infty \frac {(-R^\alpha y / \theta)^n}{n!(k+n)((k+n)\alpha+2)} \\
= \frac{2x^k}{\Gamma(k)}\sum_{n=0}^\infty \frac{(-x)^n}{n!\,(k+n)((k+n)\alpha+2)}
\end{equation*}$$
for $x = R^\alpha y /\theta.$  In other words, $\sigma=\theta/R^\alpha$ is a scale parameter.
Assuming (from the form of the expression $g/d^\alpha$) that $\alpha \gt 0,$ every one of the terms in the sum is bounded above in size by $x^n / n!$ showing the sum is dominated by the absolutely convergent series for $\exp(x),$ whence the sum converges absolutely for all $x.$
To evaluate such a sum we will use partial fractions.  Consider the simpler function
$$h(x, a) = \sum_{n=0}^\infty \frac{(-1)^n x^n}{n! (a+n)}$$
with $a \ge 0.$  Similar considerations demonstrate absolute convergence so we may differentiate term by term to obtain
$$\frac{\mathrm{d}}{\mathrm{d}x} \left(x^a h(x,a)\right) = \sum_{n=0}^\infty \frac{(-1)^n x^{n+a-1}}{n!} =  x^{a-1}\sum_{n=0}^\infty \frac{(-1)^n x^{n}}{n!} = x^{a-1} e^{-x}.$$
Therefore
$$h(x,a) = x^{-a} \int^x t^{a-1} e^{-t}\mathrm{d}t = C + x^{-a}\,\gamma(a, x),$$
where $\gamma$ is the lower Incomplete Gamma Function and $C$ is a constant of integration.   It can be found by applying L'Hopital's Rule to $x^{-a}\int_0^x t^{a-1} e^{-t}\mathrm{d}t$ as $x\to 0^+$ and comparing the resulting limit of $C+1/a$ to $h(0,a) = (-0)^0/(0!(a+0)) = 1/a$ to conclude $C=0.$
Now because
$$\frac{1}{(k+n)((k+n)\alpha+2)} = \frac{1}{\alpha}\frac{1}{(k+n)(k+n+2/\alpha)} = \frac{1}{2}\left(\frac{1}{k+n} - \frac{1}{k+n+2/\alpha}\right),$$
we again exploit the absolute convergence of the series for $F_{U_i}$ and set $a=k,$ $b=k+2/\alpha$ to express it as

$$F_{U_i}(y) = \frac{2x^k}{\Gamma(k)}\sum_{n=0}^\infty \frac{(-x)^n}{n!\,(k+n)((k+n)\alpha+2)} = \frac{\gamma(k,x) - x^{-\frac{2}{\alpha}}\gamma(k+\frac{2}{\alpha},x)}{\Gamma(k)}$$ where $$x = y/\sigma = R^\alpha y / \theta \text{ and }\sigma=\theta/R^\alpha.$$

Differentiating this to obtain the density is straightforward, yielding
$$\frac{\mathrm{d}}{\mathrm{d}x} F^\prime_{U_i}(y) = \frac{2\gamma(k+2/\alpha, x)}{\alpha \Gamma(k) x^{1 + 2/\alpha}} \ge 0$$
and it is also elementary to establish that
$$\lim_{y\to\infty} F_{U_i}(y) = 1 \text{ and } \lim_{y\to 0^+} F_{U_i}(y) = 0.$$
Therefore $F_{U_i}$ is the CDF of a continuous random variable.

Almost any statistical computing platform will compute the CDF of Gamma variables (or, equivalently, of Chi-squared variables).  This is the normalized version of $\gamma.$  For instance, here are R implementations of $F_{U_i}$ and its derivative:
# CDF
pFU <- function(x, k, alpha, scale=1) {
  x <- x / scale
  h <- function(x, a)
    ifelse(x > 0, exp(pgamma(x, a, log.p=TRUE) + lgamma(a)), 1/a)
  (h(x, k) - x^(-2/alpha) * h(x, k + 2/alpha)) / gamma(k)
}

# PDF
dFU <- function(x, k, alpha, scale=1) {
  x <- x / scale
  ifelse(x <= 0, 0,
         2/alpha * exp(-(1 + 2/alpha)*log(x) + pgamma(x, k+2/alpha, log.p=TRUE) +
                         lgamma(k+2/alpha) - lgamma(k))) / scale
}

Here are plots of them using the curve function:

The underlying red curves use these functions.  As a check, overplotted in black are direct implementations of the original series (for the CDF) and a numerical derivative of pFU (for the PDF).


text:
Q: Bulk API 2.0 v52.0 Query select * I'm trying to post the following json body to the Bulk Api endpoint but am getting an error.
{
  "operation": "query",
  "query": "SELECT * FROM Account"
}

error
[
    {
        "errorCode": "INVALIDJOB",
        "message": "Query parsing error: unexpected token: '*'"
    }
]

Is select * not allowed or am I just doing it wrong?

A: Salesforce uses something called Salesforce Object Query Language, or SOQL for short.  SQL is not used in most cases, and the edge cases are from what I understand only applicable for certain things in Marketing Cloud.
There is a decently recent addition to SOQL that's similar to using a SELECT * in SQL, which is SELECT FIELDS(ALL), but unless you're using a where clause that matches on the ID (WHERE Id = 'idgoeshere'), you must specify a limit of 200 or less (more on FIELDS() here).  If you want more than that, you have to specify each field you want to retrieve.
I would follow @identigral's advice and brush up on the SOQL Trailheads, and depending on what you're looking to do, Data Loader might be something to look into as well.


text:
Q: Read Resource strings programmatically I Have around say 6 dll's ( No source code ).
They do not contain any Logic but just a .resx file that contains a string table.
Is there a way where I can extract the Id's and values from the string table from each of these dll's and Export it to a text file?

A: Knowing the assembly name and the resource file, you can load it using reflection.
// Resources dll
var assembly = Assembly.LoadFrom("ResourcesLib.DLL");

// Resource file.. namespace.ClassName
var rm = new ResourceManager("ResourcesLib.Messages", assembly);

// Now you can get the values
var x = rm.GetString("Hi");

To list all Keys and Values you can use the ResourceSet
var assembly = Assembly.LoadFrom("ResourcesLib.DLL");
var rm = new ResourceManager("ResourcesLib.Messages", assembly);

var rs = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);

foreach (DictionaryEntry r in rs)
{
    var key = r.Key.ToString();
    var val = r.Value.ToString();
}

If you don't have access to the resources lib, you can see what are the namespaces, classes, and everything else through Reflector as mentioned by Leo.


text:
Q: Android dynamic layout performance I have a potentially large number of elements to display inside a scroll view.
The scroll view is inside a viewflipper, so the scroll view is only created when the user hits a button to flip the view.
I dynamically add a "row" for each entry that I need to show, and populate the row accordingly.
When I've got a large number of elements to display, the scroll view takes a long time to instantiate.
The scroll view looks like :
<framelayout>
...
<linear layout>
...
<viewflipper>
...

           <ScrollView
            android:id="@+id/scroll_view_viewflip"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="75dip" >

            <LinearLayout
                android:id="@+id/scroll_view_linear"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >
            </LinearLayout>
        </ScrollView>

I populate the scroll view with rows that look like: (a separate XML layout)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<TextView
    android:id="@+id/tv_name"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

<TextView
    android:id="@+id/tv_value"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

<EditText
    android:id="@+id/et_value"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

<NumberPicker
    android:id="@+id/picker_value"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

<Spinner
    android:id="@+id/spin_value"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

<TextView
    android:id="@+id/tv_units"
    style="@style/SearchTableColumn"
    android:layout_weight="25" />

And the code does, more or less:
LinearLayout row = (LinearLayout) layoutInflater.inflate(R.layout.attribute_row, null);
// multiple row.findViewById() for the elements on the row
// set up which element will be shown or hidden and set values
layout.addView(row);

From doing a trace, the bulk of the time appears to be in the inflater/inflate() function.
Are there things I can do in the XML, or in my row-creation to improve speed ?  We're talking about maybe 100s of rows. Other questions have indicated a list view is a bad idea for performance, and my data is slightly-tree-view like (but not interested in using a 3rd party tree-view control).
I could implement an async task to fill the scroll view in the background, and add synchronization logic to "wait" when the view-flipper button is pressed, but wondering if there are better options.


text:
Q: Remote error on pushing repository I have two repository project and project2. Project2 is a clone of project repository whenever I tried to push the files from project2 I got remote errors.
Total 6 (delta 0), reused 0 (delta 0)
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree   inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable t
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing int
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in som
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, se
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To C:/Users/Ashish/Desktop/new_1
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to 'C:/Users/Ashish/Desktop/new_1'


text:
Q: Javascript buttons using arrays My assignment is to create 4 buttons that scroll through 20 pictures. The pictures are currently labeled usa1.jpg all the way up to usa20.jpg. The goal is to create a first/last button that takes you all the way to the very first and last picture, and a classic next and previous button to go through the pictures. My instructor is old fashioned and this is the very first javascript class so if you see any really old looking code please remember that the instructor is requiring me to use it as it is shown and not to use anything that is beyond beginner level; otherwise I will get docked points for this assignment. Right now the images are not loading on the site when I pull it up. Any other tips or info would also be greatly appreciated.

   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="styles/usa.css">
   <title>USA Tour</title>

        Images From USA Tour 2007

        <button type="button" id="first"><=</button>
        <button type="button" id="previous"><</button>
        <button type="button" id="next">></button>
        <button type="button" id="last">=></button>

-----------------------------------------------------------------------

window.onload = function() {
    var loadFirstBtn = document.getElementById("first");
    var loadNextBtn = document.getElementById("next");
    var loadPrevBtn = document.getElementById("previous");
    var loadLastBtn = document.getElementById("last");
    var extension = ".jpg";
    var imgPath = "images/usa-";
    var images = [];

    function loadImages() {
        for (var i = 0; i < 20; i++) {
            images[i] = new Image();
            if () {
                images[i].src = imgPath + (i + 1) + extension;
            }
            console.log(images[i].src);
        }
    }
    loadFirstBtn.onclick = function(){
        var tds = document.getElementsById("btns");
        var len = images.length;
        for (var i = 0) {
            tds[i].appendChild(images[i]);
        }
    }
    loadNextBtn.onclick = function(){
        var tds = document.getElementsById("btns");
        var len = images.length;
        for (var i = 0; i++) {
            tds[i].appendChild(images[i]);
            images.sort(function(a, b) {
                return a - b;
            });
        }
    }
    loadPrevBtn.onclick = function(){
        var tds = document.getElementsById("btns");
        var len = images.length;
        for (var i = 0; i--) {
            tds[i].appendChild(images[i]);
            images.sort(function(a, b) {
                return b - a;
            });
        }
    }
    loadLastBtn.onclick = function(){
        var tds = document.getElementsById("btns");
        var len = images.length;
        for (var i = 20) {
            tds[i].appendChild(images[i]);
        }
    }
    loadImages();

}


text:
Q: SLIM framework rest API error in sending email i am designing REST API using SLIM framework. i want to send email in php.
i have write mailing.php which is sending email very accurately.
but whenever i call that mailing.php from my REST API of slim framework. then this following error occurs .
Slim Application Error
The application could not run because of the following error:

Details:

Message: Assigning the return value of new by reference is deprecated
File: C:\xampp\php\PEAR\Mail.php
Line: 154
Stack Trace:

#0 C:\xampp\htdocs\CC\mailing.php(2): Slim::handleErrors(8192, 'Assigning the r...', 'C:\xampp\php\PE...', 154, Array)
#1 C:\xampp\htdocs\CC\mailing.php(2): require_once()
#2 C:\xampp\htdocs\CC\waist.php(2): include('C:\xampp\htdocs...')
#3 C:\xampp\htdocs\CC\testingnew.php(545): include('C:\xampp\htdocs...')
#4 [internal function]: {closure}()
#5 C:\xampp\htdocs\CC\Slim\Route.php(392): call_user_func_array(Object(Closure), Array)
#6 C:\xampp\htdocs\CC\Slim\Slim.php(1051): Slim_Route->dispatch()
#7 C:\xampp\htdocs\CC\testingnew.php(771): Slim->run()
#8 {main}

please suggest me what should i do to remove this error. in any doubt then feel free to ask me. I really need your help.
Thank you in advance.

A: It looks like you're having some sort of reference assignment, this is deprecated in PHP5.
You can't use:
$foo =& new MyClass();

Please provide some more code so we can see what's wrong.


text:
Q: Как обработать исключение java.util.ConcurrentModificationException? Есть код: ссылка на github. В ходе выполнения выбрасывается исключение Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
Знающие люди подскажите как побороть проблему. Заранее спасибо)

A: Например, можно поставить блокировку перед началом модификации ArrayList и снять блокировку после завершения модификации. Используете неконкурентную структуру данных ArrayList. Такая сруктура данных будет корректно работать если поток один.
    while (i.hasNext()) {
        synchronized (i) {
            Enemy e = i.next();
            if (e.x >= 1600 || e.x <= -1600) {
                i.remove();
            } else {
                e.move(); // поправить позже
                g.drawImage(e.img, e.x, e.y, null);
            }
        }
    }

В этом коде блокировка снимается позже завершения модификации. Можно код переписать так:
    while (i.hasNext()) {
        boolean isDrawImage = false;
        synchronized (i) {
            Enemy e = i.next();
            if (e.x >= 1600 || e.x <= -1600) {
                i.remove();
            } else {
                e.move(); // поправить позже
                isDrawImage = true;
            }
        }
        if (isDrawImage)
           g.drawImage(e.img, e.x, e.y, null);
    }

A: Его не надо обрабатывать. Это исключение значит, что вы в своем коде удаляете элемент напрямую из коллекции во время использования итератора. Т.к. в этом случае появляется неопределенность, откуда итератор должен продолжать и какие последующие элементы должен пройти, выбрасываетс исключение. Для корректного изменения сущности используйте методы итератора, например, iterator.remove().

A: В дополнение к ответу etki привожу код для корректного удаления элемента коллекции внутри цикла итератора:
Iterator<String> i = strings.iterator();
while (i.hasNext()) {
    String value = i.next(); // должен быть вызван перед тем, как вызывается i.remove()
    // какой-то код
    i.remove(); // Элемент value был удалён из коллекции strings
}


text:
Q: DateTimes.toUtc() not working as expected void main() {
  var foo = DateTime(2000).toUtc();
  var bar = DateTime.utc(2000);

  assert (foo != bar);
}

foo and bar should be equal but they aren't, can anyone tell me what am I doing wrong with toUtc(). As far as I know DateTime(2000) returns the DateTime in local time zone and toUtc() converts that to UTC, but it doesn't do that.

A: Thanks to someone who deleted the answer after posting this link. And thanks to @lrn for answering it:

DateTime(y, m, d).toUtc() finds the y-m-d time in the local time-zone and then creates a UTC date at the same point in time. So, if I'm in the UTC+2 time zone, and I do DateTime(2019, 04, 02).toUtc(), I start with the local time 2019-04-02T00:00:00+02:00, and then find that the corresponding UTC-time is 2019-04-01T22:00:00Z. That's the same point in time in a different time zone, it answers the question "when the local time is 2019-04-02T00:00:00, what is the time in the UTC time zone".

When you do DateTime.utc(2019, 04, 02), you get the point in time where the UTC clock showed 2019-04-02T00:00:00Z. If I do toLocal() on that, I'd get the local time 2019-04-02T02:00:00+02:00.


text:
Q: How to select faulty records? I'm investigating an error in one of our tables of a geographical database. Given the table below, the DistrictName and DisId should always have the same combination (i.e. Bronx = 11, Manhatten = 14), but some records have a different DisId (while still sharing the the same DistrictName).
  Id    DistrictName    DisId   Section
  ------------------------------------------------
  1     Bronx           11      1
  2     Bronx           11      2
  3     Brooklyn        12      1
  4     Brooklyn        13      2   //wrong
  5     Manhatten       14      1
  6     Manhatten       14      2
  7     Queens          15      1
  8     Queens          16      2   //wrong
  9     Queens          17      3   //wrong

How can I select all faulty records in a query?
There is always a Section 1, so records with a section > 1 containing the same DistrictName but having a deviating DisId are the ones I'm looking for.
I've tried using a group by (districtname) but I'm having difficulties comparing with the section1 record. I'm kind of lost when it comes to putting the logic in the having or where clause. Any help appreciated!

A: select * from your_table
where section > 1
and districtname in
(
  select districtname
  from your_table
  group by districtname
  having count(distinct disid) > 1
)


text:
Q: Application closed in Zariski topology Consider the integral homomorphism $f: A \rightarrow  B$.
How do I prove that the map $f^*:Spec(B) \rightarrow Spec(A)$ given by $f^*(Q) = f^{-1}(Q)$ is a closed application.
Note:
1) I believe we need to show that $f^*(V(I)) = V(f^{-1}(I))$. I have already shown that $f^*(V(I))$ is contained in $V(f^{-1}(I))$ but I can not show the other inclusion.
2) $f^{-1}$ is the inverse image of $f$.
3) $I$ is any ideal of the ring $B$.

A: The massive hint that you need to solve your problem is the following result

Theorem 5.10 Atiyah - Macdonald:
    Let $f : A \to B$ be an integral morphism. For every prime ideal $\mathfrak{p} \subseteq A$ there is a prime ideal $\mathfrak{q} \subseteq B$ such that $A \cap \mathfrak{q} = \mathfrak{p}$.


text:
Q: How to use MPMedaPickerController on swift 3? I'm simply trying to get it so that when you press a button, you display the user's music library, and then you can select a song. I've found that the way to do this is through MPMediaPickerController but I've been struggling to get it to work. This is what my program looks like so far:
import MediaPlayer
import UIKit

class ViewController: UIViewController, MPMediaPickerControllerDelegate {
 var mediaPicker: MPMediaPickerController?

override func viewDidLoad() {
     super.viewDidLoad()

}

@IBAction func showSongs(_ sender: Any) {
    displayMediaPicker()
}
func displayMediaPicker() {
    mediaPicker = MPMediaPickerController(mediaTypes: .music)
    if let picker = mediaPicker {
        picker.delegate = self
        picker.allowsPickingMultipleItems = false
        picker.showsCloudItems = false
        picker.prompt = "Please Pick a Song"
        view.addSubview(picker.view)
        }
}

}

I know that there should be a property [self presentViewController:picker animated: true completion:nil] after view.addSubview(picker.view), but when I type it I have the options presentingViewController & presentedViewContoller, but no presentViewController
Any help would be much appreciated

A: The function presentViewController: animated: completion: function was renamed in Swift 3 so now it looks like this:
present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)
So, in your case you'd end up with a presentPicker function looking something like this (notice the last line):
func presentPicker() {
    mediaPicker = MPMediaPickerController(mediaTypes: .music)
    if let picker = mediaPicker {
        picker.delegate = self
        picker.allowsPickingMultipleItems = false
        picker.showsCloudItems = false
        picker.prompt = "Please Pick a Song"
        present(picker, animated: false, completion: nil)
    }
}

Hope that helps you.

A: Swift 5, Swift 4 Very simple solution
//MARK:- add it in your info.plist file
<key>NSAppleMusicUsageDescription</key>
<string>$(app Name) uses music</string>

//MARK:- Import in your file
import MediaPlayer

//MARK:- Import as your Delegates
MPMediaPickerControllerDelegate

//MARK:- Just call this function
func openAudio()
{
    let audiopicker = MPMediaPickerController(mediaTypes: .anyAudio)
    audiopicker.prompt = "Audio"
    audiopicker.delegate = self
    audiopicker.allowsPickingMultipleItems = false
    self.present(audiopicker, animated: true, completion: nil)
}


text:
Q: Double free error in my struct code I'm trying to write a struct that deletes certain nodes in a list, the delete function works correctly, but I get a double free error.
I can't figure out which free is giving me the problem. I'd appreciate any help
struct dog* delete_from_list(struct dog *dogs)
{
    int number2 = 0;

    struct dog *temp, *cur = dogs;

    if (dogs==NULL)
    {
        printf("There are no dogs on the list \n");
        return 0;
    }

    printf("Enter patient number to delete: \n");
    scanf("%d", &number2);

    if (dogs->number==number2)
    {
        if(dogs->next==NULL) //only one node in the list
        {
            free(dogs);
            return NULL;
        }
        dogs = dogs->next; //moves the head to next node
        free(cur);
        return dogs;
    }
    else
    {
        while (cur->next != NULL && cur->next->number != number2)
        {
            cur = cur->next;
        }

        if(cur->next==NULL)
        {
            printf("Dog with number %d is not present \n", number2);
            return dogs;
        }

        temp = cur->next;
        cur->next = cur->next->next;
        free(temp);
        return dogs;
    }
}

A: To avoid double free error, try this:

*

*Right after freeing a pointer, set it to NULL

*Right before freeing a pointer, check if it is NULL

I would try to remove the amount of special casing, for example
typedef struct dog Node;

Node * delete_from_list(Node * head) {
  const int key_to_delete = GetKeyToDelete();
  if (!head) return NULL;
  for (Node * cur = head; cur; ) {
    if (cur->key = key_to_delete) {
      Node * curnext = cur->next;
      free(cur);
      cur = curnext;
    }
    else {
      break;
    }
  }
  Node * new_head = cur;
  for (Node * cur = new_head; cur; cur = cur->next) {
    if (cur->next && (cur->next->key == key_to_delete)) {
      Node * curnextnext = cur->next->next;
      free(cur->next);
      cur->next = curnextnext;
    }
  }
  return new_head;
}


text:
Q: API no longer connecting Project: I'm building a restful API that's taking data from one API and using another API to translate part of that data, the description, into some other lexicon.
Problem: All was working fine until a few days back I stopped getting connection with the translation API. I've changed nothing in the code relating to the request. I can also replicate the problem when I use VCS to go back to earlier versions of my code. I've tried this in two different environments but I encounter the same issue. I've also tried my web browser and POSTMAN but they seem to be getting the appropriate responses.
I'm a receiving a HTTP code of 200 when I when running a test file but not getting the response I want from the translation API.
Code explanation: So I'm taking some nested information, flavor_text_entries from my first API (data) and using that as my description, setting that as a variable and sending it to my translation API to translate and return only the translation of the description.
def extract_descriptive_text(json_blob, language='en', version='sword'):
    text = ""
    for f in json_blob['flavor_text_entries']:
        if f['language']['name'] == language and f['version']['name'] == version:
            text = f['flavor_text']
    return text

def extract_useful_info(translated):
    text = []
    wanted_info = translated['contents']['translated']
    text.append(wanted_info)
    return text

@app.route('/pokemon/<string:name>/', methods=['GET'])
def get_translation(name):
    descrip_url = f"https://pokeapi.co/api/v2/pokemon-species/{name}"
    r = requests.get(descrip_url)
    json_blob = r.json()
    text_trans = extract_descriptive_text(json_blob)
    trans_url = f"https://api.funtranslations.com/translate/shakespeare.json?text={text_trans}"
    shakespeare = requests.get(trans_url)
    translated = shakespeare.json()
    useful_info = extract_useful_info(translated)
    return jsonify({'name': name, 'description': useful_info})

if __name__ == '__main__':
    app.run(debug=True)

Error I get when I try to return everything from translation API:
ERROR:
{
  "name": "charizard",
  "description": {
    "error": {
      "code": 404,
      "message": "Not Found"
    }
  }
}

Traceback I receive when I try return just the translation:
Traceback (most recent call last):
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/swapneel/Desktop/projects/foobar/main.py", line 58, in get_translation
    useful_info = extract_useful_info(translated)
  File "/Users/swapneel/Desktop/projects/foobar/main.py", line 21, in extract_useful_info
    wanted_info = translated['contents']['translated']
KeyError: 'contents'

Libraries and Packages used:
from flask import Flask, jsonify
from flask_restful import Api
import requests

Any help would be massively appreciated!

A: The translation API can't find the search term charizard and is returning a different JSON then the one you are expecting and are able to handle.
In extract_useful_info() you are retrieving translated['contents'] but as you can see in the API response you are getting that key is not present when there's an API error. Instead, the response contains 'name' and 'description'.
You'll need to implement a check for when the API errors out. You can do that by e.g. wrapping wanted_info in a try/except:
def extract_useful_info(translated):
    text = []
    try:
        wanted_info = translated['contents']['translated']
    except KeyError:
        wanted_info = ''

    text.append(wanted_info)
    return text

As a side note: I can't see why text needs to be a list. The code becomes much simpler if it's just a string i.e.
def extract_useful_info(translated):
    try:
        return translated['contents']['translated']
    except KeyError:
        return '' # return None is better but I don't know if your app can handle that.

If that's the case, though, we we can get rid of extract_useful_info() altogether and do
...
try:
    useful_info = shakespeare.json()['contents']['translated']
except KeyError:
    useful_info = '' # or return None
...


text:
Q: How do I scale up button when trigger isMouseOver is true I just started learning xaml so I barely have any knowledge of it yet.
I was trying to make the button scale up to 1.2 when the user Overs on the button but I can't find anywhere how to do it
Bellow is the xaml code if it is of any use,
<Window.Resources>

    <SolidColorBrush x:Key="Button.Static.Background" Color="#FF124D91"/>
    <SolidColorBrush x:Key="Button.Static.Border" Color="Transparent"/>
    <SolidColorBrush x:Key="Button.Static.Foreground" Color="White"/>
    <SolidColorBrush x:Key="Button.MouseOver.Background" Color="Transparent"/>
    <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF124D91"/>
    <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
    <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF124D91"/>
    <SolidColorBrush x:Key="Button.Disabled.Background" Color="Transparent"/>
    <SolidColorBrush x:Key="Button.Disabled.Border" Color="Transparent"/>
    <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="Transparent"/>
    <Style x:Key="ButtonPressStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource Button.Static.Foreground}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="true" CornerRadius="8">
                        <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsDefaulted" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            <Setter Property="Foreground" Value="Black"/>
                            <Setter Property="BorderThickness" Value="1.5"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</Window.Resources>

Button:
<Button x:Name="ButtonPress" Style="{DynamicResource ButtonPressStyle}" Margin="133,0,133,15" Content="Press" Height="50" VerticalAlignment="Bottom" Click="ButtonPress_Click"/>

Also if theres any way to do this in C# too please teach me how to do it,
Appreciate any help.

A: add this to your trigger property
<Setter Property="RenderTransformOrigin" Value="0.5, 0.5"/>
<Setter Property="RenderTransform">
     <Setter.Value>
           <ScaleTransform ScaleX="1.2" ScaleY="1.2"/>
     </Setter.Value>
</Setter>

final code
<Trigger Property="IsMouseOver" Value="true">
     <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
     <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
     <Setter Property="Foreground" Value="Black"/>
     <Setter Property="BorderThickness" Value="1.5"/>
     <Setter Property="RenderTransformOrigin" Value="0.5, 0.5"/>
     <Setter Property="RenderTransform">
         <Setter.Value>
               <ScaleTransform ScaleX="1.2" ScaleY="1.2"/>
         </Setter.Value>
      </Setter>
</Trigger>


text:
Q: Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction ASP.NET MVC project 4.5 and EntityFramework Database First.
I have some command, which will be triggered when the user clicks a button
using (TransactionScope scope = new TransactionScope())
{
    using (DbContext context = new DbContext())
    {
      //update about 3 tables
      scope.Complete();
    }
}

In the other hand, I have another method which ONLY read (not updating anything) data from one of the previous tables, but it's working every 2 seconds (there is a timer which triggers this read process).
Problem: sometimes (not always) I am receiving the following exception from the reading process (not the updating process).

System.Data.SqlClient.SqlException: Transaction (Process ID 57) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

although the update process is working correctly and success and although the read process fails (sometimes not always), which is not a big deal because It will be requested again after 2 seconds and success at that time.
I am afraid that I am not doing it the correct way, Is there any advice to get rid of this exception completely?
NOTE: I was not receiving this exception before, I started to receive this exception when I started to use the TransactionScope.
Update (Possible Solution)
Actually, I tried to play with the IsolationLevel as suggested in the comments, Actually, this caused a great reduction in this exception.
I created the Transaction like the following
new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions()
        {
            IsolationLevel = IsolationLevel.RepeatableRead
        })

NOTE: the level SnapShot did not work because the database does not support this level.
Update here is the Deadlock profile


text:
Q: How to parallelize for-loop in bash limiting number of processes I have a bash script similar to:
NUM_PROCS=$1
NUM_ITERS=$2

for ((i=0; i<$NUM_ITERS; i++)); do
    python foo.py $i arg2 &
done

What's the most straightforward way to limit the number of parallel processes to NUM_PROCS? I'm looking for a solution that doesn't require packages/installations/modules (like GNU Parallel) if possible.
When I tried Charles Duffy's latest approach, I got the following error from bash -x:
+ python run.py args 1
+ python run.py ... 3
+ python run.py ... 4
+ python run.py ... 2
+ read -r line
+ python run.py ... 1
+ read -r line
+ python run.py ... 4
+ read -r line
+ python run.py ... 2
+ read -r line
+ python run.py ... 3
+ read -r line
+ python run.py ... 0
+ read -r line

... continuing with other numbers between 0 and 5, until too many processes were started for the system to handle and the bash script was shut down.

A: As a very simple implementation, depending on a version of bash new enough to have wait -n (to wait until only the next job exits, as opposed to waiting for all jobs):
#!/bin/bash
#      ^^^^ - NOT /bin/sh!

num_procs=$1
num_iters=$2

declare -A pids=( )

for ((i=0; i<num_iters; i++)); do
  while (( ${#pids[@]} >= num_procs )); do
    wait -n
    for pid in "${!pids[@]}"; do
      kill -0 "$pid" &>/dev/null || unset "pids[$pid]"
    done
  done
  python foo.py "$i" arg2 & pids["$!"]=1
done

If running on a shell without wait -n, one can (very inefficiently) replace it with a command such as sleep 0.2, to poll every 1/5th of a second.

Since you're actually reading input from a file, another approach is to start N subprocesses, each of processes only lines where (linenum % N == threadnum):
num_procs=$1
infile=$2
for ((i=0; i<num_procs; i++)); do
  (
    while read -r line; do
      echo "Thread $i: processing $line"
    done < <(awk -v num_procs="$num_procs" -v i="$i" \
                 'NR % num_procs == i { print }' <"$infile")
  ) &
done
wait # wait for all the $num_procs subprocesses to finish

A: A relatively simple way to accomplish this with only two additional lines of code.  Explanation is inline.
NUM_PROCS=$1
NUM_ITERS=$2

for ((i=0; i<$NUM_ITERS; i++)); do
    python foo.py $i arg2 &
    let 'i>=NUM_PROCS' && wait -n # wait for one process at a time once we've spawned $NUM_PROC workers
done
wait # wait for all remaining workers

A: Are you aware that if you are allowed to write and run your own scripts, then you can also use GNU Parallel? In essence it is a Perl script in one single file.
From the README:

= Minimal installation =
If you just need parallel and do not have 'make' installed (maybe the
  system is old or Microsoft Windows):
wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel
cp parallel sem
mv parallel sem dir-in-your-$PATH/bin/

seq $2 | parallel -j$1 python foo.py {} arg2

parallel --embed (available since 20180322) even makes it possible to distribute GNU Parallel as part of a shell script (i.e. no extra files needed):
parallel --embed >newscript

Then edit the end of newscript.

A: bash 4.4 will have an interesting new type of parameter expansion that simplifies Charles Duffy's answer.
#!/bin/bash

num_procs=$1
num_iters=$2
num_jobs="\j"  # The prompt escape for number of jobs currently running
for ((i=0; i<num_iters; i++)); do
  while (( ${num_jobs@P} >= num_procs )); do
    wait -n
  done
  python foo.py "$i" arg2 &
done

A: GNU, macOS/OSX, FreeBSD and NetBSD can all do this with xargs -P, no bash versions or package installs required. Here's 4 processes at a time:
printf "%s\0" {1..10} | xargs -0 -I @ -P 4 python foo.py @ arg2

A: This isn't the simplest solution, but if your version of bash doesn't have "wait -n" and you don't want to use other programs like parallel, awk etc, here is a solution using while and for loops.
num_iters=10
total_threads=4
iter=1
while [[ "$iter" -lt "$num_iters" ]]; do
    iters_remainder=$(echo "(${num_iters}-${iter})+1" | bc)
    if [[ "$iters_remainder" -lt "$total_threads" ]]; then
        threads=$iters_remainder
    else
        threads=$total_threads
    fi
    for ((t=1; t<="$threads"; t++)); do
        (
            # do stuff
        ) &
        ((++iter))
    done
    wait
done


text:
Q: ruamel.yaml equivalent of sort_keys? I'm trying to dump a Python dict to a YAML file using ruamel.yaml. I'm familiar with the json module's interface, where pretty-printing a dict is as simple as
import json
with open('outfile.json', 'w') as f:
    json.dump(mydict, f, indent=4, sort_keys=True)

With ruamel.yaml, I've gotten as far as
import ruamel.yaml
with open('outfile.yaml', 'w') as f:
    ruamel.yaml.round_trip_dump(mydict, f, indent=2)

but it doesn't seem to support the sort_keys option. ruamel.yaml also doesn't seem to have any exhaustive docs, and searching Google for "ruamel.yaml sort" or "ruamel.yaml alphabetize" didn't turn up anything at the level of simplicity I'd expect.
Is there a one-or-two-liner for pretty-printing a YAML file with sorted keys?
(Note that I need the keys to be alphabetized down through the whole container, recursively; just alphabetizing the top level is not good enough.)

Notice that if I use round_trip_dump, the keys are not sorted; and if I use safe_dump, the output is not "YAML-style" (or more importantly "Kubernetes-style") YAML. I don't want [] or {} in my output.
$ pip freeze | grep yaml
ruamel.yaml==0.12.5

$ python
>>> import ruamel.yaml
>>> mydict = {'a':1, 'b':[2,3,4], 'c':{'a':1,'b':2}}
>>> print ruamel.yaml.round_trip_dump(mydict)  # right format, wrong sorting
a: 1
c:
  a: 1
  b: 2
b:
- 2
- 3
- 4

>>> print ruamel.yaml.safe_dump(mydict)  # wrong format, right sorting
a: 1
b: [2, 3, 4]
c: {a: 1, b: 2}

A: You need some recursive function that handles mappings/dicts, sequence/list:
import sys
import ruamel.yaml

CM = ruamel.yaml.comments.CommentedMap

yaml = ruamel.yaml.YAML()

data = dict(a=1, c=dict(b=2, a=1), b=[2, dict(e=6, d=5), 4])
yaml.dump(data, sys.stdout)

def rec_sort(d):
    try:
        if isinstance(d, CM):
            return d.sort()
    except AttributeError:
        pass
    if isinstance(d, dict):
        # could use dict in newer python versions
        res = ruamel.yaml.CommentedMap()
        for k in sorted(d.keys()):
            res[k] = rec_sort(d[k])
        return res
    if isinstance(d, list):
        for idx, elem in enumerate(d):
            d[idx] = rec_sort(elem)
    return d

print('---')

yaml.dump(rec_sort(data), sys.stdout)

which gives:
a: 1
c:
  b: 2
  a: 1
b:
- 2
- e: 6
  d: 5
- 4
---
a: 1
b:
- 2
- d: 5
  e: 6
- 4
c:
  a: 1
  b: 2

The commented map is the structure ruamel.yaml uses when doing a
round-trip (load+dump) and round-tripping is designed to keep the keys in
the order that they were during loading.
The above should do a reasonable job preserving comments on mappings/sequences when you load data from a commented YAML file

A: There is an undocumented sort() in ruamel.yaml that will work on a variation of this problem:
import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()

test = """- name: a11
  value: 11
- name: a2
  value: 2
- name: a21
  value: 21
- name: a3
  value: 3
- name: a1
  value: 1"""
test_yml = yaml.load(test)

yaml.dump(test_yml, sys.stdout)

not sorted output
  - name: a11
    value: 11
  - name: a2
    value: 2
  - name: a21
    value: 21
  - name: a3
    value: 3
  - name: a1
    value: 1

sort by name
test_yml.sort(lambda x: x['name'])
yaml.dump(test_yml, sys.stdout)

sorted output
  - name: a1
    value: 1
  - name: a11
    value: 11
  - name: a2
    value: 2
  - name: a21
    value: 21
  - name: a3
    value: 3

A: As pointed out in @Anthon's example, if you are using Python 3.7 or newer (and do not need to support lower versions), you just need:
import sys
from ruamel.yaml import YAML

yaml = YAML()

data = dict(a=1, c=dict(b=2, a=1), b=[2, dict(e=6, d=5), 4])

def rec_sort(d):
    if isinstance(d, dict):
        res = dict()
        for k in sorted(d.keys()):
            res[k] = rec_sort(d[k])
        return res
    if isinstance(d, list):
        for idx, elem in enumerate(d):
            d[idx] = rec_sort(elem)
    return d

yaml.dump(rec_sort(data), sys.stdout)

Since dict is ordered as of that version.


text:
Q: Typescript dist error "Cannot find module" I'm trying to run my typescript application directly from the server.js folder compiled in the dist folder, and I can even create the folder and forward the directory, but I get an error when I try to run the application
package.json
{
  "dependencies": {
    "@types/bcryptjs": "^2.4.2",
    "@types/body-parser": "^1.19.2",
    "@types/cors": "^2.8.12",
    "@types/express": "^4.17.13",
    "@types/node": "^18.6.3",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "nodemon": "^2.0.19",
    "pg": "^8.7.3",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "ts-node": "^10.9.1",
    "typeorm": "^0.3.7",
    "typescript": "^4.7.4"
  },
  "name": "api_authentication",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "build": "rimraf dist && tsc",
    "start": "npm run build && nodemon dist/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "description": ""
}

tsconfig.json
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "ES6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "ES6",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    "strictPropertyInitialization": false,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true,
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

When trying to give the command 'npm start', the console returns me the error
Error: Cannot find module 'C:\Users\mypc\OneDrive\Documents\api_authentication\index.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',


text:
Q: Capacity Provisioning for Server Farms Markov Chain Queues Suppose we are using an M/M/N model, how many servers would we need to keep the probability of an arriving job to wait to be less than 0.2. Given that jobs arrive at a rate of 400/second, and the processing times are exponentially distributed with a mean of 1 second.
So I used Erlang's C-formula:
P[queueing] = (1/c!)*(lambda/mu)^(c)*(1/(1-rho))*pi_o

And got an answer of 4 servers, however when I used the model they showed in the textbook:
rho < 1 -> (lambda)/(k*mu) -> k > lambda/mu

I get k = 400 servers. I'm not sure.


text:
Q: I cannot build the application in VS code, when i am trying to connect the app with firebase. Following is the error i get when i start running it I have followed the steps for adding dependency accordingly.
ProcessException: Process "F:\firebase_demo\android\gradlew.bat" exited abnormally:
FAILURE: Build failed with an exception.

* Where:
Build file 'F:\firebase_demo\android\app\build.gradle' line: 24

* What went wrong:
A problem occurred evaluating project ':app'.
> ASCII

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with
--scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
  Command: F:\firebase_demo\android\gradlew.bat app:properties

Please review your Gradle project setup in the android/ folder.

#-------------------------Here is the change i brought to build gradle

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
}

apply plugin: 'com.google.gms.google-services'

A: I've had a very similar problem with "ASCII". Turns out I had put my google firebase files in the wrong folder. Double check the position?
In Android Studio it is: android/app/google-services.json


text:
Q: Dynamically showing a control in JQuery Mobile I am trying to add some dynamic content to the bottom of my JQuery mobile page. The content is populated by a JavaScript file. A user navigates to this page by clicking a link on another page. When they click that link they are shown the page that is defined below. Oddly, the dynamic content does NOT show when the user arrives by the navigating from the previous page. However, if I refresh the page, the content appears. Alternatively, if I navigate to the page directly via the url, the content appears. In all three situations, no JavaScript errors are reported in the console. What am I doing wrong?
Page.html

Testing

      Add

No Results

Tab 1

Tab 2

Tab 3

A: Put your js that adds the content in the head of your document. Then add you dynamic content on pageinit. JQM is pulling that content into the same dom as page1 and I believe is ignoring your external script.

<link ....


text:
Q: Invoke a Perl script from Powershell and stores the script output in a variable Could someone try to help me out to run a Perl program from a PowerShell script? I'm trying to save the script results into a PowerShell variable.
So far, I have tried the below from the Powershell ISE. But it does not seem to be working.
perl 'C:\Program Files (x86)\ABC\ABC Software\bin\testcheck.pl -print verbose'

Powershell Script Path: C:\MyScripts
Perl Program Dir: C:\Program Files (x86)\ABC\ABC Software\perl\bin\perl.exe


text:
Q: SyntaxError: Expecting Unicode escape sequence \uXXXX This bug had been bugging us on our nextjs project(doesn't allow the project to completely compile). This seem to relate with babel-plugin-preval and tailwindcss configuration
// Snippet of tailwind config extraction
import tailwindConfig from /* preval */ '../tailwind.config';

export const extractedTailwindConfig = tailwindConfig;
export const extractedTailwindTheme = extractedTailwindConfig.theme;

Photo of error:

I'm currently utilizing windows and it seem to flag out the macOS' /r. Removing all the new line and sticking everything together seem to fix it.


text:
Q: Z3 converting "small" BitVectors to Ints I know that both bv2int and int2bv are handled as uninterpreted functions in Z3. Still, I am looking for a best practice in solving the following problem: given a "small" (< 10 bits) bitvector index,
how to efficiently cast it to Int, and use in queries like this one:
(declare-const s String)
(declare-const someInt                Int)
(declare-const someBitVec10 (_ BitVec 10))

(assert (= s "74g\x00!!#2#$$"))

;(assert (str.in.re (str.at s someBitVec10) (re.range "a" "z")))
( assert (str.in.re (str.at s someInt     ) (re.range "1" "3")))

(check-sat)
(get-value (s someInt))

Output:
sat
((s "74g\x00!!#2#$$")
 (someInt 7))

Thanks!


text:
Q: Making Javascript Simple Slideshow I'm trying to create a simpke slideshow but it seem not working correctly, anyone know what i did wrong??
Here is my code:

var img = document.getElementsByTagName('img');
index = 0;
for (j = 0; j < img.length; j++) {
  img[j].style.display = 'none';
}

function slider() {
  if (index < img.length) {
    img[index - 1].style.display = 'none';
    img[index].style.display = 'block';
    index++;
  } else {
    img[index - 1].style.display = 'none';
    img[index].style.display = 'block';
    index = 0;
  }
}
slider();
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

  <button class="w3-button w3-black w3-display-left" onclick="slider()">❮</button>
  <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">❯</button>

Thanks in advance

A: Please try this code.
I have implemented slider and plusDivs function. I hope this output is your expected result.
html:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

  <button class="w3-button w3-black w3-display-left" onclick="slider()">❮</button>
  <button class="w3-button w3-black w3-display-right" onclick="plusDivs()">❯</button>

js:
var img = document.getElementsByTagName('img');
index = 0;
for (j = 1; j < img.length; j++) {
  img[j].style.display = 'none';
}

function slider() {
  img[index].style.display = 'none';

  index--;
  if (index < 0) {
    index = img.length - 1;
  }
  img[index].style.display = 'block';
}

function plusDivs() {
  img[index].style.display = 'none';

  index++;
  if (index > img.length - 1) {
    index = 0
  }
  img[index].style.display = 'block';
}

JSFiddle: https://jsfiddle.net/kuromoka/hn4wm1be/


text:
Q: Include external files for modular tests I have a scenario where I would like to test many different sites using one base Test Plan. All of those sites makes roughly the same calls (a shopping scenario), but some sites makes additional calls.
To make it simple, let's say I have two sites to test, site A and site B. Each test site has a test folder containing their custom external plans. Right now I have a "base" Test Plan, let's call it TP, and one external file, let's call that EP (External Plan) only in site A. In site B I have no external files (because it does not have any additional calls).
I tried calling the EP for site A, using an Include Controller, from TP and that works fine, but when I run TP against site B the external file (EP) does not exist and the test will not even start.
The problem is that JMeter only runs when the external file actually exist on the path (you can not even start the test if Include Controller is not passed a valid file.
My goal is to make this scenario module in a way that you add an external file to each site's test-folder for each "special call" that is made. If the site in question has no "special calls", no external file should be added. If we add a new site, we should not have to add external files to all other sites!
For example, having an option for Include Controller like ignore missing file would help immensely, but alas there is no such option.
How can I make my scenario modular with JMeter?


text:
Q: How to recover data from old encrypted hard drive? I am trying to work out how to recover the data from the hard drive that was in my old laptop. It was running the latest ubuntu and I am now running Ubuntu satanic 11.04 as i do not like 11.10. Uhe drive was encrypted and I have it now in an external usb drive enclosure.
I have tried chown and advanced chown and still it is not showing me the contents of the home folder. I am starting to be at a loss what to do as there is quite a large amount of data on there that is pretty important to me.
The old OS is pretty irrelevant and I will be using the drive for a backup once I can get the data recovered. It was the graphics that died on the old laptop.

A: If you don't have the key that is given after the creation of the encrypted volume there would be no way to restore the data. Otherwise the encryption would fail to fulfill it's purpose.
However...if you somehow still have access to the previous installation that used the encrypted volume you would be able to extract the needed key.
Edit #1:
Here is how you can retrieve the passphrase of a encrypted homedrive.
Step 1: Switch to the metadata directory of encryptfs
If your encrypted folder is ~/Private

$>sudo cd /home/&ltusername&gt/.ecryptfs

If that fails (i.e. directory does not exist) try the following directory that is used when you chose to encrypt the complete home directory.

$>sudo cd /home/.ecryptfs/&ltusername&gt/.ecryptfs

Step 2: unwrap the passphrase (it is encrypted with your user account password)

$>sudo ecryptfs-unwrap-passphrase wrapped-passphrase
passphrase: &ltuser password&gt

You now have the passphrase that was used to encrypt your data.
Conclusion
If you can find the .ecryptfs folder on your old volume you would be able extract the old ecryptfs passphrase from the metadata using the old users password.


text: Q: Mathematica 13 not Working with Windows 11 Pro (bug) Erratic behavior in Mathematica 13 on Windows 11 Pro. I have two issues that come and go. (1) Sometimes, the equation controlling the manipulate in my notebooks corrupts. The slider bars are not able to move the line describing my equation to the correct locations. Sometimes the line describing the graph of my equation disappears completely. (2) Sometimes, when I table a function. Next, 'shift enter' on the tabled equation I get erratic results with the variables in the equation set to the same values from one shift enter to the next. This problem often erupts when I move a decimal place in the equation with 'Set Precision' set to 3 significant figures. (Don't forget, very few Mathematica people are running Windows 11 Pro, Windows 11 Pro is not popular yet)


text:
Q: After Response.redirect Onselectedindexchanged keeps firing I have a web form I am building to bring up reports from Srss using response.redirect().  After this though whenever another postback happens the same onselectedindexchanged events keep firing.  Is there something that needs to happen to clear the event?
For example, when the ddlBlankForms index changes, the event fires and the response.redirect makes the file download.  But the drop down list does not return to index 0 like the code suggests.  And now after any more events like for example one of the other drop down lists, the ddlBlankForms_OnSelectedIndexChanged keeps trying to fire.  If I remove the response.redirect it seems to work but it defeats the purpose which is to open the file.
Code Behind.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        ddlBusinessUnit.DataSource = sqlCommands.GetBusinessUnits();
        ddlBusinessUnit.DataValueField = "BusinessUnit";
        ddlBusinessUnit.DataBind();
        ddlBusinessUnit.Items.Insert(0, new ListItem("", ""));

        ddlBlankForms.DataSource = sqlCommands.GetForms();
        ddlBlankForms.DataTextField = "FormDesc";
        ddlBlankForms.DataValueField = "FormReport";
        ddlBlankForms.DataBind();
        ddlBlankForms.Items.Insert(0, new ListItem("", ""));
    }
}

protected void Page_Init(object sender, EventArgs e)
{
    //ddlBusinessUnit.DataSource = sqlCommands.GetBusinessUnits();
    //ddlBusinessUnit.DataValueField = "BusinessUnit";
    //ddlBusinessUnit.DataBind();
    //ddlBusinessUnit.Items.Insert(0, new ListItem("", ""));

    //ddlBlankForms.DataSource = sqlCommands.GetForms();
    //ddlBlankForms.DataTextField = "FormDesc";
    //ddlBlankForms.DataValueField = "FormReport";
    //ddlBlankForms.DataBind();
    //ddlBlankForms.Items.Insert(0, new ListItem("", ""));
}

protected void ddlBusinessUnit_OnSelectedIndexChanged(object sender, EventArgs e)
{
    ddlType.DataSource = sqlCommands.GetTypes(ddlBusinessUnit.SelectedValue);
    ddlType.DataValueField = "FormID";
    ddlType.DataTextField = "TypeDesc";
    ddlType.DataBind();
    ddlType.Items.Insert(0, new ListItem("", ""));
}

protected void ddlType_OnSelectedIndexChanged(object sender, EventArgs e)
{
    ddlTask.DataSource = sqlCommands.GetTasks(ddlType.SelectedValue, ddlBusinessUnit.SelectedValue);
    ddlTask.DataValueField = "TaskID";
    ddlTask.DataBind();
    ddlTask.Items.Insert(0, new ListItem("", ""));
}

protected void ddlTask_OnSelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlTask.SelectedIndex == 0) return;
    string url = "http://reportserver";
    url += sqlCommands.GetSpecificFormReportName(ddlType.SelectedValue);
    url += "&BU=" + ddlBusinessUnit.SelectedValue;
    url += "&TID=" + ddlTask.SelectedValue;
    url += "&rs:Format=PDF";
    Response.Redirect(url);

    //Response.Redirect("http://mje-imtmisql03/reportserver?/QAQC_Reports/QCBore&BU=251Template&TID=Required1&rs:Format=PDF");
}

protected void ddlBlankForms_OnSelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlBlankForms.SelectedIndex == 0) return;
    string url = "http://reportserver";
    url += ddlBlankForms.SelectedValue;
    url += "&BU=";
    url += "&TID=";
    url += "&rs:Format=PDF";
    ddlBlankForms.SelectedIndex = 0;
    Response.Redirect(url);
    //Response.End();
}

ASP.
<asp:DropDownList runat="server" ID="ddlBlankForms" OnSelectedIndexChanged="ddlBlankForms_OnSelectedIndexChanged" AutoPostBack="True" Width="300px"/>
<asp:DropDownList runat="server" ID="ddlTask" OnSelectedIndexChanged="ddlTask_OnSelectedIndexChanged" AutoPostBack="true" EnableViewState="True" Width="200px"/>
<asp:DropDownList runat="server" ID="ddlType" OnSelectedIndexChanged="ddlType_OnSelectedIndexChanged" AutoPostBack="True" EnableViewState="True" Width="200px"/>
<asp:DropDownList runat="server" OnSelectedIndexChanged="ddlBusinessUnit_OnSelectedIndexChanged" AutoPostBack="True" EnableViewState="true" ID="ddlBusinessUnit" Width="200px"/>

A: I suggest you to use the Page_Load event :When this event fires, the page and its controls are fully initialized, and their previous values are restored. Use also the IsPostBack property aslo.
But for the Page_Init event:The framework uses this event to set the properties of web controls to their previous values via postback or view state data.
So you can try this:
    protected void Page_Load(object sender, EventArgs e)
    {

      If(!IsPostBack)
       {
        ddlBusinessUnit.DataSource = sqlCommands.GetBusinessUnits();
        ddlBusinessUnit.DataValueField = "BusinessUnit";
        ddlBusinessUnit.DataBind();
        ddlBusinessUnit.Items.Insert(0, new ListItem("", ""));

        ddlBlankForms.DataSource = sqlCommands.GetForms();
        ddlBlankForms.DataTextField = "FormDesc";
        ddlBlankForms.DataValueField = "FormReport";
        ddlBlankForms.DataBind();
        ddlBlankForms.Items.Insert(0, new ListItem("", ""));
      }
    }

And leave the Page_Init empty
     the protected void Page_Init(object sender, EventArgs e)
    {
     //empty
    }

I hope it will help you. It is just a solution between many.
Update
  protected void ddlTask_OnSelectedIndexChanged(object sender, EventArgs e)
 {
   if (ddlTask.SelectedIndex == 0) return;
   string url = "http://reportserver";
   url += sqlCommands.GetSpecificFormReportName(ddlType.SelectedValue);
   url += "&BU=" + ddlBusinessUnit.SelectedValue;
   url += "&TID=" + ddlTask.SelectedValue;
   url += "&rs:Format=PDF";
   Response.Redirect(url, false);//false to allow the code to continue execution
   Return;
 }

A: did you try following ?
Response.Redirect(url, false);

A: I have a "partial" fix for this. It's not 100%, and should be considered a "hack".
Basically the page has to render in the browser in order for the ViewState to contain the "cleared" drop down list.
public class ResponseStuff
{
    public static void ClientRedirect(Page page,string url)
    {
        string script = "<script type='text/javascript' runat='client'>$(function() {window.location='" + page.ResolveUrl(url) + "';});</script>";
        page.RegisterClientScriptBlock("client_redirect",script);
    }
}

called via
ddl.ClearSelection();
ResponseStuff.ClientRedirect(this,url);

hack alert caveats: Hitting the browser back button twice (fast) causes the same behavior before this fix. When the back button is clicked, a redirect is again performed, however the drop down is "cleared". This requires JQuery.


text:
Q: Non-automatic numbering of mathematical equations in LyX In my LyX document, I want to number my mathematical equations as I see fit, and not automatically.

I looked for information on this question but without success.
So if a LyX user could tell me how, I would be grateful.

A: At the end of a normal displayed equation (added with e.g. Ctrl + Shift + M), type \tag and hit the Tab key. Then type whatever number or text you want.


text:
Q: A word to describe what a company does when it adds balance to a credit account due to interest So I have a debt of $500. After a month, I owe $600 because my debtor has added to my account due to interest (also because the account has a terrible APR). In this situation I would say my creditor has (1._________). I would also say interest has been (2.______) against my account
I could swear I've read this word in context, I just can't for the life of me remember it.

A: For #1, I can't think of a single word that would fit there. It would mostly require at least two words, including a direct object (probably "me" or "my account").
For #2, interest accrues, but when it gets added to your amount owed, it becomes capitalized.
https://myfedloan.org/help-center/faq/interest-faq.shtml

A: After some research I found the word I was looking for. Using the third definition here
I might say my creditor has assessed interest.
I might also say interest has been assessed against my account.
From Dictionary.Com
Assess
verb (used with object)

*

*to estimate officially the value of (property, income, etc.) as a basis for taxation.

*to fix or determine the amount of (damages, a tax, a fine, etc.):The hurricane damage was assessed at six million dollars.

*to impose a tax or other charge on.

*to estimate or judge the value, character, etc., of; evaluate:to assess one's efforts.


text:
Q: Random "Login failed for user 'NT Authority\Anoymous Login'" errors in production We have a asp.net web application that uses windows authentication It was previously using sql authentication. We are consistently (but randomly) getting "Login failed for user 'NT Authority\Anoymous Login'" errors in production. Most of the times, the application works fine. From SQL server database perspective, the SPN's and delegations are in place.
The connection string looks like:
<add name="SomeName" connectionString="Data Source=<SomeDataSource>;Initial Catalog=<SomeInitialCatalog>;Integrated Security=true" providerName="System.Data.SqlClient">

What could the underlying issue be?


text:
Q: Python package naming strategy for company I work in a data analysis role and my team is just getting set up to use Git. We have various useful bits of Python that we'd like to keep in version control. I'm looking to understand the best way to structure utility code modules/packages in our Git repos.
I'd like to namespace our modules with the company name as in PEP 423. So a module might be named mycorp.graphing or mycorp.numbercruncher
Is this the right approach and can I set up each of these namespaced modules as separate Git repos? I am wondering if each repo should be rooted at the non-namespaced folder (eg. graphing, numbercruncher) and users should be directed to check out any useful ones into a folder called "mycorp" on their python path.
Is there a better way than this?
The tech skills among the team are varied so I need this to be as simple as possible for people to use.

A: That seems to be the right approach if these packages should be maintained independently. Then you just keep the same folder structure: "mycorp" folder with an empty __init__.py and graphing and numbercruncher subfolders. The subfolders are git repositories.
Then you can add this "mycorp" path to a global PYTHONPATH environment variable and import mycorp.graphing or from mycorp import graphing.


text:
Q: Where can I get a list of cache line sizes and cache sizes for AMD and Intel processors I was hoping somebody somewhere has compiled a human readable list of L1 cache size / line size for recent processors.

A: Not quite what you're looking for, but there's the CPUID dev kits which can determine this info programmatically.


text:
Q: Green's Functions solution to PDE with Neumann Boundary Condition I am trying to find the Green's function for $-cu''=f(x)$ with the boundary condition that $u'(0)=0=u(1)$.
So far I've started by supposing $f(x)=\delta_\xi(x)$ and then considering $ \frac{d^2G}{dx^2}=\delta_\xi(x)$. And then I consider the homogenous equation, giving $G=ax+b$, with  $a,b\in \mathbb{R}$ but that doesn't seem right and think I am making a mistake. Where should I proceed from here? I know how to solve for coefficients and such, but I get stuck in the actual set up of the problem.
Thanks.

A: You want a solution of
$$
                   u_{\xi}''(x)=0,\;\;\; 0 < x < \xi,\;\; \xi < x < 1, \\
                           u_{\xi}'(0)=0,\;\; u_{\xi}(1)=0, \\
                           u_{\xi}(\xi+0)=u_{\xi}(\xi-0), \\
                          -cu_{\xi}'(\xi+0)+cu_{\xi}'(\xi-0)=1.
$$
The last condition gives the $\delta_{\xi}$ property for $-cu''$. The solution to the left of $\xi$ is a constant. The solution to the right of $\xi$ is a constant times $1-x$. Thus,
$$
          u_{\xi}(x) = \left\{\begin{array}{cc}
                          A, & 0 < x < \xi \\
                          B(1-x), & \xi < x < 1
                        \end{array} \right.
$$
where $A$ and $B$ are determined by the last two conditions. Continuity gives $A=B(1-\xi)$ and the jump condition gives $-cB(-1)-0=1$, or $B=1/c$. So $A=(1-\xi)/c$. Therefore,
$$          u_{\xi}(x) = \left\{\begin{array}{cc}
                          (1-\xi)/c, & 0 < x < \xi \\
                          (1-x)/c, & \xi < x < 1
                        \end{array} \right.
$$


text:
Q: PHP and SQL - Echoing Rows from Database I am trying to select data from a database, dependent on the user and echo it in the html code, but for some reason it won't capture the data.. please see code below:
<?php

$loginuser = $_GET['uid'];

$check = mysql_query("select * from users where username='$loginuser'");
   while($row = mysql_fetch_array($check)){

  $result = $row['email'];
  $result = $row['firstname'];

 }

 ?>

    <title> SIAA Dashboard </title>

 User Dashboard

 You should only see this screen if you are a registered user.

    <?php
    echo "Your username is: " . $loginuser . "

";
    echo "Your first name is: " . $result=$row['firstname'] . " ";
    ?>

If someone could tell me what I'm doing wrong, it will be much appreciated!
Thanks
Sohail.

A: Besides that your code is prone to SQL injection as you do not sanitze the $__GET Parameter 'uid' before inserting it in the query and you are using the deprecated mysql extension, your problem is the line
    echo "Your first name is: " . $result=$row['firstname'] . " ";

which should read
    echo "Your first name is: " . $row['firstname'];

Additionally, you did not establish a connection to the database.

A: A few notes:

*

*Don't use mysql_... functions: they're deprecated. See the documentation

*Check whether the input is supplied using isset: if uid is missing from $_GET the visitor will see a PHP warning.

*Escape/sanitize user input! If anyone requests your php file with ?uid='; drop table users;-- you're going to have a problem!

*If you expect 0 or 1 results, don't use a while loop

*Better not use constructs like echo "foo" . $bar = $baz . "something";: it's unclear.

And a suggestion on how to structure your page:

    <title> SIAA Dashboard </title>

<?php
  $loginuser = isset( $_GET['uid'] ) ? $_GET['uid'] : null;

  if ( empty( $loginuser ) )
  {
     echo "Missing parameter!";
  }
  else
  {
    $check = mysql_query("select * from users where username='"
    . mysql_real_escape_string( $loginuser ) . "'" );
    if ( $row = mysql_fetch_array($check) )
    {
?>

 User Dashboard

 You should only see this screen if you are a registered user.

      Your username is: <?php echo $loginuser; ?>

      Your first name is: <?php echo $row['firstname']; ?>
<?php
    }
    else
    {
      echo "Unknown user!";
    }
  }
?>

A: First do not use mysql_* functions and you need to create a mysql connection. This is still as risk for injection but should work.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$loginuser = $conn->real_escape_string($_GET['uid']);

$sql = "SELECT * FROM `users` WHERE `username` = '$loginuser'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();
}
$conn->close();
?>

    <title> SIAA Dashboard </title>

 User Dashboard

 You should only see this screen if you are a registered user.

    <?php
    echo "Your username is: " . $loginuser . "

";
    echo "Your first name is: " . $data['firstname'] . " ";
    ?>

A: /*
 * Best to start using PDO for db, If i was you i would rewrite your entire db script and stay away from mysql.
 *
 */

$id = $_GET['uid'];
try {
    $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $DBusername, $DBpassword);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT * FROM users where username= :id');
    $stmt->execute(array('id' => $id));

    $result = $stmt->fetchAll();

    if ( count($result) ) {
        foreach($result as $row) {
        print_r($row); // $row  will give you access for your variables.
    }
    } else {
        echo "No rows returned.";
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>

    <title> SIAA Dashboard </title>

 User Dashboard

 You should only see this screen if you are a registered user.

    <?php
    echo "Your username is: " . $loginuser . "

";
    echo "Your first name is: " . $result=$row['firstname'] . " ";
    ?>


text:
Q: validation on JSP page does not work I have the following jsp page with one input textbox, upon entering the number, the page is redirected to a servlet where I retrieve that number and let's say display it on a page. I'm trying to do the validation in JavaScript but in spite of it, it's still executing the servlet even though validation returns false and I get java.lang.NumberFormatException: For input string: "" in the doGet method on the servlet on the following line: int max = Integer.parseInt(request.getParameter("lengthTxt"));. Why does it seem to bypass validation and still execute the servlet ? How to fix it ? thanks for help !
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Length calc</title>

enter length

<form name=frm action="MyServlet" onSubmit="return validateForm();">

    <input name="lengthTxt" />

    <input type = "submit" value = "Submit"/>

</form>

A: This seems insane.After checking this code on some browsers.It will execute form submit event even the the onsubmit returned with a false value like this.
onsubmit="return validateForm()";

So that you can prevent further form exection with event.preventDefault() function.
So that using Conditional Statement in onsubmit will save the day.Below goes the full statement to be used.
<form onsubmit="event.preventDefault(); return validateMyForm();">

Anything more,jz comment.

A: if you given wrong name in field to focus then it happens otherwise it should be work fine.  please check again in java Script function.


text:
Q: How could I add my project path to the sys.path permanently? I'm using visual studio code to build up a python project. It is my first time to build a project with an Editor(in the past using Pycharm).
As the project gets bigger, I want to import some classes I have written in the other directories(in the same project). First I added the __init__.py in the directories I want to import from. However, it did not work and it raised:
ModuleNotFoundError: No module named 'LinkedList'
Then I searched on the internet and found that my project path was not in the sys.path. So I added the following in the file where I want to import class:
sys.path.append('D:\\Python_Projects\\Python_DataStructure')
And it worked. I have a question here. How could I permanently add my project path into the sys.path so I did not need to do the sys.path.append in every file where I want to import some classes or functions from other directories?
My project structure currently looked like this:
Python_DataStructure\
                     LinkedList\
                                 Mylinkedlist.py
                                 __init__.py
                     Queue\
                           queue.py
                           __init__.py

I omitted some python files in the directories above for simplicity

A: You can set the environment variable PYTHONPATH to a colon-separated list of
   directories to search for imported modules.
You can do that by going into:
My Computer > Properties > Advanced System Settings > Environment Variables >
Add the paths to the modules here.