text:
Q: Add string values to variable depending on another variable I have the following variable in bash:
$httpd_server_count, this variable can contain values like 1 or 2 and etc. And depending on this value I need to get proper value in $settings variable. The string is:
If the $httpd_server_count=1:
settings={'httpd1': {'server': 'settings.server1'},

If the $httpd_server_count=2:
settings={'httpd1': {'server': 'settings.server1'}, {'httpd2': {'server': 'settings.server2'},

and count can be is up to 10 and more. How to properly organize it in code?

A: I'm a bit unclear on what you are needing, but it appears you want to read the value of httpd_server_count and based on the number 1, 2, whatever generate the server strings needed. If I have it right, one way would be to use a simple C-Style for loop based on httpd_server_count. For example:
#!/bin/bash

str=
for ((i = 1; i <= $httpd_server_count; i++)); do
    str="${str}{'httpd$i': {'server': 'settings.server$i'}, "
done

echo -e "str\n\n$str"

You would still be responsible for trimming the trailing , and appending a closing '}' if required. But, if your value of httpd_server_count is 1, then you get:
{'httpd1': {'server': 'settings.server1'},

If it is 2, you get:
{'httpd1': {'server': 'settings.server1'}, {'httpd2': {'server': 'settings.server2'},

This may give you an idea you can run with. Let me know if you have any questions. (by the way, a json parser is generally preferred, like jq)

A: Use functions in bash to make the code more portable and efficient. Just put the code in a wrapper like below. Logic is similar to this David C. Rankin's answer,
function settingsGenerator() {
    local httpd_server_count=$1

    local i
    local settings

    for ((i=1; i<=httpd_server_count; i++))
    do
        settings="${settings}{'httpd$i': {'server': 'settings.server$i'}, "
    done

    printf "%s" "$settings"
}

and store the output of the function in a variable, settings as
settings=$(settingsGenerator 2)
printf "%s\n" "$settings"
{'httpd1': {'server': 'settings.server1'},{'httpd2': {'server': 'settings.server2'},

Using arrays would require a small change something like,
function settingsGenerator() {
    local httpd_server_count=$1

    local i
    local settings=()

    for ((i=1; i<=httpd_server_count; i++))
    do
        settings+="{httpd$i': {'server': 'settings.server$i'}, "
    done

    printf "%s" "${settings[@]}"
}

A: Use for loop:
#!/bin/bash
for i in `seq $httpd_server_count`; do
    settings+="{'httpd$i': {'server': 'settings.server$i'}, "
done


text:
Q: Newly opened window is not getting preferences from parent window in selenium webdriver I'm automating an application which is having digestive authentication process. From one window, when clicking on particular link we will get a new window which will have digestive authentication. I'm using Firefox browser for my automation. When I do it from system profile, it's working fine, but when I use custom profile from selenium, it's not automatically authenticated. I suspect that preferences from parent window is not shared with new window. Can anyone help me on this ?

A: You need to make sure that the window is definitely opening in the profile you need it to.
If it isn't, a good idea is to go through and check that the webdriver settings are connected to the correct profile.
If that is all correct, ensure the settings within your custom Firefox profile are the exact same as the ones within the system profile.
You can check the profile running in the terminal:
firefox -P

This should open the profile manager.
Hope I've helped :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is Object reflective information stored?
*

*What use could someone have to override this (getClass()) method? What purpose could it solve practically.

*The java documentation says this: By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass() == x.getClass(). Why would this be true? What does this truth hold? Where is the information being stored that knows what type of object it is? How does this work?
Sorry this question I deleted and I shouldn't have. I meant to edit it. Won't happen again.
EDIT: I misread the documentation, it is final X-(, but I still would like to ask the second question

A: The getClass method is public final.  It can not be overridden.
Using clone is definitely not a good practice.
I think what the java documentation is saying is don't change the implementation of clone.  If you override clone, use super.clone to keep the same implementation.
If you don't change the implementation, what is the point of overriding?
You could add logging.
You could loosen it from protected to public.
etc
If you don't change the implementation, then it will have the standard implementation which evidently guarantees that property.  On the other hand, if you change the implementation, all bets are off.

A:
Where is Object reflective information stored?

In the class.

What use could someone have to override this (getClass()) method? What
  purpose could it solve practically.

No purpose whatsoever, because getClass() is final, so it cannot be overridden, so your question isn't about anything that can actually occur.

Why would this be true?

Because Object.getClass() returns the class of the Object it is called on, and because Object.clone() returns an object of the same class that it was called on, and because a chain of super.clone() calls will terminate at Object.clone().


text:
Q: Using bash to sort data horizontally I have a file full of data in columns
sarah mark john
10    20   5
x     y    z

I want to sort the data so the columns stay intact but the second row is in increasing order so it looks like this:
john sarah mark
5    10    20
z    x     y

I've been looking at the sort command but have only been able to find vertical sorting, not horizontal. I'm happy to use any tool, any help is appreciated.
Thank you!

A: Let's create a function to transpose a file (make rows become columns, and columns become rows):
transpose () {
  awk '{for (i=1; i<=NF; i++) a[i,NR]=$i; max=(max<NF?NF:max)}
        END {for (i=1; i<=max; i++)
              {for (j=1; j<=NR; j++)
                  printf "%s%s", a[i,j], (j<NR?OFS:ORS)
              }
        }'
}

This just loads all the data into a bidimensional array a[line,column] and then prints it back as a[column,line], so that it transposes the given input. The wrapper transpose () { } is used to store it as a bash function. You just need to copy paste it in your shell (or in ~/.bashrc if you want it to be a permanent function, available any time you open a session).
Then, by using it, we can easily solve the problem by using sort -n -k2: sort numerically based on column 2. Then, transpose back.
$ cat a | transpose | sort -n -k2 | transpose
john sarah mark
5 10 20
z x y

In case you want to have a nice format as final output, just pipe to column like this:
$ cat a | transpose | sort -n -k2 | transpose | column -t
john  sarah  mark
5     10     20
z     x      y

Step by step:
$ cat a | transpose
sarah 10 x
mark 20 y
john 5 z
$ cat a | transpose | sort -n -k2
john 5 z
sarah 10 x
mark 20 y
$ cat a | transpose | sort -n -k2 | transpose
john sarah mark
5 10 20
z x y

A: Coming from a duplicate question, this would sort the columns by the first row:
#!/bin/bash

input="$1"

order=$((for i in $(head -1 $input); do echo $i; done) | nl | sort -k2 | cut -f1)

grep ^ $input | (while read line
  do
    read -a columns <<< "${line%"${line##*[![:space:]]}"}"

    orderedline=()
    for i in ${order[@]}
    do
      orderedline+=("${columns[$i - 1]}")
    done
    line=$(printf "\t%s" "${orderedline[@]}")
    echo ${line:1}
  done)

To sort by second row, replace head -1 $input with head -2 $input | tail -1. If the sort should be numeric, put in sort -n -k2 instead of sort -k2.

A: Good one-liner gets the job done:
perl -ane '$,=" "; print sort @F; print "\n";' file
I found it here: http://www.unix.com/unix-for-advanced-and-expert-users/36039-horizontal-sorting-lines-file-sed-implementation.html


text:
Q: The basis for additive subgroup is discriminant-invariant i.e. given bases $\{\beta_{i}\}$ and $\{\gamma_{i}\}$ for S additive subgroup of number field K (degree n over $\mathbb{Q}$), then $disc(\{\beta_{i}\})=disc(\{\gamma_{i}\})$.
any hints?
Is that because any algebraic number can be made into an algebraic integer

A: Hint : there is a $p\times q$ integral matrix $P$ such that $(\beta_1,\beta_2,\ldots,\beta_p)=P(\gamma_1,\ldots,\gamma_q)$ and a $q \times p$ integral matrix $Q$ such that $(\gamma_1,\ldots,\gamma_q)=Q(\beta_1,\beta_2,\ldots,\beta_p)$.
  What can you say about the products $PQ$ and $QP$ ?


text:
Q: how to pass file from client to controller by jquery? i want to create very simple sample to uploading a file by client side in mvc4 by jquery and java script.
i Google it and found many samples and many plugins on internet but i prefer to do not have any dependency on any extra plugin or library like "uploadify"
for this i create a simple mvc4 application and in my view i attach my script file that contains method bellow until user click a button on this view start to uploading.
i do not know how to change bellow method to pass file to controller(in client side) ?
function uploadimage() {

  $.ajax({
    url: "/Uploader/FileUpload",
    type: 'POST',
    dataType: 'json',
    data:null,
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {

    },
    error: function (xhr) {

    }
});

}
in my view
   <input type="file" id="fileToUpload" name="file" />
   <input type="button"  value ="Upload"  onclick="uploadimage()"/>

my controller
 public ActionResult FileUpload(HttpPostedFileBase file)
    {
       //do somethings with file
     }

A: file upload is not possible through ajax. You can upload file, without refreshing page by using IFrame.


text:
Q: teaching concept of "subspace" to linear algebra students I'm currently a T.A. for an introductory combined linear algebra & differential equations course geared toward engineering students. One major problem I've run across is that most of my students, when asked determine for instance whether the set $S=\left\{f\colon \mathbb{R}\to\mathbb{R}: f(x)=f(-x)\text{ for all }x\in \mathbb{R}\right\}$ is a subspace of the space $V$ of all real-valued functions, will begin with some variation of:

Let $x,y\in S$. Then $f(x+y)=\ldots$

On the other hand, when asked to do the same thing for something like $S=\{\mathbf{x}\in \mathbb{R}^n:A\mathbf{x}=\mathbf{b}\}$ (where $A$ is an $m\times n$ matrix and $\mathbf{b}\in \mathbb{R}^m$) and $V=\mathbb{R}^n$, these same students are able to proceed correctly.
What are some good ways to address this sort of issue?
EDIT (4:24pm 3/15/2013): Note that for the first $S$ above, the students were actually given a description of the set in prose-form, i.e. "Let $S$ be the set of real-valued functions $f$ on $\mathbb{R}$ such that $f(x)=f(-x)$ for all $x\in \mathbb{R}$."

A: Sounds like they are struggling with the jump from a concrete vector space like $\mathbb R^n$ to an abstract vector space. If I were you, I would run a lesson/review session or write a worksheet that

*

*States the defining properties of a vector space

*Encourages the students to think of sets that satisfy these properties which are not tuples of numbers

I would discuss polynomials, functions, and subspaces thereof in depth with them, being sure to lead them to examples and counterexamples.
If the only thing in my power was to revise the question, I would create a part (a) asking them to prove the space of real functions was a vector space (in prose, rather than giving them symbols to start playing with before thinking about it) and maybe a part (b) asking them to name a few elements of the set you will ask them about in (c) your original question.
IMHO, since sounds like a beginning-intermediate course that isn't aiming to train math majors, don't make them work so hard to parse out the mathematical ideas. Specifically, I think they could be getting distracted by the set builder notation.  I would just call this "the set of even functions" here.

A: It sounds like they have a fixed prototype of a vector space as looking like $\Bbb R^n$. Sure, that is true, but I think they are so attached to the image of $\Bbb R^n$ that they aren't recognizing vector spaces that appear in other forms.
When you ask them to think abstractly about "the vector space of functions from $\Bbb R ^n\rightarrow \Bbb R$" their prototype is breaking down. In all likelihood, their image of functions is that functions start on $\Bbb R^n$ and go somewhere, and the idea that functions as entities could be added and scaled as vectors is new.
Spend a little more time trying to convince them that the functions are vectors in a vector space, and hopefully that will remind them that what they should be checking is $f+g$ instead of $f(x+y)$.

A: I run into the same problem with my students and I think the best thing you can do is precsiely what you already do: assign them a problem like that and then point out why they are doing it wrongly. But let them think about it first.


text:
Q: Implementing columnar encryption technique? I am working on another encryption technique now, the columnar transposition cipher technique.
So far I have only tried to make columns and what I am trying to do is to view the matrix.
But with the code that I have written it is only showing one letter in the matrix:
import java.io.*;
import java.lang.reflect.Array;

public class transCip {
    public static void main(String args[]) {
        String keys;
        String message;
        String encrypt;
        String decrypt;
        message = "encryptiontextbe";
        keys = "work";
        encrypt = "";
        decrypt = "";
        char msg[] = message.toCharArray();
        char key[] = keys.toCharArray();
        int x = msg.length;
        int y = key.length;
        char temp[][] = new char[y][x];

        if (x % y != 0) {
            System.out.println("Cannot encrypt string");
        }
        for (int i = 0; i < (x/y); i++)
        {
            for (int j = 0; j < y; j++)
            {
                int k=0;
                temp[i][j] = msg[k];
                k++;
            }
        }
        System.out.println("Matrix");
        for (int i = 0; i < (x/y); i++)
        {
            for (int j = 0; j < y; j++)
            {
                System.out.print(temp[i][j]);
            }
            System.out.println("");
        }
    }
}

And my current output is as follows:
Matrix
eeee
eeee
eeee
eeee

I can't seem to figure out why this is happening;
I tried solving the run on paper also.

A: for (int i = 0; i < (x/y); i++)
    {
            for (int j = 0; j < y; j++)
        {
        int k=0;
                temp[i][j] = msg[k];
        k++;
        }
        }

You reset k to zero in each iteration of the loop, guaranteeing you always get the first letter 'e' of your message string.  Try initializing k before the inner loop.  This would have been easier to spot with better formatting:
for (int i = 0; i < (x/y); i++) {
    for (int j = 0; j < y; j++) {
        int k=0;
        temp[i][j] = msg[k];
        k++;
    }
}


text:
Q: Undo/redo + save I'm developing a C# application that has the following two requirements:

*

*the user should be able to undo/redo commands such as inserting, editing and deleting accounts, transactions, etc.

*these commands should only be persisted to the SQL CE database when the user clicks save.

Are there any best practices for doing this? I have read that implementing the command pattern is useful for the undo/redo requirement. The problem for me comes in persisting the changes to the database. I am using business entities and not DataSets, and I cannot use Linq to SQL or Entity Framework, so I am not sure how to track changes made to these entities to persist to the database when the user clicks save.
My question is:
Is it advisable to implement the Unit of Work pattern to track changes or is there a better way? I am not sure how that will combine with the command pattern, e.g. is the unit of work passed to the command which marks an entity as dirty/new/deleted, and what happens when the undo method of a command is executed? Is the entity marked as dirty/new/deleted again or can it be removed from the unit of work somehow?

A: http://en.wikipedia.org/wiki/Memento_pattern
Command will change your business entities, they will store current state in state objects, and list of previous state entries, save will save current state, rollback will restore previous state.

A: Use the Command Pattern with the following change (in the regular command pattern you have an invoke method. In this specialization you use a dispatcher to invoke the command).
Create a Dispatcher class which all commands are invoked through. Create an event in that class which is invoked for all commands. Create a class which listens on that event. Let that class save serialize all changes to your database.


text:
Q: Transfering a Debian HDD into a different PC I would like to take my HDD with Debian Lenny installed on it and plug it into a totally different computer.
Does my Debian will handle the hardware changes? And if not, what do I have to do?

A: If this was the first drive on the old computer and you plug it in so that it's the first drive on the new computer, then as long as the hardware is compatible with your kernel, everything else should work just fine, except probably your network configuration (unless it's got the exact same network setup as well).
Otherwise, you'll probably need to create a bootable USB stick or CD (and test this on the new computer).  When you move the drive to the new computer, if it fails to boot on its own, boot with the USB stick and:

*

*find what device the harddrive was assigned as

*mount your partition (typically to /mnt)  (if you have multiple partitions mount those as well to /mnt/home, /mnt/usr, whatever)

*chroot to /mnt so you are working from the local drive (chroot /mnt should do it)

*fix /etc/fstab (inside the chroot) so all the devices point to the new device

*reinstall the boot loader (grub-install --recheck to force getting a new device map)


text:
Q: How do vw and vh units work? I want to know how to calculate the value for vh and vw. I am designing a website that uses 2vw and its working perfectly for my text. However, I just guessed. Please tell me how these units work so I can use them in the future. I'd also like to know if they have cross browser support.

A: vw and vh are a percentage of the window width and height, respectively: 100vw is 100% of the width, 80vw is 80%, etc.
To calculate the value in pixels, you would just do something like
vwToPx = function(vwValue) {
    return $(window).outerWidth()/100*vwValue;
}

One thing you should be aware of is that mobile Safari still renders vh incorrectly, and anything but the most recent Android browser can't handle either unit.  See caniuse.
For more information, you might look at this article on csstricks.com.


text:
Q: Is it possible to use proxies to change ports in this way? I am new to SysAdmining if you can even call it that. Basically me and the homies are running a minecraft server. But we don't want to pay the premium to get port 25565 which is super expensive for some reason.
Is it possible to get some kind of proxy, that takes in xxxx.xxx.xxx.xxx:23974 or similar and outputs yyyy.yyy.yyy.yyy:25565. That way I don't have to pay the premium for dedicated IP.
Soo sorry if this is a stupid question. I thought this was the place where you guys would know it anyone did.

A: Though not completly the answer you were asking for - AFAIK minecraft can use SRV dns records to alter the default port in a transparent way, I believe you can use it to run the server on a custom port and not having issue with typing the port in minecraft clients each time. You can also use it to run multiple world on the same IP and connect to each by using a different fqdn.
the records looks like this :
_minecraft._tcp.name TTL class SRV priority weight port target
in the link below you also have some examples, I'm sure that with enough fiddling you will get it to work
https://www.mcmiddleearth.com/community/wiki/setting-up-a-srv-record/


text:
Q: Capitalization of User Interface Buttons Being an amateur programmer and a bit of a perfectionist, I often find myself wondering about capitalization in user interfaces.
If you look towards the top of this very website, you'll notice the links under the "English Language & Usage" banner are all capitalized.  Every word, in fact; not just the first word of every link.  However, the ones at the very top of the page ("log out," "chat," etc.) have no capitalization.
What is the correct form?
Furthermore, when describing the buttons in a manual, should they be capitalized as if they were proper nouns?  For example:
Navigate to the "First Example" pane and click the arrow next to "Second Example."  This will bring up a dialog.  Now click "Third Example" to perform the task.

A: I would go with Stacker's answer. As per the Manual of Style for Technical Publications (MSTP), which is strictly followed by all of Microsoft's manuals, software applications etc., title case uses uppercase for every word in the title except prepositions, conjunctions and articles.
Prepositions that have more than 5 letters such as "During" and "Through" should also be capitalized. Articles that appear in the beginning of a sentence should obviously be capitalized.
Words that appear after colons/semicolons are capitalized as well.
Hyphenated words are capitalized based on consistency. For example, if you start out with "Non-company", you retain the lowercase for 'c' throughout the manual/application. If you start out with "Non-Company", you capitalize the 'C' throughout the manual/application. However, Web 2.0 has broken many of these standards and "log out" has also become acceptable. Ideally it should be "Log out".

A: Capitalization does not only apply to menu items, it is usualy part of a style guide which describes almost all elements of a user interface. Microsoft Styleguide
Another one for KDE

A: There is no correct form.  If you are used to UNIX and C programming, you might be tempted to make your site look like craigslist.org did in its early days.  You can do whatever you like.

A: Microsoft has made a page for a very quick overview and "cheat sheet" concerning capitalization of UI elements:
MSDN Common UI Controls and Text Guidelines: Capitalization


text:
Q: Selenium Python Paste Not Working in Headless Mode Python selenium paste isnt working in headless mode, i tried CONTROL + V, SHIFT + INSERT, with pyperclip3, pyperclip, klembord, but nothing seems to working, here is the code
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pyperclip3
import time

Desc = """

10 Undeniable Reasons People Hate cheats
"""

options = Options()
options.binary_location = r'CHROME_BINARY_LOCATION'
options.add_argument("--headless")
webdriver.Chrome(executable_path=r'CHROME_DRIVER_LOCATION', options=options)
driver.implicitly_wait(10)
driver.get("http://google.com")
time.sleep(2)
pyperclip3.copy(Desc)
element = driver.find_element(By.XPATH, '//input[@name="q"]')
# element.send_keys(Keys.CONTROL, 'v')
a = pyperclip3.paste()
element.send_keys(Keys.SHIFT, Keys.INSERT)
element.send_keys(Keys.CONTROL, 'v')
time.sleep(2)
driver.save_screenshot("image.png")
driver.close()
driver.quit()

A: I tried the below code with explicit waits, and it seems to do the job with pyperclip :
options = webdriver.ChromeOptions()
options.add_argument("--disable-infobars")
options.add_argument("--start-maximized")
options.add_argument("--disable-extensions")
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 2})
options.add_argument('--window-size=1920,1080')
options.add_argument("--headless")
options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})
driver = webdriver.Chrome(executable_path=driver_path, options = options)
driver.implicitly_wait(30)
driver.maximize_window()
driver.get("http://google.com")
wait = WebDriverWait(driver, 20)

desc = '''

10 Undeniable Reasons People Hate cheats
'''
pyperclip.copy(desc)
time.sleep(1)
wait.until(EC.visibility_of_element_located((By.NAME, 'q'))).send_keys(pyperclip.paste())
print("Succesful")
driver.save_screenshot("image.png")

Imports :
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pyperclip as pyperclip


text:
Q: How install libevent extension in Apache2 I try to install libevent in the php of my Apache2.4 in Ubuntu 16.04 but I can't do it.
I have this snippet of code for know if the library is detected in a test page on my apache server :
$test = event_base_new();

It says to me

Call to undefined function event_base_new()

I miss some informations like I don't know if a library is considered a mod (I think no) but i found no documentation about libraries in the Apache2 doc.
I compiled the source libevent-2.1.8-stable from the official website and add the line in my php.ini (php/apache2) :
extension=/usr/local/libevent.so

I restarted my Apache2 but that doesn't work.

A: The libevent extension is not distributed with PHP. It is separate from the event extension, also separate from (but related to) the libevent C library, and it is entirely unrelated to the Apache event MPM.
If you want to install the PHP libevent extension, you will need to install it from PECL. However, that extension isn't compatible with PHP 7, and hasn't been updated since 2013, so you probably don't want it.


text:
Q: Correct standard form for the equation of a line? So I was tutoring an Algebra 1 student yesterday and we were reviewing the three forms in which one can write the equation for a line: point-slope form, slope-intercept form and standard form. I told him to write an equation in standard form and he wrote:
$\frac x5 + \frac y4 = 1$ and I told him to rewrite it without any fractions as $4x +5y = 20$
Are both forms correct? I understand that the latter form may be more common but what I really want to know is if it is acceptable to use the former. Thanks all!

A: I agree that the latter is more common, but the former is indeed acceptable: each describes precisely the same line, after all!
However, I think it's perfectly reasonable to suggest that, when presenting the equation of a line in "standard form," to strive for integer coefficients.

A: The first form is usually called intercept form. That's because if you can write the equation in the form $\frac{x}{a} + \frac{y}{b} = 1$, then the $x$-intercept is $a$ and the $y$-intercept is $b$.
General form isn't unique, but intercept form is a specific variety of the general form in which the constant term is $1$ and is isolated on one side, and the coefficients of the variables are written as fractions with numerator $1$.

A: I have been taught that the standard form is: $$Ax + By + C = 0$$
Where A, B, and C are all integers, and A must be positive. So the latter part is correct.
For example, if I have a "messy" equation in slope-intercept form, $$y = x/2 + 3/4$$
I would have to multiply both sides by 4, giving me the equation: $$4y = 2x + 3$$
Because the coefficient of the x term has to be positive, I will move 4y to the right, which gives: $$2x - 4y + 3 = 0$$
I hope this answer helped!


text:
Q: Sending a POST request in Postman set to send a certain status sends the default status I want that my POST request sends a HTTP 409 in a certain case, so this is the code:
res.status(409).send();

However, when I tun the request in Postman it shows the result 200 OK. I put some logs in the code and I'm sure that the above line is hit.
What is wrong?
UPDATE:
Here is the full method:
app.post('/orders/:order_id/sync_status', (req, res) => {
    order.findOne({ order_id: req.params.order_id},
        function(err, results) {
            if (err) {
                res.send(`error: ${error}`);
            } else if (!results) {
                res.send(`no order with order_id: ${req.params.order_id}`);
            } else {
                status.findOne({ order_id: req.params.order_id},
                    function(err, result) {
                        if (err) {
                            res.send(`error: ${error}`);
                        } else if (result) {
                            res.status(409).send();
                        } else {
                            const newStatus = new status (req.body);
                            newStatus.save();
                        }
                    });
            }
            res.end();
        });
});

and the Postman request:

A: The simple reason is because you have res.end()
The longer answer is because res.end() is executed before this piece
status.findOne({order_id: req.params.order_id}, function(err, result) {
  if (err) {
    res.send(`error: ${error}`);
  } else if (result) {
    res.status(409).send();
  } else {
    const newStatus = new status(req.body);
    newStatus.save();
  }
});

got executed due to asynchronous call/callback.
Without testing, your final code should look like this
app.post('/orders/:order_id/sync_status', (req, res) => {
  order.findOne({order_id: req.params.order_id}, function(err, results) {
    if (err) {
      return res.send(`error: ${error}`);
    }

    if (!results) {
      return res.send(`no order with order_id: ${req.params.order_id}`);
    }

    status.findOne({order_id: req.params.order_id}, function(err, result) {
      if (err) {
        return res.send(`error: ${error}`);
      }

      if (result) {
        return res.status(409).send();
      }

      const newStatus = new status(req.body);
      newStatus.save();
      return res.end();
    });
  });
});


text:
Q: Empty outputInfoList for second graphic card I have two discrete video adapters on my PC: GTX 1060 and RTX 2080 ti.
I would like to use second one for my DXUT app. I found command line argument -adapter# to specify it, however, my program crashed when I run with -adapter1  (1 is adapter ordinal for RTX2080) option.
I started debugging and figured out the following issue: EnumOutputs returns only DXGI_ERROR_NOT_FOUND.
For GTX1060 first EnumOutputs call returns correct output.
Code section:
HRESULT CD3D11Enumeration::EnumerateOutputs( _In_ CD3D11EnumAdapterInfo* pAdapterInfo )
{
    HRESULT hr;
    IDXGIOutput* pOutput;

    for( int iOutput = 0; ; ++iOutput )
    {
        pOutput = nullptr;
        //next line returns at once DXGI_ERROR_NOT_FOUND for RTX2080
        hr = pAdapterInfo->m_pAdapter->EnumOutputs( iOutput, &pOutput );
        if( DXGI_ERROR_NOT_FOUND == hr )
        {
            return S_OK;
        }
        ...
}

        hr = EnumerateOutputs( pAdapterInfo );
        if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() ) //failed here cause second condition is true
        {
            delete pAdapterInfo;
            continue;
        }

Who know how to fix this problem?
All drivers are up to date.
P.S. I also tried to specify graphic card via Windows and GeForce software, but It seems appropriate only for laptop case with both integrate/discrete cards.

A: Oh my God..
The problem is only GTX1060 connected to my monitor.
My tutor explained me that it's impossible to render frame buffer in this case.


text:
Q: Create array - Visual Studio shows question marks I have problem with array creation in C#.
        String[] tempDateLine = new String[dataImport.nbrLines];

The syntax is (for me) right and the dataImport.nbrLines value is 23 (debugger).
But in the debugger I see :

After the index 14 I have problem for initialize my array and during the assignment I haven't error but no value is imported in my array (above 14).

A: Apparently this is the bug of Visual Studio, and you should use down arrow instead of mouse scrolling. This and This ask the same problem.


text:
Q: Internet access speed drops suddenly I have been using Ubuntu for six years. Since 20.04 LTS, the internet access (wifi) drops suddenly and randomly from 20Mb/s for download to 1Mb/s or even below! Sometimes it works flawlessly, sometimes I need to reboot twice a day. Unfortunately, the problem persists in Ubuntu 22.04 too.
I tried out most of the tricks recommended here but with no avail:  https://blog.rottenwifi.com/ubuntu-slow-internet/
According to some, the standard 5.15 kernel in Ubuntu 22.04 LTS is responsible for bad wifi behaviour. One guy recommends downgrading to 5.13 the other one prefers upgrading to 5.17: wifi issues in ubuntu 22.04LTS
What to do???
Any suggestion will be greatly appreciated

A: Check the configuration of your wifi router and set to follow values if possible:

*

*Place your router on a good place. See follow: https://blog.gl-inet.com/my-wifi-is-slow-where-to-place-my-router/

*Set the right country. Depend on law, different country`s have different count and power of wifi channels. So it shouldn't be set different on your router and your pc.

*Set your channel selection on you router to auto channel.

*If possible, use MiMo supporting devices (thats supportted by a part of wifi5 and all WiFi6 devices). This one have a much better handling in environments with a high count of wifi devices.

*Enable DFS support on your router, if possible. That protect you a little bit about wifi issues around airports, which are related on weather radar.

*Often you find a menue item on your router like "Do you like to support "b, g, n, ac, ax", if you dont need and if possible, disable "WiFi b and g" on your router.


text:
Q: Comparing subcategories of a categorical variable between two groups I would like to ask whether you could suggest me a test for the following situation:
I have two groups (A and B). Both groups have data for a categorical variable called X that has 3 categories. I would like to test whether the answers for each of the category are different between two groups. For example, I want to know if the number of observations in the first category is significantly greater in group A compared to the number of observations in the same category in group B.

A: If I understand correctly, it sounds like you should be able to take your data and produce a table like this one (I'm using fake data here):

x
A
B

level_1
500
450

level_2
300
200

level_3
200
350

Basically a table showing the counts across each level and group. Based on this table, we see that we have 1,000 people in each group. We can also see that, in the sample, $\frac{500}{500+300+200}=50\%$ of people in group A have x = level_1. You want to find out (i.e. test) whether this proportion is significantly different from the proportion of x = level_1 in group B, which in this case is $\frac{450}{450+200+350}=45\%$. And then you want to repeat this test for each level.
A simple way to do this is by carrying out a test of proportions using prop.test() in R. For example, for level_1 it would be:
prop.test(c(500, 450), c(500+300+200, 450+200+350))

### Output ###

    2-sample test for equality of proportions with continuity correction

data:  c(500, 450) out of c(500 + 300 + 200, 450 + 200 + 350)
X-squared = 4.814, df = 1, p-value = 0.02823
alternative hypothesis: two.sided
95 percent confidence interval:
 0.005283576 0.094716424
sample estimates:
prop 1 prop 2
  0.50   0.45

This gives you:

*

*The estimated proportions at the bottom (0.50 vs 0.45)

*The 95% confidence interval for the difference in proportions (0.005283576 0.094716424)

*The $\chi^2$ statistic for your test (4.814)

*The p-value for your test (0.02823)

So with this made-up data, we would conclude that the proportion of people with x = level_1 in group A is significantly different from group B's (at the 5% significance level). Then we would repeat this for the other two levels.
Note that if you were only interested in whether a proportion was greater in group A than in group B, you would need to set the alternative = 'greater' in prop.test(). This would make your test a one-sided one (the default test is two-sided).


text:
Q: Create different instance of a React component in React Router with import I am trying to initiate to use the same component but passing diffrent props to it depending on the route. Like this:
import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";

import Layout from "./pages/Layout";
import ApplicantsContainer from "./pages/ApplicantsContainer";
import Filtered from "./pages/Filtered";
import ApplicantStore from "./stores/ApplicantStore";

const app = document.getElementById('app');
ReactDOM.render(
  <Router history={hashHistory}>
    <Route path="/" component={Layout}>
      <IndexRoute/>
      <Route path="new" component={ApplicantsContainer} getData={ApplicantStore.getNew.bind(ApplicantStore)}/>
      <Route path="prescreen" component={ApplicantsContainer} getData={ApplicantStore.getPrescreen.bind(ApplicantStore)}/>
      <Route path="interview" component={ApplicantsContainer} getData={ApplicantStore.getInterview.bind(ApplicantStore)}/>
      <Route path="offer" component={ApplicantsContainer} getData={ApplicantStore.getOffer.bind(ApplicantStore)}/>
      <Route path="hired" component={ApplicantsContainer} getData={ApplicantStore.getHired.bind(ApplicantStore)}/>
      <Route path="declined" component={ApplicantsContainer} getData={ApplicantStore.getDeclined.bind(ApplicantStore)}/>
      <Route path="filtered" component={Filtered}/>
    </Route>
  </Router>,
app);

The problem is all routes receives the same instance of the component and use only the first getData props. How to declare different instances of the ApplicantsContainer component?

A: You can always create a new component outside <Router/>
e.g. your version
<Route path="new" component={ApplicantsContainer}
    getData={ApplicantStore.getNew.bind(ApplicantStore)}/>
<Route path="prescreen" component={ApplicantsContainer}
    getData={ApplicantStore.getPrescreen.bind(ApplicantStore)}/>

can be rewritten to
 // Assume getData is a prop you need to set in ApplicantsContainer
const ApplicantsContainerForNew = (
  <ApplicantsContainer
    getData={ApplicantStore.getNew.bind(ApplicantStore)}
  />
)

const ApplicantsContainerForPrescreen = (
  <ApplicantsContainer
   getData={ApplicantStore.getPrescreen.bind(ApplicantStore)}
  />
)
...

<Route path="new" component={ApplicantsContainerForNew}/>
<Route path="prescreen" component={ApplicantsContainerForPrescreen} />


text:
Q: Conditional expectation wrt random variable I really cannot figure out what is wrong with the last line....
There seem to be three definitions at least for conditional expectation with respect to a random variable. I would like to know if they are equivalent in all or in whichever contexts. Here are the three definitions I've found :
$\mathbb{E}(X|Y)$ is the only $\sigma(Y)$-measurable random variable such that either :

*

*$\forall Z \in \mathbb{L}^2 \left( \Omega, \sigma(Y), \mathbb{P}|_{\sigma(Y)} \right) \mathbb{E}(Z \mathbb{E}(X|Y)) = \mathbb{E}(ZX)$

*$\forall Z$ essentially bounded on $\left( \Omega, \sigma(Y), \mathbb{P}|_{\sigma(Y)} \right) \mathbb{E}(Z \mathbb{E}(X|Y)) = \mathbb{E}(ZX)$

*$\forall U \in \sigma(Y)$, $\mathbb{E} ( \mathbb{E}(X|Y) \mathbb{1}_U)= \mathbb{E}(X\mathbb{1}_U) $
I realised 1 implies 2 and 2 implies 3. So really my question is : does 3 imply 1 ?

A: I am showing (3) implies (1). Due to confusion in notation, let me denote by $E(X|Y)$ by $Z$ and let me write the $Z$ in condition (1) as $T$.
First take $T=1_A$ for any $A\in\sigma(Y)$. Then $E(TZ)=E(Z1_A)=E(X1_A)=E(TX)$ so the relation is true for indicators. By linearity, it's true for simple non-negative functions $T$.
Now take $T\geq0$ and take $T_n\uparrow T$ where $T_n$ are non-negative simple. Since the relation (1) is true for every $n$, $E(T_nZ)=E(T_nX)$. [Note we are taking $T,T_n$ to be $\sigma(Y)-$measurable].
Suppose first that $X\geq0$ then $T_nX\uparrow TX$ and by MCT, $E(T_nX)\uparrow E(TX)$. This implies $E(T_nZ)\uparrow E(TX)$. But since $X\geq0$, we have $Z\geq0$ (a.s.) ad therefore, $T_nZ\uparrow TZ$ implying $E(T_nZ)\uparrow E(TZ)$ by MCT. Therefore, $E(TZ)=E(TX)$.
Now take $X=X^+-X^{-}$ and apply MCT with $T,T_n\geq0$ separately to $X^+$ and $X^-$ and combine by linearity. Note also that $Z^+$ and $Z^-$ are versions of $E(X^+|Y)$ and $E(X^-|Y)$. So for any general $X$ you have $E(TZ)=E(TX)$.
Now for any general $T$, break $T=T^+$ and $T^-$. Get sequences $T_n\uparrow T^+$ and $S_n\uparrow T_n^-$ and play the same game with $T^+X$ and $T^-X$.


text:
Q: in JointJs, how to prevent element with ports from being moved, but still allow its ports to work? I have a JointJs element with ports. I'd like the element not to be movable within the diagram, but still allow the user to connect its ports to other elements. If I use the interactive attribute in the Paper to disallow interactions for these elements, then it becomes unmovable, but it's ports no longer work.
How can I accomplish that?
Thanks!

A: interactive can be both boolean or an object. Object defines more specific cases. It can have properties such as:
labelMove
arrowheadMove
vertexMove
useLinkTools applicable for links and elementMove applicable for elements.
so in your case paper.setInteractivity({elementMove: false}) should do the trick


text:
Q: How to change text position in window in javaFX In my program a text field takes value from the user and shows the value in the window. But i want show the texts in the right of the window.
I used setTextAlignment(TextAlignment.RIGHT) but it still shows texts in the left(I'm not sure whether it is the right method to call).
How can i solve it?
public class ChatBox extends Application{

    final ScrollPane sp = new ScrollPane();
    public void start(Stage stage){
    TextFlow textFlow = new TextFlow();
    textFlow.setPadding(new Insets(10));
    textFlow.setLineSpacing(10);
    TextField textField = new TextField();
    textField.setPrefSize(50,30);
    Button button = new Button("Send");
    button.setPrefSize(80,30);
    VBox container = new VBox();
    VBox box = new VBox();
    box.getChildren().addAll(sp,textFlow);
    container.setPadding(new Insets(10));
    container.getChildren().addAll(box, new HBox(textField, button));
    VBox.setVgrow(sp, Priority.ALWAYS);
    VBox.setVgrow(textFlow, Priority.ALWAYS);

textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));

textField.setOnKeyPressed(e -> {
    if(e.getCode() == KeyCode.ENTER) {
        playSound();
        button.fire();
    }
});
button.setOnAction(e -> {
    Text text;
    if(textFlow.getChildren().size()==0){
        text = new Text(textField.getText());
        text.setTextAlignment(TextAlignment.RIGHT);
        String str = textField.getText();
        System.out.println(str);
    } else {
        text = new Text("\n" + textField.getText());
        text.setTextAlignment(TextAlignment.RIGHT);
    }
    textFlow.getChildren().add(text);
    textField.clear();
    textField.requestFocus();
});
VBox vb = new VBox();
vb.getChildren().addAll(textFlow);
sp.setVmax(440);
sp.setPrefSize(400, 300);
sp.setContent(vb);
sp.vvalueProperty().bind((ObservableValue<? extends Number>) vb.heightProperty());
Scene scene = new Scene(container, 400, 300);
stage.setScene(scene);
stage.setTitle("jui");
stage.show();
}
}

A: Setting the textAlignment property for individual children does not work, since the alignment of the TextFlow is always used.
You need to set the textAlignment property of the TextFlow:
textFlow.setTextAlignment(TextAlignment.RIGHT);


text:
Q: WPF MediaElement Download File While Playing Is there anyway to play a file (video or audio type) from server using MediaElement and at the same time save data to a specific file location , so that next time once can load directly from local system.In my project i am using WPF Media Element

A: There is no straightforward way. It's possible - there are at least two ways you could do it. But it's not easy.
It's tricky to meddle with how MediaElement handles its source stream, because it uses Windows Media Player internally (which means that it's using either MediaFoundation or DirectShow under the covers, depending on which version of Windows you're running). The 'obvious' solution of writing some sort of interceptor that relays the underlying stream while also saving it to disk is possible, but you have to leave the world of .NET to do it, because MediaElement won't work with a .NET stream.
That's not to say that it's impossible. You 'simply' have to write a custom source filter, and set it up with a custom protocol implementation. http://msdn.microsoft.com/en-us/library/ms787558(VS.85).aspx describes how the video rendering infrastructure goes about deciding what kind of object to create to represent the video source, based on the URL passed in. MediaElement passes the source URL directly into this underlying infrastructure, so if you write a custom filter and associate it with, say the myhack: protocol, then if you set the source to, say, myhack://whatever, it'll end up loading your filter. If you then make your filter a wrapper around the http: filter, you will be able to save a copy of the incoming data out to disk.
This is non-trivial.
An alternative may be to host a local HTTP server. If you have the option to open up a local socket that you can listen on, then you could write an HTTP implementation that uses one of .NET's built-in HTTP client types to fetch the data, while saving a copy and serving that data up. This is also non-trivial, but possibly easier than writing a custom source filter.

A: I found that if I set the file size of the downloading file before i start downloading, then the MediaElement will play the whole video/audio while it's downloading.
using (var httpClient = new HttpClient() {Timeout = TimeSpan.FromMinutes(25)})
using (var response = await httpClient.GetAsync(theDownloadUrl, HttpCompletionOption.ResponseHeadersRead))
using (var videoFileStream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read)) {
    videoFileStream.SetLength(response.Content.Headers.ContentLength.GetValueOrDefault());
    var copying = response.Content.CopyToAsync(videoFileStream);
    //await Task.Delay(1000);
    MediaSource = fileName;
    await copying;
}


text:
Q: getting the error "Medium without key" while installing my rpm from my repo O.S: Mageia 5
Problem:

*

*I build rpm , sign it and add it to my private repo.

*I exported my key using the command  gpg --export -a 'MY NAME' > RPM-GPG-KEY-pmanager

*I took this key and imported it to the PC where I want to install the rpm using rpm --import

*I have the error
/var/cache/urpmi/rpms/my_rpm_name.rpm: Medium without key (OK (RSA/SHA1, Mon 16 Sep 2019 03:50:12 PM EEST, Key ID 351f1c3ab40c2563))

*I can see the key
rpm -qa | grep ^gpg-pubkey-
gpg-pubkey-b40c2563-58ecf275
rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n'
gpg-pubkey-b40c2563-58ecf275 --> gpg(NAME & email here)
What I am missing ? Thanks

A: The media directory needs to contain the pub key as well.
This solved the issue.


text:
Q: ¿Cómo hacer un Split() con múltiples separadores Jquery? tengo esta fecha  2018-05-10T18:30:31 , y tengo que convertir esto para que el resultado final tener esto:
10/05/2018
12:34
es decir tener por un lado la hora en formato HH:mm  y la fecha en formato dd/MM/yyy.

A: Podrías hacer esto. Recuerda que esto se trata de mostrar que has hecho un esfuerzo en resolver el problema y que nosotros te ayudemos donde estás atascado

let firstDate= "2018-05-10T18:30:31";

let firstArray = firstDate.split("T");

let dma = firstArray[0].split('-');
let fmt = dma[2] + '/' + dma[1] + '/' + dma[0];

let hms = firstArray[1].split(":");
let hm = hms[0] + ":" + hms[1];

console.log(fmt);
console.log(hm);

A: Puedes explotar la cadena usando una expresión regular:
var fecha='2018-05-10T18:30:31',
    arrayfecha=fecha.split(/-|T|:/);

Que separa todos los componentes en un array [año, mes, dia, hora, minuto, segundo]

var fecha='2018-05-10T18:30:31',
    arrayfecha=fecha.split(/-|T|:/),
    fecha_formateada=arrayfecha.splice(0,3).reverse().join('/'),
    segundos=arrayfecha.pop(),
    hora_formateada= arrayfecha.join(':');

console.log(fecha_formateada);
console.log(hora_formateada);


text:
Q: Any performance gains from having identical clustered and nonclustered indexes on table on different filegroups? I am attempting to rearchitect our MSSQL database such that we have two filegroups, one for data, on a 15K HDD, primary, and one for indexes on a separate SSD, indexes, in order to realize some performance gains (which I read could be debatable, but I think in my case it is true).
I would ideally like to create a table on primary with an index on indexes to realize these gains, however the PK constraint happens to contain the same columns we would normally query, therefore the clustered PK index must, by definition also live on primary.
Would I still realize any performance gains if I created a nonclustered index containing the same columns as the PK on the indexes FG?


text:
Q: Angular material virtual scroll default offset in scroll when the scroll loads I have a table rendered using angular material virtual scroll.
this.trs = [  ...batch, ...this.trs];
setTimeout(() => this.viewPort.scrollToIndex(100), 1000);

I get the data and populated the virtual scroll and then set the scrollToIndex to 100.
and the 100th row shows up on the screen.
The problem here is that there is jumping, initially when the scroll loads it loads the 1st row and then jumps to the 100th row.
Is there a way to default it to the 100th row. So that it shows up directly without jumping.
More insight into the problem,
This is a bidirectional scroll, when the scrollbar hits the top it calls API and get new values and append on top of the array and then it hits bottom appends data to the bottom.
The logic works well when the data is appended at the bottom, but it scrollbar jumps every time the data is appended on top.
OR
https://stackblitz.com/edit/angular-4cwieu?file=src%2Fapp%2Fapp.component.ts
Is it possible to scroll to a particular index without that settimeout?


text:
Q: Variable usage in MySQL Stored Procedure I've some issue with a stored procedure on a MySQL 5.6.36:
DELIMITER $$
USE `test_schema`$$

DROP PROCEDURE IF EXISTS `count_requests`$$

CREATE PROCEDURE count_requests()
    BEGIN
    DECLARE tablename_tmp VARCHAR(64);
    DECLARE counter_tmp INT;
    DECLARE counter INT;
    DECLARE v_finished INT DEFAULT 0;
    DECLARE v_cur CURSOR FOR SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema='test_schema' limit 10;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;

    OPEN v_cur;
        get_flagged: LOOP
            FETCH v_cur INTO tablename_tmp;
            IF v_finished = 1 THEN
                LEAVE get_flagged;
            END IF;
            SELECT COUNT(*) INTO counter_tmp FROM tablename_tmp WHERE data_richiesta > (UNIX_TIMESTAMP(NOW())-21600);
            SET counter=counter+counter_tmp;
        END LOOP get_flagged;
        CLOSE v_cur;
    END $$
DELIMITER ;

The targets, in order, are:

*

*extract a list of tables from a specific schema;

*counting the records matching a WHERE clause;

*use the previous count result to increment a variable;

The trouble comes when I try to call it because, for some reason, the SELECT COUNT statement doesn't use "tablename_tmp" as variable, but as string. So:
mysql> call count_requests;
ERROR 1146 (42S02): Table 'test_schema.tablename_tmp' doesn't exist

Now, the stored procedure (logically speaking) should works beacause if I remove the SELECT COUNT to use a simple
SELECT CONCAT ('Tab name: ', tablename_tmp)
I get the expected result:
+-------------------------------------+
| CONCAT('Tab name: ', tablename_tmp) |
+-------------------------------------+
| Tab name: tab_10001                 |
+-------------------------------------+
1 row in set (0.10 sec)

+-------------------------------------+
| CONCAT('Tab name: ', tablename_tmp) |
+-------------------------------------+
| Tab name: tab_10002                 |
+-------------------------------------+
1 row in set (0.10 sec)

+-------------------------------------+
| CONCAT('Tab name: ', tablename_tmp) |
+-------------------------------------+
| Tab name: tab_10003                 |
+-------------------------------------+

I did some experiments, but without serious results and now I don't now how to proceed.
I appreciate any help.
Thanks in advcance.


text:
Q: JObject SelectToken Unexpected character while parsing path indexer I need to parse an API json response to pull out a certain value.  This method has always worked well for me without issue until tonight.  When attempting to execute this code:
JObject oR = JObject.Parse(response2.Content);

if (oR.SelectToken("[response][0][assignment][current][channelId]") != null)
{
    ChannelId = oR.SelectToken("[response][0][assignment][current][channelId]").ToString();
}

I receive this error:
Unexpected character while parsing path indexer: r

Here is the full json response from the api I'm attempting to parse:
{
    "response": [
        {
            "id": 268633,
            "parentOrderId": 0,
            "orderTypeCode": "SO",
            "reference": "#351569",
            "version": 3,
            "state": {
                "tax": "READY"
            },
            "orderStatus": {
                "orderStatusId": 41,
                "name": "Ready to Ship"
            },
            "tax": {
                "errors": []
            },
            "orderPaymentStatus": "PAID",
            "stockStatusCode": "SOA",
            "allocationStatusCode": "AAA",
            "shippingStatusCode": "SNS",
            "placedOn": "2021-10-07T18:53:54.000-05:00",
            "createdOn": "2021-10-07T18:54:12.000-05:00",
            "updatedOn": "2021-10-07T18:57:43.000-05:00",
            "createdById": 4,
            "priceListId": 3,
            "priceModeCode": "EXC",
            "delivery": {
                "deliveryDate": "2021-10-06T19:00:00.000-05:00",
                "shippingMethodId": 9
            },
            "invoices": [
                {
                    "invoiceReference": "",
                    "taxDate": "2021-10-07T00:00:00.000-05:00",
                    "dueDate": "2021-10-06T19:00:00.000-05:00"
                }
            ],
            "currency": {
                "accountingCurrencyCode": "USD",
                "orderCurrencyCode": "USD",
                "exchangeRate": "1.000000",
                "fixedExchangeRate": true
            },
            "totalValue": {
                "net": "14.10",
                "taxAmount": "1.16",
                "baseNet": "14.10",
                "baseTaxAmount": "1.16",
                "baseTotal": "15.26",
                "total": "15.26"
            },
            "assignment": {
                "current": {
                    "staffOwnerContactId": 0,
                    "projectId": 0,
                    "channelId": 3,
                    "leadSourceId": 0,
                    "teamId": 0
                }
            },
            "parties": {
                "customer": {
                    "contactId": 748240,
                    "addressFullName": "John Doe",
                    "companyName": "",
                    "addressLine1": "225 N First ST",
                    "addressLine2": "",
                    "addressLine3": "My Town",
                    "addressLine4": "Texas",
                    "postalCode": "76082-2583",
                    "country": "United States",
                    "telephone": "+1900MIXALOT",
                    "mobileTelephone": "",
                    "fax": "",
                    "email": "john.doe@yahoo.com",
                    "countryId": 223,
                    "countryIsoCode": "US",
                    "countryIsoCode3": "USA"
                },
                "delivery": {
                    "addressFullName": "John Doe",
                    "companyName": "",
                    "addressLine1": "225 N First ST",
                    "addressLine2": "",
                    "addressLine3": "My Town",
                    "addressLine4": "Texas",
                    "postalCode": "76082-2583",
                    "country": "United States",
                    "telephone": "+1900MIXALOT",
                    "mobileTelephone": "",
                    "fax": "",
                    "email": "john.doe@yahoo.com",
                    "countryId": 223,
                    "countryIsoCode": "US",
                    "countryIsoCode3": "USA"
                },
                "billing": {
                    "contactId": 748240,
                    "addressFullName": "John Doe",
                    "companyName": "",
                    "addressLine1": "225 N First ST",
                    "addressLine2": "",
                    "addressLine3": "My Town",
                    "addressLine4": "Texas",
                    "postalCode": "76082-2583",
                    "country": "United States",
                    "telephone": "+1900MIXALOT",
                    "mobileTelephone": "",
                    "fax": "",
                    "email": "john.doe@yahoo.com",
                    "countryId": 223,
                    "countryIsoCode": "US",
                    "countryIsoCode3": "USA"
                }
            },
            "orderRows": {
                "600995": {
                    "orderRowSequence": "10",
                    "productId": 30727,
                    "productName": "Mens Wrangler Sport Western Plaid Snap - M",
                    "productSku": "395802",
                    "quantity": {
                        "magnitude": "1.0000"
                    },
                    "itemCost": {
                        "currencyCode": "USD",
                        "value": "11.2500"
                    },
                    "productPrice": {
                        "currencyCode": "USD",
                        "value": "24.9900"
                    },
                    "discountPercentage": "0.00",
                    "rowValue": {
                        "taxRate": "9.5000",
                        "taxCode": "T",
                        "taxCalculator": "manual",
                        "rowNet": {
                            "currencyCode": "USD",
                            "value": "4.9900"
                        },
                        "rowTax": {
                            "currencyCode": "USD",
                            "value": "0.4000"
                        },
                        "taxClassId": 2
                    },
                    "productOptions": {
                        "Top Size": "M",
                        "Color": "Multi"
                    },
                    "nominalCode": "4000",
                    "composition": {
                        "bundleParent": false,
                        "bundleChild": false,
                        "parentOrderRowId": 0
                    },
                    "externalRef": "10197546795147",
                    "clonedFromId": 0
                },
                "600997": {
                    "orderRowSequence": "30",
                    "productId": 1001,
                    "productName": "Shipping: UPS SurePost",
                    "productSku": "",
                    "quantity": {
                        "magnitude": "1.0000"
                    },
                    "itemCost": {
                        "currencyCode": "USD",
                        "value": "0.0000"
                    },
                    "productPrice": {
                        "currencyCode": "USD",
                        "value": "9.1100"
                    },
                    "discountPercentage": "0.00",
                    "rowValue": {
                        "taxRate": "9.5000",
                        "taxCode": "T",
                        "taxCalculator": "manual",
                        "rowNet": {
                            "currencyCode": "USD",
                            "value": "9.1100"
                        },
                        "rowTax": {
                            "currencyCode": "USD",
                            "value": "0.7600"
                        },
                        "taxClassId": 2
                    },
                    "nominalCode": "4030",
                    "composition": {
                        "bundleParent": false,
                        "bundleChild": false,
                        "parentOrderRowId": 0
                    },
                    "clonedFromId": 0
                },
                "600996": {
                    "orderRowSequence": "20",
                    "productId": 1000,
                    "productName": "Coupon: PDJA046209",
                    "productSku": "",
                    "quantity": {
                        "magnitude": "1.0000"
                    },
                    "itemCost": {
                        "currencyCode": "USD",
                        "value": "0.0000"
                    },
                    "productPrice": {
                        "currencyCode": "USD",
                        "value": "0.0000"
                    },
                    "discountPercentage": "0.00",
                    "rowValue": {
                        "taxRate": "0.0000",
                        "taxCode": "-",
                        "taxCalculator": "brightpearl",
                        "rowNet": {
                            "currencyCode": "USD",
                            "value": "0.0000"
                        },
                        "rowTax": {
                            "currencyCode": "USD",
                            "value": "0.00"
                        },
                        "taxClassId": 1
                    },
                    "productOptions": {
                        "Top Size": "S",
                        "Color": "Green"
                    },
                    "nominalCode": "4020",
                    "composition": {
                        "bundleParent": false,
                        "bundleChild": false,
                        "parentOrderRowId": 0
                    },
                    "clonedFromId": 0
                }
            },
            "warehouseId": 3,
            "acknowledged": 0,
            "costPriceListId": 1,
            "historicalOrder": false,
            "externalRef": "3912489140363",
            "installedIntegrationInstanceId": 484,
            "orderWeighting": 100
        }
    ]
}

Unfortunately, I have no control over the json that is returned from the webservice API.  The best I have been able to dig up is that there is an issue with one of the json keys, but I can't seem to figure out how to fix it or account for it.
Thanks in advance for any help.

A: The correct JSONPath syntax is:
response[0].assignment.current.channelId

...or use enquoted property names:
['response'][0]['assignment']['current']['channelId']

Personally I prefer the former syntax as it's much cleaner and easier to read.

Additionally, your program is also inefficient because you're evaluating the JSONPath twice. Instead use C#'s is var operator to store the result:
JObject oR = JObject.Parse(response2.Content);

if (oR.SelectToken("response[0].assignment.current.channelId") is JToken channelIdToken)
{
    this.ChannelId = channelIdToken.ToString();
}


text:
Q: FeatureCollection (Error) Image.reduceRegions: Group input must come after weighted inputs I was trying to find the area of each block by category in the band. There is one band and it has 18 categories. The feature collection is a collection of blocks described uniquely by code_2011.
var image1 = ee.Image ("image_name");
var andhra = ee.FeatureCollection("Feature_name");

var image2 = ee.Image.pixelArea().addBands(image1);

var result = image2.reduceRegions({
    collection: andhra.select(['2011_code']),
    reducer: ee.Reducer.sum().group({
    groupField: 0,
    groupName: 'code',
  }),
    scale: 50
  }).filter(ee.Filter.neq('sum', null)
  ).flatten();

A: The problem is just from the order of the bands in the image. EE wants absolutely that the grouping variable comes after the variable to be reduced. So you will never be able to use  groupField: 0 (meaning grouping variable is first).
To see this, you can just invert the order of the bands in the documentation on  grouped reductions:

*

*nlDiff.select(["Land_Cover_Type_1", "stable_lights"]) with groupField: 0 will NOT work

*nlDiff.select(["stable_lights", "Land_Cover_Type_1"]) with groupField: 1 WILL work. This is the case implicit in the documentation.

Code:
// Load a region representing the United States
var region = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
  .filter(ee.Filter.eq('country_na', 'United States'));

// Load MODIS land cover categories in 2001.
var landcover = ee.Image('MODIS/051/MCD12Q1/2001_01_01')
  // Select the IGBP classification band.
  .select('Land_Cover_Type_1');

// Load nightlights image inputs.
var nl2001 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F152001')
  .select('stable_lights');
var nl2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012')
  .select('stable_lights');

// Compute the nightlights decadal difference, add land cover codes.
var nlDiff = nl2012.subtract(nl2001).addBands(landcover);

// Grouped a mean reducer: change of nightlights by land cover category.
var means = nlDiff.reduceRegion({
  reducer: ee.Reducer.mean().group({
    groupField: 1,
    groupName: 'code',
  }),
  geometry: region.geometry(),
  scale: 1000,
  maxPixels: 1e8
});

// Print the resultant Dictionary.
print(means);

A: You have to add a band to the existing band and call that band instead of the original one.
var image1 = ee.Image ("image_name");
var andhra = ee.FeatureCollection("Feature_name");

var image2 = ee.Image.addBands(image1);

var result = image2.reduceRegions({
    collection: andhra.select(['2011_code']),
    reducer: ee.Reducer.sum().group({
    groupField: 1,
    groupName: 'code',
  }),
    scale: 50
  }).filter(ee.Filter.neq('sum', null)
  ).flatten();


text:
Q: Replacing a sublist with another list in Java in constant time Is there a List-like container in Java that provides the capability of replacing a sublist with another list in constant time, given an iterator to the start and end of the sublist?
For example I could do the following:
List<T> l1, l2;
ListIterator<T> i1, i2;

// Initialize the above variables correctly...

l1.replace(i1, i2, l2);

If I was rolling my own linked list, this would be easy so I'd assume this is a feasible task using Collections.
Thanks in advance!

A: No, there's no way to do this in constant time using the built-in APIs.

If I was rolling my own linked list, this would be easy so I'd assume this is a feasible task using Collections.

Not quite.  Even rolling your own implementation, you can't do this in constant time in a way that

*

*would only change l1, not l2

*would let you do the same operation more than once, perhaps with l3 and l2
It is easy to imagine that if this were built into the JDK APIs, these problems could result in accidental behavior that was really unpleasant to debug.

A: Take a look at the AbstractList.html#addAll.


text:
Q: Why does IIS get stuck on startup at PipelineRuntime.WaitForRequestsToDrain()? When I launch a .NET 4.5 web application from Visual Studio 2013 (but I am not entirely sure that it is limited to this scenario) IIS gets stuck while starting up the application. If I kill w3wp.exe, it restarts automatically and the application works fine.
When I attach the debugger to the hung w3wp.exe I get the stack trace below. There is just one managed thread called Worker thread, all other are running native code - as such there isn't any custom code running/sleeping at the moment - just this one.
mscorlib.dll!System.Threading.Thread.Sleep(int millisecondsTimeout)
System.Web.dll!System.Web.Hosting.PipelineRuntime.WaitForRequestsToDrain()
System.Web.dll!System.Web.HttpRuntime.Dispose()
System.Web.dll!System.Web.HttpRuntime.ReleaseResourcesAndUnloadAppDomain(object state)
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()
[Native to Managed Transition]

What could be the reason for this?

A: I think you deserve an answer. I ran into the same issue and it looks like I've resolved it.
For me it was occurring because I wasn't tagging my await commands with .ConfigureAwait(false). I believe that not using it causes the main thread to do all of the work, constantly staying busy by switching code segments. But this thread gets hung somewhere via a deadlock (a waits for b, b waits for c, c waits for a).
Adding .ConfigAwait(false) results in parallel processing with no context instead of linear processing within a single context.
Hope you got it fixed.


text:
Q: How to sort a massiv array along innermost dimension? I have an Array r Ix2 a such that (Manifest r Ix2 a, Ord a). I'd like to sort this array on its innermost dimension - that is, sort each row internally, but not across rows. According to this, massiv doesn't have any sorting implemented at all. Would I have to roll my own, or can I re-use something that already exists for Vectors (such as vector-algorithms for example)?

A: Of course, it would be better to roll out your own sorting and submit a PR to massiv library ;) But there is a way to fall back onto vector-algorithms package. I was curious how I'd do it efficiently and here it is, along with automatic parallelization of sorting each row:
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
module Examples.SortRows where

import           Data.Massiv.Array                 as A
import           Data.Massiv.Array.Manifest.Vector as A
import           Data.Massiv.Core.Scheduler
import           Data.Typeable
import           Data.Vector.Algorithms.Merge
import           Data.Vector.Generic               as VG
import           Data.Vector.Generic.Mutable       as VGM
import           System.IO.Unsafe

sortRows ::
     forall r e v.
     (Ord e, Typeable v, A.Mutable r Ix2 e, VG.Vector v e, ARepr v ~ r, VRepr r ~ v)
  => Array r Ix2 e
  -> Array r Ix2 e
sortRows arr = unsafePerformIO $ do
  mv :: VG.Mutable v RealWorld e <- VG.thaw (A.toVector arr :: v e)
  let comp = getComp arr
      sz@(m :. n) = size arr
  case comp of
    Seq -> do
      loopM_ 0 (< m) (+ 1) $ \i -> sort $ VGM.slice (toLinearIndex sz (i :. 0)) n mv
    ParOn wIds ->
      withScheduler_ wIds $ \scheduler -> do
        loopM_ 0 (< m) (+ 1) $ \i ->
          scheduleWork scheduler $ sort $ VGM.slice (toLinearIndex sz (i :. 0)) n mv
  v :: v e <- VG.unsafeFreeze mv
  return $ A.fromVector comp sz v

I did add this to examples in massiv in this commit together with a simple property test.


text:
Q: how to compare two string in python ? I am getting this error Code syntax:
if( email_from1 != email_from2 & email_subject1 != email_subject2):

Error:

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

A: In python & is a bitwise operator.  It appears you need the logical operator, which would be and.  In addition in Python you do not need the () around the expresion for an if.  But using tuples you can just do:
if email_from1, email_subject1 != email_from2, email_subject2:

A: Python '&' doesn't work with strings. It's a Bitwise Operator. use 'and' instead:
eg 1:
a = 'omi'
b ='not omi'
c ='omi'

if a == c && b!=c:
    print "hello"

output:
  File "test.py", line 5
    if a == c && b!=c:
               ^
SyntaxError: invalid syntax

eg2 :
a = 'omi'
b ='not omi'
c ='omi'

if a == c and b!=c:
    print "hello"

output:
hello

could you try so :
if( email_from1 != email_from2 and email_subject1 != email_subject2):


text:
Q: How to install Ruby and Net::IMAP on Windows? I need to get started with Net::IMAP to write a Ruby script on Windows, so I've got the RubyInstaller for windows, but how do I install the IMAP gem? How do I setup my dev environment to write and run scripts?

A: As I see Net::Imap is a standart class and you don't need to install any gems.
Just install Ruby, launch your the favorite editor and try examples.
irb(main):005:0> require 'net/imap'
=> true
irb(main):006:0> imap = Net::IMAP.new('mail.example.com')


text:
Q: What is the correct method to wrap a heap of code into a variable I'm working with a shopping cart script that doesn't let me add php to the template files. The method used is to create $GLOBALS within the class files and call them from the tpl files. What I need to do is the following.
$GLOBALS['DiscountedPrice'] needs to be equal to that chunk of code that follows. I've tried a few syntax options to try and wrap it up, but it breaks because the same syntax is used inside the chunk of code.
$GLOBALS['DiscountedPrice'] =  $query = mysql_query("
             SELECT *
             FROM isc_customer_group_discounts
             WHERE `catorprodid` = '%%GLOBAL_ProductId%%'
             AND `customergroupid` = 1
             AND `discounttype` = 'PRODUCT'
             ");
$discounted_price = '';
while($proddisc = mysql_fetch_array($query)) {
    $discperc = $proddisc['4'];
    $discmeth = $proddisc['6'];
    if($discmeth = 'percent') {
        $discperc = $proddisc['4']/100;
        $discounted_price = $row['prodprice'] * $discperc;
        $GLOBALS['DiscountedPrice'] = $discounted_price;
    }elseif ($discmeth = 'price') {
        $discounted_price = $row['prodprice'] - $discperc;
        $GLOBALS['DiscountedPrice'] = $discounted_price;
    }elseif ($discmeth = 'fixed') {
        $discounted_price = $discperc;
        $GLOBALS['DiscountedPrice'] = $discounted_price;
    }};

A: $GLOBALS['DiscountedPrice'] .= $discounted_price;

Use a dot to concatenate the string as the loop goes round.  (no space between . and =)
EDIT.
Possibly I have not fully understood you question, but if you want to continually join strings this is what you'd do.
$discounted_price = ''; // you start with an empty string
while($proddisc = mysql_fetch_array($query)) {
$discperc = $proddisc['4'];
$discmeth = $proddisc['6'];
if($discmeth = 'percent') {
    $discperc = $proddisc['4']/100;
    $discounted_price = $row['prodprice'] * $discperc;
// and now you concat (join) it to the new value
    $GLOBALS['DiscountedPrice'] .= $discounted_price;
}elseif ($discmeth = 'price') {
    $discounted_price = $row['prodprice'] - $discperc;
    $GLOBALS['DiscountedPrice'] .= $discounted_price;
}elseif ($discmeth = 'fixed') {
    $discounted_price = $discperc;
    $GLOBALS['DiscountedPrice'] .= $discounted_price;
}};


text:
Q: Mediation analysis Baron and Kenny
I would be very grateful if someone could advise me as to why the indirect effect in this type of mediation analysis is made up of the product of a and b as opposed to the sum of a and b.
Thank you very much for any information.


text:
Q: Area calculations don't agree after raster to polygon conversion I have a landsat 8 image [UTM 19s] (30m resolution, so 900m sq per pixel).
I need to calculate the total area (hectares) from a land cover type.
I take the count of pixels from the attribute table, calculate field using the ([count]900).0001 to get total hectares.
As a check, I convert the raster to a polygon and do not simplify so that it returns polygons in a stepped fashion and shaped just like the pixels.This allows me to use the calculate geometry tool to populate an area field. This tool returns different values than the straight calculation from the raster itself. It is off by a few hundred hectares which is far too much for my reporting purposes.
How can I "convince" the two calculations to agree? is one method more precise than the other? I would be inclined to go with the straight conversion from the raster itself rather than relying on the arc tool to produce the areas...Thoughts or suggestions?


text:
Q: CORS Prelight Issue I am getting following error for a jQuery call to my azure app proxy
XMLHttpRequest cannot load https://azentsearchdev01-mytenant.msappproxy.net/search?text=mytext&type=json&callback=json_callback.
Response for preflight is invalid (redirect)
This is what I am doing

*

*From mytenantsite.sharepoint.com, making a call jQuery call to an Azure app on the folliwing url - https://azentsearchdev01-mytenant.msappproxy.net

*As part of the call, I am setting an authorization header with authentication token (access token) from Azure AD

*The jQuery call is fails with a 302 redirect to https://login.microsoftonline.com/
Here is my code

//authorization context
var resource = 'https://azentsearchdev01-mytenant.msappproxy.net/';
var endpoint = 'https://azentsearchdev01-mytenant.msappproxy.net/search?text=mytext&type=json&callback=json_callback';

var authContext = new AuthenticationContext({
        instance: 'https://login.microsoftonline.com/',
        tenant: 'mytenant.onmicrosoft.com',
        clientId: 'guid for client id',
        postLogoutRedirectUri: window.location.origin,
        cacheLocation: 'localStorage'
    });

//save tokens if this is a return from AAD
authContext.handleWindowCallback();

var user = authContext.getCachedUser();
if (user) {  //successfully logged in
    authContext.acquireToken("https://graph.windows.net", function (error, token) {
      if (error || !token) {
         jQuery("#loginMessage").text('ADAL Error Occurred: ' + error);
             return;
      }

      $.ajax({
        type: 'GET',
     url: endpoint,
  headers: {
           Accept: 'application/json',
           },
    beforeSend: function(xhr, settings) {
   xhr.setRequestHeader('Authorization','Bearer ' + token);
     }
        }).done(function (data) {
                jQuery("#loginMessage").text('success');
               }).fail(function (err) {
                jQuery("#loginMessage").text('Error calling endpoint: ' + err.statusText); **-->This is where the code lands**
               });

So far -
Based on what I have read, this is known gap in current state of how browsers handle a CORS preflight redirects. Reference link.
Question -
Are there any options to make a successful call to an app that requires cors preflight redirect?

A: To overcome the CORS issue for the Azure AD app proxy, we can develop a proxy for the Azure AD App proxy.
And if anyone want to Azure AD app proxy to support CORS, you can vote it through this link.


text:
Q: Read textfile line by line and scan from buffert - C I have made a program which handles and stores records of movies in a library. This is how my library looks like when I print it out to a file.
So basicly my problem is to read this file and save those columns in my struct of variables and dynamically increase the size of the struct for every entry.
Right now I have a while loop reading line by line into a buffert and I am then trying to scan the values from the buffert.
I know the format of the spacings in between the columns if that helps.(No it's not tabs, would that help?)
Else i thought about once it finds "two spaces" it could parse onto the next one...
What I'm looking for is something like this:
("%s %d %d %d %s %d", name, &id, &qty, &price, genre, &year)
This is how the textfile looks like: "test.txt" (UPDATED version below)
-------------------------------------------------------------------------------
NAME                                          ID    QTY   PRICE GENRE      YEAR
-------------------------------------------------------------------------------
THE SHAWSHANK REDEMPTION                      1     25    99    Crime      1994
THE GODFATHER                                 2     65    199   Crime      1972
PULP FICTION                                  3     265   99    Drama      1994
THE LORD OF THE RINGS                         4     1024  199   Action     2003
THE DARK KNIGHT                               5     99    99    Action     2008

And this is how my code looks like:
void read_from_file(struct movies *movie)
{
    FILE *fp;
    char buffer[1024];
    int line_num = 0;
    int index = 0;

    fp = fopen("test.txt", "r");

    if ( fp == NULL )
    {
        printf("Error opening file!\n");
        exit(1);
    }

    fgets(buffer, 1024, fp); fgets(buffer, 1024, fp); fgets(buffer, 1024, fp); // Skip 3 first lines (header)

    while(fgets(buffer, 1024, fp) != NULL) // read one line to buffer at a time
    {
        printf("%s", buffer); //DEBUG

        // Trying here to read only the names which i know should be no longer than 40chars. first row goes well, then it's messed up
        sscanf(buffer, "%40[^\0]" , movie[index].name);

        index++;
    }

    fclose(fp);
    getch();
}

Update: I changed the format of the storage file to the following:
THE SHAWSHANK REDEMPTION,1,25,99,Crime,1994
THE GODFATHER,2,75,199,Crime,1972
PULP FICTION,3,512,99,Drama,2000
THE LORD OF THE RINGS,4,1024,199,Action,2003
THE DARK KNIGHT,5,99,99,Action,2008

A: The main problem is that there is no single char delimiter.  So process the first 45 char;
while(fgets(buffer, sizeof buffer, fp) != NULL) {
  printf("%s", buffer); //DEBUG
  if (strlen(buf < 80)) {
    handle_short_line_error();
  }
  size_t len;
  for (len = 45; len > 0; len--) {
    if (!isspace(buf[len-1])) {
      break;
    }
  }
  if (!IsAGoodLength(len)) {
    handle_format_error();
  }
  memcpy(movie[index].name, buf, len);
  movie[index].name[len] = '\0';
  if (5 != sscanf(&buffer[45], "%d%d%d%9s%d", &id, &qty, &price, genre, &year)) {
    handle_format_error();
  }
  // Use other fields scanned
  index++;
}


text:
Q: Export from Excel to txt preserving especial date format I had been using a code to copy data from excel to .txt removing any unwanted characters, for input to another application:
Public DirRoot As String
Public CasNam As String

Public Sub Export()

    Dim intUnit As Integer
    Dim rngRow As Range
    Dim rngCell As Range
    Dim strText As String

    intUnit = FreeFile

    DirRoot = "C:\temp\"
    CasNam = "Test"

        Open DirRoot & CasNam & ".txt" For Output As intUnit

    'End If

    With Worksheets("Export").UsedRange
        For Each rngRow In .Rows
            strText = ""
            For Each rngCell In rngRow.Cells
                If Len(rngCell.Value) = 0 Then Exit For
                strText = strText & " " & rngCell.Value
            Next
            Print #intUnit, Trim(strText)
        Next
    End With

    Close intUnit

End Sub

Now I need to use it under a different set of data where one of the columns is a date with the format: yyyymmdd, when I apply the above code, I get that column with the format dd/mm/yyyy.
Is there any way I can preserve the original date format from excel to .txt?
Your help is highly appreciated!

A: Change this line
      strText = strText & " " & rngCell.Value

To
      strText = strText & " " &  Format(rngCell.Value,"yyyymmdd")

Good luck
EDIT
Please check this up. colCounter is to identify your format requeried column.
Dim colCounter as Integer
colCounter = 1
With Worksheets("Export").UsedRange
   For Each rngRow In .Rows
      strText = ""
      colCounter = 1
      For Each rngCell In rngRow.Cells
        If Len(rngCell.Value) = 0 Then Exit For
        If colCounter = 2  Then ' change 2 to whatever column you want to format
           strText = strText & " " &  Format(rngCell.Value,"yyyymmdd")
        Else
           strText = strText & " " & rngCell.Value
        End if
        colCounter = colCounter + 1
      Next
      Print #intUnit, Trim(strText)
   Next
End With

A: Not very clear to me which part declares the variable with the date, but this explanation may be helpful:
Sub Date_Convert

dim dtDate_Orig as date
dim dtDate_Convert as date
dim sDate as String

dtDate_Orig = "22/01/2012"
dtDate_Convert = format(dtDate_Orig, "yyyymmdd")
sDate = Cstr(dtDate_Convert)

'Now you can use the string for a filename

End Sub

A: Is this what you are trying?
'~~> Change this to the column which has dates
Col = 2

For Each rngCell In rngRow.Cells
    If Len(rngCell.Value) = 0 Then Exit For

    If rngCell.Column = Col Then
        strText = strText & " " & Format(rngCell.Value, "yyyymmdd")
    Else
        strText = strText & " " & rngCell.Value
    End If
Next


text:
Q: Remove duplicate lines with position delimiter I need a function javascript.
I have a list with format
abc|a|1
abc|a|2
abcd|a|1
abc|b|1

And i want to duplicate by first and second postion (split "|")
New list is:
abc|a|1
abcd|a|1
abc|b|1

Thank you so much

A: You could filter the data with Array#filter() and take a temporary object for lookup if there is already an item with the same two parts in the result.

var list = ['abc|a|1', 'abc|a|2', 'abcd|a|1', 'abc|b|1'],
    result = list.filter(function (a) {
        var b = a.split('|'),
            k = b[0] + '|' + b[1];
        if (!this[k]) {
            this[k] = true;
            return true;
        }
    }, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');


text:
Q: MYSQL: how to return value from column that has relation to values in another column Im struggling to articulate this, let alone execute in in MYSQL. How Do I return the userId X where userId.X and permissionId in (1,2,3,4,5,6,7,8) ?
The below example should return 6.
MariaDB [mailserver]> select * from user2permission;
+--------------+--------+
| permissionId | userId |
+--------------+--------+
|            1 |      5 |
|            1 |      6 |
|            2 |      6 |
|            2 |      7 |
|            3 |      6 |
|            4 |      6 |
|            5 |      6 |
|            6 |      6 |
|            7 |      6 |
|            8 |      6 |
+--------------+--------+

A: This kind of query can be written with the use of Group By clause and counting the instance as per the filteration applied in where clause
SELECT userId
FROM user2permission
WHERE permissionId  IN (1,2,3,4,5,6,7,8)
GROUP BY userId
HAVING COUNT(*) = 8

A: You want to only show users that have an entry for all required permissions. Two solutions spring to mind:
select *
from users
where userid in (select userid from user2permission where permissionid = 1)
  and userid in (select userid from user2permission where permissionid = 2)
  ...

and
select userid,
from user2permission
group by userid
having count(case when permissionid = 1 then 1 end) > 0
   and count(case when permissionid = 2 then 1 end) > 0
   ...

And when I say "spring" to mind, I mean exactly that = without much thinking :-) Rizwan's aggregation solution is what you should use.


text:
Q: SQL - Find specific value in a specific table Say I have a table called "Team" with the following columns:
ID, MemberName ,ManagerName,Title
And I would like to retrieve all rows where a value "John" exists.
Assume "John" exists in a row for the MemberName column, and that "John" would exist in another row under the "ManagerName" column.
Please assume would have large number of columns. Greater than 50, and do would not know where the value would fall under statically.

A: If you need an exact match for "John" you can use following query:
Select *
From Team
Where MemberName = 'John' or ManagerName = 'John'

If you need all rows where "John" could be a part of the string then you can use like:
Select *
From Team
Where MemberName like '%John%' or ManagerName like '%John%'

A: Generally, you need to specify all the columns your are searching from in SQL.
SELECT * FROM Team WHERE 'John' IN (col1, col2, col3, ..., colN) ;

However that depends.
If you are using MySQL you can Search Table Data. From the MySQL Workbench right click the table , and choose Search Table Data.
If you are using PostgreSQL take a look at the following:
https://stackoverflow.com/a/52715388/10436747


text:
Q: Oracle NoSQL Error : [ILLEGAL_ARGUMENT] PUT: Illegal Argument: Value should not be set for a generated always identity column: id I'm trying to update a row with the Node sdk and I keep getting Error: NoSQLArgumentError: [ILLEGAL_ARGUMENT] PUT: Illegal Argument: Value should not be set for a generated always identity column: id.
What am I doing wrong here?
async function update(id, data, table)
{
    var timestamp = new Date
    res = await client.putIfPresent(table, {
        id: id,
        last_modified: timestamp,
        json_document: data
    })
}

A: I've created this "Answer your own question" because the first time dealing with this error, I've decided to change ALL my code in order to use the SQL API and so use the UPDATE command. I was thinking that it was the only solution
It appears that you have created a table with an identity column for the field "id" and that you used "generate always." In this case, when you perform a put operation there must be no value set for "id" or you will get this error. Further, if you are trying to update (vs create) an existing row with an identity column you cannot use put() at all but must instead use an update query
In fact, We can use the command putIfPresent if the table was created using generate by default. In this case, the previous constraints will not apply
Oracle NoSQL supports the following options :

*

*GENERATED ALWAYS AS IDENTITY

*GENERATED BY DEFAULT AS IDENTITY

*GENERATED BY DEFAULT ON NULL AS IDENTITY

Depending your requirements, this is interesting to know


text:
Q: Как все элементы одного списка перенести в конец другого? Люди у меня появился вопрос, как все элементы одного списка перенести в конец другого без повторений.
mass_3 = [[2,3,4],[5,3,3],[8,9,3]]
mass_4 = []
truelen = "3"

for i4 in mass_3:
    mass_4.append("_")
    for i5 in i4:
        if str(i5) == str(truelen):
            f3 = [i6 for i6, ltr in enumerate(i4) if ltr == i5]
            print(f3)

#f3 = [1]
#f3 = [1,2]
#f3 = [1,2]

данных повторений быть не должно, но они почему то есть, а это для меня очень критично.

A: mass_3 = [[2,3,4],[5,3,3],[8,9,3]]
mass_4 = []
truelen = 3

for arr in mass_3:
    mass_4.append([i for i, el in enumerate(arr) if el == truelen])

print(mass_4)

A: Ну если решать основную задачу "все элементы одного списка перенести в конец другого без повторений", то это вроде работает:
mass_3 = [[2,3,4],[5,3,3],[8,9,3]]
mass_5 = []
for arr in mass_3:
    mass_5.extend(arr)

mass_x = list(set(mass_5))
print(mass_x)

даст
[2, 3, 4, 5, 8, 9]


text:
Q: How do I autoscale windows servers w/ amazon ec2 I'm building a distributed app which consists of a load balancer, web-server, database server, messaging queue, and backend workers. Workers consume messages off the queue, perform tasks and then update the database server. Ideally I'd like to have the ability to scale the workers based on some metric. I'm familiar with ec2, s3, cloudfront, but am new to VPC and auto-scaling.
My question is this: How do I go about setting up autoscaling windows servers based on a metric that I define. I have setup windows servers before on ec2, it's painful to RDP in, install cygwin, then ssh in, not very scalable IMO. I'd like them to be ephemeral if possible so I can save money on usage by scaling up and down. Any ideas / advice are greatly appreciated.
Thanks

A: Your link to how to create CloudWatch Alarms is indeed the mechanism you will wind up using if you go the Amazon Auto Scaling route. However, as you state yourself, setting up Windows servers can be quite painful -- not only is connecting to them and getting them up to the state you want rather slow, there is often also a considerable delay just getting them up and running in the first place (see Speeding up launch of Amazon EC2 Windows instances, for instance -- it's horrible).
To mitigate the pain a bit, you can create a custom Windows AMI. This lets you install your software on the machine so that it's already there when the instance comes up. Chef, the infrastructure management framework, works with Windows, so you can also go that route. Anything that makes life easier for you! If you combine the two, you can use Chef mostly for configuring software that you've already installed, saving you even more time.
However clever these approaches may be, there is still the slowness of getting Windows up and running on Amazon. If what you are auto scaling cannot deal with these delays and the instances not being up and running on time, you need a solution that can help plan ahead. Amazon's own CloudWatch service is reactive in nature, and lacks the ability to estimate future load. This gap in functionality is what caused Netflix to develop their own in-house predictive auto scaler Scryer (which is not available to the public), and what Elastisys offers in elastisys:scale, a product whose private beta one can request to join right now.
Full disclosure: I work for Elastisys AB, a company that creates auto-scaling solutions based on research performed in the Umeå University (Sweden) cloud research group.


text:
Q: Windows 8 Loop Issue after disk partitioning Hi I have some issue with my recently bought (few hours!) laptop. My laptop is a Sony Vaio running a Windows 8 64 bit. It has over 600GB disk size that I immediately decided to partition it into two. I used the EaseUS Partition Master to perform this and select to reduce the size of the main partition and divide it into two. The application force the OS to restart in order to complete the operation and then it goes to the loop where we select language and keyboard layout and all those options for repairing.
Using Window's DiskPartition, this is what I get:
DISKPART> sel disk 0

Disk 0 is now the selected disk.

DISKPART> list vol

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 0     E                       DVD-ROM         0 B  No Media
  Volume 1     C                NTFS   Partition    673 GB  Healthy
  Volume 2     D   Recovery     NTFS   Partition     23 GB  Healthy
  Volume 3                      FAT32  Partition    260 MB  Healthy    Hidden
  Volume 4         SONYSYS      NTFS   Partition    260 MB  Healthy    Hidden
  Volume 5         Windows RE   FAT32  Partition   1474 MB  Healthy    Hidden

From what I've read so far, it seems that something is wrong with my C volume. Firstly it needs to be in FAT32 and then secondly, it needs to be bootable (hence the missing Boot in the info section).
Can someone guide me on what should I enter in the command prompt to get this fixed? Thanks!


text:
Q: HABTM logic needed I have posts and tags and posts_tags tables.
I want to list tags in post on all posts. e.g
1 | Hello world | (hello,world,is,generic)

Getting all posts then watching on posts_tags for related tags and add them to posts.
So how can I get foreach post related tags, from tag table.

A: It should be retrieving related tags automatically when doing find on Posts. unless you have set the recursive property to 0 or -1. try increasing the value of recuresive