text:
Q: How can I stop these cars from hitting each other? I'm working on a simple traffic simulation for practice, as I'm fairly new to programming. I've gotten all I want to work so far, but when a car stops at a red light, the cars behind it just run into it and stack on top of each other.
Here is the general code where I call the cars:
private ArrayList<CarsRight> carsright = new ArrayList<CarsRight>();

public IntersectionSimulation() {
    for (int i = 0; i < 4; i++) {
        carsright.add(new CarsRight(i * -250));
    }
}

public void paint(Graphics g) {
    for (CarsRight cr : carsright) {
        Graphics2D g2d = (Graphics2D) g;
        cr.paint(g2d);
        tl.paint(g2d, mkl.b);   //tl is the traffic light (either green or red)
                                //mkl.b checks whether or not the spacebar is being pressed and changes the light accordingly
    }
}

public void move() {
    for (CarsRight cr : carsright) {
        cr.move(mkl.b);     //mkl.b checks whether or not the spacebar is being pressed and makes the cars move or stop accordingly
    }
)

And here is basically my CarsRight.java class:
public class CarsRight extends JPanel {
    int x;
    private int y = 330;
    private int a;
    private int speed = 20;
    int rgb = colorCode();
    private int height = 40;
    private int length = 100;

    public CarsRight(int i) {
        this.x = i;
    }

    void move(boolean b) {
        if (b == true) {
            x++;
            a = speed;
            x = x + a;
        }   //move if the light is green
        else {
            if (x > 300) {
                x++;
                a = speed;
                x = x + a;
            }
            else if (x < 250) {
                x++;
                a = speed;
                x = x + a;
            }
        }   //if the car is before the light, move up to the light, and if the car is past the light, keep going
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paint(g2d);

        for (int d = 0; d < 20; d++) {
            if (rgb == 1) {
                Color c = new Color(255, 255, 255);
                g2d.setColor(c);
            } else if (rgb == 2) {
                Color c = new Color(0, 0, 0);
                g2d.setColor(c);
            } else if (rgb == 3) {
                Color c = new Color(179, 179, 179);
                g2d.setColor(c);
            } else if (rgb == 4) {
                Color c = new Color(187, 10, 48);
                g2d.setColor(c);
            } else {
                Color c = new Color(182, 177, 169);
                g2d.setColor(c);
            }       //random color generator for car

            g2d.fillRoundRect(x, y, length, height, 10, 20);    //prints car
        }
    }
}

Once again, I have no clue how to approach this :/

A: I looked at your code and was able to solve your problem. You need relative distance between cars without which they would stack-up as it is right now.
I made changes to CarsRight flow. You can do similar changes for other cars.
MoveForLoopRight class in IntersectionSimulation:
public class MoveForLoopRight extends IntersectionSimulation {
        public void run() {
            // It is important to know the relative distance between each car. If not, your cars would stack on each other.
            int distance = 0;
            for (int i = 0; i< carsright.size(); i++) {
                CarsRight car = carsright.get(i);
                if (car.getX() <= 300) { // If they are before signal, move them till the line maintaining the distance
                    car.move(mkl.b, distance); // move method needs distance between cars
                    distance = distance + car.getLength() + 50; // 50 is the gap between each car
                } else {
                    car.move(mkl.b,  0); // these cars crossed the signal. They can move freely and don't need any distance
                }
            }
        }
    }

CarsRight.java changes:
@Override
public int getX() {
    return x;
}

public int getLength() {
    return length;
}

void move(boolean b, int distance) {
    if (b == true) {
        x++;
        a = speed;
        x = x + a;
    }
    else {
        if (x > 300) {
            x++;
            a = speed;
            x = x + a;
        }
        else if (x < (250 - distance)) {
            x++;
            a = speed;
            x = x + a;
        }
    }
}

Let me know how it went. Thanks!


text:
Q: Bcrypt - Ruby on Rails with Devise - Windows issue I'm having problems with bcrypt when either trying to start my rails server or attempting to login on the localhost.
I have played around by re-downloading/updating my Gem file with different versions of bcrypt and moving files around as per some of the github issues raised around this.
At the moment, my rails server starts, and when I login I get the error:

cannot load such file — 2.3/bcrypt_ext

And my Gem file has: gem 'bcrypt-ruby', '~> 3.0.0'
Any thoughts to get this working consistently on Windows?

A: Came across this github issue and the following seems to work

*

*Firstly uninstall bcrypt and bcrypt-ruby by running these two commands:
gem uninstall bcrypt and gem uninstall bcrypt-ruby

*Install it again with gem install bcrypt --platform=ruby

*In your Gemfile write gem 'bcrypt-ruby', '3.1.5', :require => 'bcrypt'

*Run bundle install

A: Okay I got this working by referring to the following answer: https://stackoverflow.com/a/33593911/6676900
The key steps are as follows:
1. Install Devkit from - http://rubyinstaller.org/downloads/ (NOTE: I had to use the 32 bit version even though I am running Windows 10 64 Bit)
2. Update my PATH variable to use the 32bit version of the Dev kit.  i.e. %DEVKIT_HOME%\bin (Where %DEVKIT_HOME% is the location of the extracted Dev Kit)
3. Follow the commands in the following answer: https://stackoverflow.com/a/33593911/6676900
Good to go!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi program resolution We have a Delphi 7 program running on Windows 7 Professional SP1, developed approximately 10 years ago. On the current system, it became unusable as some form elements have incorrect size so the text they contain doesn't fit there or the graph overflows the bottom of the window:
Picture 1: Table rows have incorrect size (or the text is bigger than it should be)

Picture 2: There is a graph in the window but the bottom part of the graph isn't visible. And there are no scrollbars...

We have no source code nor we do we have contact with the people who developed the software. We think the software was built in Delphi 7 because it uses several xxxx70.bpl libraries.
We tried to change resolution of the screen and change compatibility mode used to run the program with no luck.
Is there anything we can try?

A: Your program is not DPI aware, and you are running with font scaling settings that mean the application is asked to scale. The application font is scaled automatically but your Delphi application does not adapt.
I can see some options for you:

*

*Run your machine with 100% font scaling.

*Run your machine with >125% font scaling. Then DPI virtualization will kick in which should fix the issue. Although the app may appear fuzzy as it will suffer aliasing when scaled.

*Try to find a compat setting that forces DPI virtualization. Don't know if such a thing exists.

*Edit the .dfm resources in the executable to set the Scaled property to true. This would require a resource editor that understands Delphi. For instance XN resource editor. I've no idea whether or not this will work. If it does work, each form will re-scale themselves according to the font scaling.

Update
Forcing DPI virtualization won't help, on second thoughts. The system will tell your app that the font scaling is 125% and scale from there. But your app won't even handle 125% scaling correctly it seems. So you have little option other than to disable all font scaling or perhaps try with the Scaled property.


text:
Q: Как отправить js запрос заполняя данные на сайте
Пожалуйста, помогите отправить запрос на сайт, заполняя input (на другом сайте) и нажать на кнопку, тоже input
Любым способом пожалуйста

A: Если я правильно понял вопрос, то необходимо по запросу с одного сайта, заполнить данные на другом сайте. Для такой задачи можно использовать puppeteer (надеюсь правильно написал), если у конкретного сайта нет определённого API.


text:
Q: How do you get the DST time adjustment from a timezone? function isDST(d) {
    let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
    let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
    return Math.max(jan, jul) !== d.getTimezoneOffset();
}

I can use the above to get if current time currently applying the DST, but I would like a function where I can enter the time zone and get what is the offset that needs to be applied when DST is true. So basically most of the time it's +1 hour, and in all situation it's "+ some value", but I would like to know the value that needs to be applied when DST is true.
I need the offset.
moment.tz([2012, 0], 'America/Los_Angeles').format('Z');
-08:00

moment.tz([2012, 5], 'America/Los_Angeles').format('Z');
-07:00

-7 - -8 = +1 so the DST offset is 1 hour, but I can't use this example, because DST applies during different times depending on the region.

A: There is nothing like that built into the browser or JS core. You will need to use a library with a timezone database like Moment: https://momentjs.com/timezone/
moment.tz([2012, 0], 'America/Los_Angeles').format('Z');
// -08:00

moment.tz([2012, 5], 'America/Los_Angeles').format('Z');
// -07:00

A: We can create a function to get the UTC offset in minutes for a timezone for DST and standard time, getUTCOffset().
The difference between the two will be the DST adjustment in minutes.
Some zones such as Asia/Kolkata do not implement DST.
NB: This is almost always 60, for zones that implement DST. A couple of exceptions exist: Lord Howe Island (30 minutes) and Troll Station (120 minutes)

function toIso(date, timeZone) {
    return new Date(date).toLocaleString('sv', { timeZone } ).replace(' ', 'T').replace(',', '.');
}

function getUTCOffset(year, month, day, hour, minute, second, timeZone) {
    const date = [year, month, day].map(e => (e + '').padStart(2, '0')).join('-') + 'T' + [hour, minute, second].map(e => (e + '').padStart(2, '0')).join(':');
    const dt = Date.parse(date + 'Z');
    for(let offsetMinutes = -900; offsetMinutes <= 900; offsetMinutes += 15) {
        const test = new Date(dt - offsetMinutes * 60000);
        if (date === toIso(test, timeZone)) {
            return offsetMinutes;
        }
    }
}

function getDSTDetails(zone, year) {
    const jan = getUTCOffset(year, 1, 1, 0, 0, 0, zone);
    const jul = getUTCOffset(year, 7, 1, 0, 0, 0, zone);
    if (jan === jul) return { zone, year, standardOffsetMinutes: Math.min(jan, jul) }
    return { zone, year, standardOffsetMinutes: Math.min(jan, jul), dstOffsetMinutes: Math.max(jan, jul), dstChangeMinutes: Math.abs(jan - jul) }
}

console.log(getDSTDetails('Pacific/Auckland', 2022))
console.log(getDSTDetails('America/New_York', 2022))
console.log(getDSTDetails('America/Los_Angeles', 2022))
console.log(getDSTDetails('Asia/Kolkata', 2022))

// Exceptions to the rule...
console.log(getDSTDetails( 'Australia/Lord_Howe', 2022))
console.log(getDSTDetails( 'Antarctica/Troll', 2022))
.as-console-wrapper { max-height: 100% !important; }

And another, slightly different implementation just for fun:

function getUTCOffset(year, month, day, hour, minute, second, timeZone) {
    const date = [year, month, day].map(e => (e + '').padStart(2, '0')).join('-') + 'T' + [hour, minute, second].map(e => (e + '').padStart(2, '0')).join(':');
    const offsets = Array.from ({ length: 121 }, (_,n) => -900 + 15*n);
    return offsets.find(offsetMinutes => {
        return date === toIso(Date.parse(date + 'Z') - offsetMinutes * 60000, timeZone);
    });
}

function toIso(date, timeZone) {
    return new Date(date).toLocaleString('sv', { timeZone } ).replace(' ', 'T');
}

function getDSTDetails(zone, year) {
    const jan = getUTCOffset(year, 1, 1, 0, 0, 0, zone);
    const jul = getUTCOffset(year, 7, 1, 0, 0, 0, zone);
    if (jan === jul) return { zone, year, standardOffsetMinutes: Math.min(jan, jul) }
    return { zone, year, standardOffsetMinutes: Math.min(jan, jul), dstOffsetMinutes: Math.max(jan, jul), dstChangeMinutes: Math.abs(jan - jul) }
}

console.log(getDSTDetails('Pacific/Auckland', 2022))
console.log(getDSTDetails('America/New_York', 2022))
console.log(getDSTDetails('America/Los_Angeles', 2022))
console.log(getDSTDetails('Asia/Kolkata', 2022))

// Exceptions to the rule...
console.log(getDSTDetails( 'Australia/Lord_Howe', 2022))
console.log(getDSTDetails( 'Antarctica/Troll', 2022))
.as-console-wrapper { max-height: 100% !important; }


text:
Q: Saving coefficients and standard errors as variables I have run a regression and I would like to save the coefficients and the standard errors as variables.
I can see the coefficients with ereturn list and e(b) but I have trouble at getting the standard errors. Also, I don't really now how to turn those into variables. In the Stata manual they refer to [eqno] b[varname] and [eqno] se[varname] but there's no example and I can't figure out/find online how to use them.
Example where b1 is the regression coefficient for dependent variable 1, se1 is regression standard error for dependent var1:
name    year    output  var1    var2    b1  b2  se1 se2
a   1   0.72    0.74    0.87    0.64    0.15    0.48    0.62
a   2   0.61    0.75    0.33    0.64    0.15    0.48    0.62
a   3   0.08    0.61    0.85    0.64    0.15    0.48    0.62
b   1   0.02    0.22    0.26    0.64    0.15    0.48    0.62
b   2   0.8 0.32    0.51    0.64    0.15    0.48    0.62
b   3   0.47    0.68    0.79    0.64    0.15    0.48    0.62
c   1   0.56    0.12    0.63    0.64    0.15    0.48    0.62
c   2   0.35    0.49    0.53    0.64    0.15    0.48    0.62
c   3   0.93    0.65    0.97    0.64    0.15    0.48    0.62

Any help would be hugely appreciated!

A: An example to do it manually,
sysuse auto, replace
reg price mpg foreign trunk weight length
mata: b=st_matrix("e(b)")' // extracts e(b) into mata matrix b
mata: se=sqrt(diagonal(st_matrix("e(V)"))) // converts e(V) into se and placed in mata matrix se
getmata b se, force // force mata matrices into variables
list b se if b<.

Or to avoid mata, you could use,
sysuse auto, replace
reg price mpg foreign trunk weight length
ereturn list
mat b=e(b)' // transpose e(b) into matrix b
svmat double b, n(beta) // convert matrix b into variable beta1 (see help svmat)

mat V=e(V) // place e(V) in V
loca nv=`e(rank)' // count number of right hand variables
mat se=J(`nv',1,-9999) // create empty matrix for standard errors
forval i=1/`nv' {
    mat se[`i',1]=sqrt(V[`i',`i']) // convert the variances into the se one at a time
}
svmat double se, n(se) // convert matrix se into variable se1
list beta1 se1 if beta1<.

Not quite sure how you wanted the values to be arranged. If you like them in columns rather than rows (say you like to manually predict yhat), just transpose the matrices before running svmat. Only these three lines need to be modified.
mat b=e(b) // instead of "mat b=e(b)'"
mat se=J(1,`nv',-9999) // instead of "mat se=J(`nv',1,-9999)"
mat se[1,`i']=sqrt(V[`i',`i']) // instead of "mat se[1,`i']=sqrt(V[`i',`i'])"

A: Roger Newson at Imperial has written a nice package called parmest that will do this for you. Took me a while to work out the options but it works very nicely.


text:
Q: How do I link a compiled ".so" library with Scons? I have an existing .so library (libgit2), and I would like to use this within a C program (the build system is Scons). I read through the entirety of the Scons documentation for "Chapter 4. Building and Linking with Libraries", but there is no mention of how to use an existing .so library. The only mention of .so in the entirety of chapter 4 is on the first page, and it is only about Scons using a .so file for output. How do I use an existing compiled .so library in Scons?

A: If you are using an sconscript then you should add a LIBS= arguments and a LIBS_PATH=.
if you want to directly add it to the build line, use -L for lib path and -l to link a lib.
You can find further information here: https://scons.org/doc/0.97/HTML/scons-user/x628.html

A: With help from the SCons Discord server and other places, I've gotten farther than when I first posted this question. I haven't solved my specific problem of using .so libraries with GDNative, but I think I've figured out the SCons side.
As of me posting this question, the SConstruct file was able to compile working code if I didn't use libgit2 and instead just printed out the text. With only the header included, my test call to git_libgit2_version compiled but didn't run, as Godot said undefined symbol: git_libgit2_version.
First of all, you need to add the named parameter for LIBS to your env.SharedLibrary or env.Program line. The lib prefix and .so suffix seem to be added automatically, I still haven't figured out how to make it point to libgit2.so.1.0.1 (so for now I have the library copied and named as libgit2.so, but I would like to have it point to libgit2.so.1.0.1 eventually instead). Also, the SCons team suggested adding LIBPATH, but this doesn't seem to actually do anything.
library = env.SharedLibrary(target=env["target_path"] + env["target_name"] , source=sources, LIBS=['git2'])

Then, the SConstruct file needs to have this magic line:
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1

With the above code, ldd will report not found, and Godot will say Error: libgit2.so.1.0: cannot open shared object file: No such file or directory (I have no idea why it's asking for .so.1.0 instead of the .so or .so.1.0.1 file, and yes I tried copying and naming as libgit2.so.1.0 and that doesn't change anything either).
I also added this, which was suggested by another GDNative user.
env.Append(LINKFLAGS=[
    '-Wl,-rpath,addons/git_for_godot/gdnative/linuxbsd'
])

With all of the above code, this seems to allow ldd and Godot to find the library just fine with a relative path (when running ldd you have to be cd'd into the project folder). I can run the project fine without any errors, but the project crashes immediately after opening, with no error messages printed. If I comment out the call to git_libgit2_version but keep the header included, the file does compile and run. Any time I try to call anything from libgit2 it causes Godot to crash without printing any errors. At this point I'm stuck and I don't know what I'm doing wrong.
I did try adding libgit2 to the Dependencies section of the .gdnlib file, but this doesn't seem to affect anything. Another thing I tried which didn't work is this line (+ variants on the extension) which append to the sources list passed as the named source parameter. I'll post it here for completeness, but for the moment I have this line commented out because it doesn't work:
sources.append(File("project/addons/git_for_godot/gdnative/linuxbsd/libgit2.so"))


text:
Q: InstagramAPI - How to Parse JSON Python Data into Pandas DataFrame (iPython, Jupyter Notebook) This is the python script i've built, in Jupyter Notebook, to query my own Instagram handle, but I cannot seem to get all of the data into a pandas dataframe, can anyone help me?
    from instagram.client import InstagramAPI
    import pandas as pd
    import requests
    import json

    access_token = "xxxx"
    client_secret = "xxxx"

    recentMediaResponse = requests.get("https://api.instagram.com/v1/users/self/media/recent/",params = {"access_token": access_token})
    recentMediaJson = json.loads(recentMediaResponse.text)

    DataDF = pd.DataFrame(columns = ['numComments', 'likes', 'id', 'tags'])

    numcomments = pd.DataFrame({'numComments' : [recentMediaJson['data'][1]['comments']['count']],
                               'likes': [recentMediaJson['data'][1]['likes']['count']],
                               'id': [recentMediaJson['data'][1]['id']],
                               'tags': [recentMediaJson['data'][1]['tags']]

                               })
    Final = DataDF.append(numcomments)
    print Final

When I print the 'Final' variable i only get one id and all of the corresponding data values/strings :

I know there's a lot of data because this is how the 'recentMediaJson' file looks:

A: In this section I think you are selecting the first element in the list of dictionaries recentMediaJson['data'][1]. You will need to loop through all entries in the list and append numcomments each time to DataDF.
numcomments = pd.DataFrame({'numComments' : [recentMediaJson['data'][1]['comments']['count']],
                                   'likes': [recentMediaJson['data'][1]['likes']['count']],
                                   'id': [recentMediaJson['data'][1]['id']],
                                   'tags': [recentMediaJson['data'][1]['tags']]

Also you can visualize the json object that the api is returning much easier using pprint. Try importing pprint and running pprint.pprint(recentMediaJson) and you will be able to see the structure much better.

A: You are only including one record from the JSON data.
I got my answer from here: JSON to pandas DataFrame
This is untested, but something like this should work.
data = json.loads(recentMediaResponse.text)
numComments,likes,id,tags = [],[],[],[]
for result in data['results']:
    numcomments.append(result['comments']['count'])
    likes.append(result['likes']['count'])
    id.append(result['id'])
    tags.append(result['tags'])
df = pd.DataFrame([numcomments,likes,id,tags]).T
print df


text:
Q: Windows 10 Start menu: "These results may be incomplete", won't find settings When searching in the Start menu of Windows 10, the results usually include items from the System Settings app. On a fresh install of Windows 10 Enterprise, either 1607 or 1511, this works as expected for the first user to logon.
After going through Windows update and creating a second local user (or, if joined to a domain, using a domain user to logon), Search doesn't work for this user. Results will not include any items from System settings.
This question already proposes a lot of troubleshooting of which I already tried everything. Maybe the most interesting thing is that the folder %LOCALAPPDATA%\Packages\windows.immersivecontrolpanel_cw5n1h2txyewy\LocalState stays empty, while the same folder is populated with files in the first user's profile. Copying those files over makes search work, however, this is more of a workaround than an actual solution.
This might be related to a recent update, because both 1511 and 1607 without any updates installed are behaving correctly. I'm also using the German version of Windows, however, changing Language packs did not change search behaviour.


text:
Q: How to duplicate the list value and append back to the same list? For example if:
List = [1,2,3,4,5]

I want like this:
List = [1,1,2,2,3,3,4,4,5,5]

A: Try this:
li = [1,2,3,4,5]

print(sorted(li+li))

A: you can use zip with chain(for flatten):
from itetools import chain

List = list(chain(*zip(List,List)))
print(List)

output:
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

or you can use a for loop:
new_list = []
for n in List:
    new_list.extend([n, n])

List = new_list
print(new_list)

output:
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

A: You can zip the list with itself:
[i for t in zip(List, List) for i in t]

A: Maybe this, if there is no notion of sorting:
myList = [1,2,3,4,5]

for idx in range(0, len(myList)*2, 2):
  myList.insert(idx+1, myList[idx])

print(myList)

A: You can use extend. If you want to preserve the order.
l = [2,1,3,5,6]
res = []
for i in l:
    res.extend((i, i))
print(res)

output
[2, 2, 1, 1, 3, 3, 5, 5, 6, 6]

res = []
l = [None, True, 5, 1, 8]
for i in l:
    res.extend((i, i))
print(res)

output
[None, None, True, True, 5, 5, 1, 1, 8, 8]


text:
Q: Compiler error: (enumerated class) was not declared in this scope I am attempting to compile the following program that utilizes an enumerated class called Noun. It takes input in from a string and enumerates the data using a map.
The following is in the header file that defines the enumerated class:
nouns.h
#ifndef NOUNS_H
#define NOUNS_H

#include <iostream>
#include <map>          //std::map
#include <string>       //std::string

#include "classes.h"    // where classes are stored
#include "functions.h"  // standard functions kept here
#include "cmdtree.h"    // where the arguments from these functions are sent

enum class Noun
{
    name,
    /* other nouns */
    invalid
};

std::map < std::string, Noun > knownNouns =
{
    {   "name",         Noun::name          },
    /* more stuff in the map */
    {   "suspect",      Noun::suspect       }
};

Noun parseNoun(std::string &noun)
{
    auto n = knownNouns.find(noun);
    if ( n == knownNouns.end() ) {
        return Noun::invalid;
    }
    return n->second;
}

void ask (Noun noun);
void look (Noun noun);

#endif  /* NOUNS_H */

When I compile, I get a number of errors:
In file included from functions.h:16:0,
                 from classes.h:15,
                 from nouns.h:37,
                 from nouns.cpp:1:
verbs.h:44:15: error: 'Noun' was not declared in this scope
 int verbProc (Noun noun, Verb verb);
               ^
verbs.h:44:31: error: expected primary-expression before 'verb'
 int verbProc (Noun noun, Verb verb);
                               ^
verbs.h:44:35: error: expression list treated as compound expression in initializer [-fpermissive]
 int verbProc (Noun noun, Verb verb);
                                   ^
In file included from classes.h:15:0,
                 from nouns.h:37,
                 from nouns.cpp:1:
functions.h:23:32: error: 'Noun' has not been declared
 char validateInput (Verb verb, Noun noun);
                                ^

In verbs.h, where it tells me "noun" is not declared in scope, I look at my header file...
verbs.h:
#ifndef VERBS_H
#define VERBS_H

#include <iostream>
#include <map>
#include <string>

#include "nouns.h"
#include "classes.h"
#include "functions.h"
/*
 * See the nouns.h header for better documentation on what exactly this
 * is doing.
 */

    enum class Verb
    {
        ask,        // first verb
        /* other verbs */
        invalid     // last verb

    };

    std::map < std::string, Verb > knownVerbs =
    {
        {   "ask",      Verb::ask       },
        /* other stuff in map */
        {   "examine",  Verb::look      }
    };

    Verb parseVerb(const std::string &verb);
    int verbProc (Noun noun, Verb verb);        // <-- function where Noun is "undeclared."

    #endif  /* VERBS_H */

A similar nondelared error is in "functions.h":
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <iostream>
#include <string>
#include <cstring>

#include "classes.h"
#include "verbs.h"
#include "nouns.h"
#include "classes.h"
#include "cmdtree.h"

void localPause ();
void readInput (char* &command, const int MAXL, std::string &noun, std::string &verb);
char verifyExit(char exitChoice);
char validateInput (Verb verb, Noun noun); //  <-- error here, "Noun has not been declared"
void initializeSuspect();
void introduction();

#endif  /* FUNCTIONS_H */

Can anyone spot something that I cannot?


text:
Q: Angular2 - Not able to data bind when property is changed from different component (plunker example) I want to create an ErrorComponent responsible to display any error message for the entire application on the top of the page. So, naturally I was wondering about something like:

<my-app>
    <error-app></error-app>

</my-app>

I have a Pluker website which illustrate the problem: http://plnkr.co/edit/wYy4gl
I want to be able to add an error from anywhere calling the ErrorComponent. As in:

// File app/app.component.ts
onSelect(hero: Hero) {
    this.selectedHero = hero;
    this.errorComp.addError(hero.name);
}

The alert shows the errors being added to errors:

// File app/error-app.component.ts
addError(e:string) {
    this.errors.push(e);
    alert("Errors:" + this.errors + "| AddeError: " + e);
}

But the list {{errors}} is not being updated by some reason:

// File app/error-app.component.ts

{{errors}}

Any help is appreciated.

A: Instead of
{{errors}}
 try this:

{{error}}

Also, you referenced your error component in the wrong way.
Instead of injecting it via DI you should use @ViewChild, like so:
import { Component, ViewChild } from '@angular/core';

// ....

@Component({
  selector: 'my-app',
  directives: [ ErrorAppComponent],
  //providers: [ErrorAppComponent ],
  template: `

Error list

    <error-app #error></error-app>

Click bellow to add to the error list

         {{hero.name}}

  `
})
export class AppComponent {
  constructor() { }
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero: Hero;
  @ViewChild("error") errorComp;

  onSelect(hero: Hero) {
    this.selectedHero = hero;
    this.errorComp.addError(hero.name);
  }
}


text:
Q: How to create a Datalake using Apache Kafka, Amazon Glue and Amazon S3? I want to store all the data from a Kafka's topic into Amazon S3. I have a Kafka cluster that receives in one topic 200.000 messages per second, and each value message has 50 fields (strings, timestamps, integers, and floats).
My main idea is to use Kafka Connector to store the data in a bucket s3 and after that use Amazon Glue to transform the data and keep it into another bucket. I have the next questions:
1) How to do it? That architecture will work well? I tried with Amazon EMR (Spark Streaming) but I had too many concerns How to decrease the processing time and failed tasks using Apache Spark for events streaming from Apache Kafka?
2) I tried to use Kafka Connect from Confluent, but I have a few questions:

*

*Can I connect to my Kafka Cluster from other Kafka instance and
run in a standalone way my Kafka Connector s3?

*What means this error "ERROR Task s3-sink-0 threw an uncaught an
unrecoverable exception"?

ERROR Task s3-sink-0 threw an uncaught and unrecoverable exception
  (org.apache.kafka.connect.runtime.WorkerTask:142)
  java.lang.NullPointerException    at
  io.confluent.connect.hdfs.HdfsSinkTask.close(HdfsSinkTask.java:122)
    at
  org.apache.kafka.connect.runtime.WorkerSinkTask.commitOffsets(WorkerSinkTask.java:290)
    at
  org.apache.kafka.connect.runtime.WorkerSinkTask.closePartitions(WorkerSinkTask.java:421)
    at
  org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:146)
    at
  org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:140)
    at
  org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:175)
    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745) [2018-10-05 15:32:26,086]
  ERROR Task is being killed and will not recover until manually
  restarted (org.apache.kafka.connect.runtime.WorkerTask:143)
  [2018-10-05 15:32:27,980] WARN could not create Dir using directory
  from url file:/targ. skipping. (org.reflections.Reflections:104)
  java.lang.NullPointerException    at
  org.reflections.vfs.Vfs$DefaultUrlTypes$3.matches(Vfs.java:239)   at
  org.reflections.vfs.Vfs.fromURL(Vfs.java:98)  at
  org.reflections.vfs.Vfs.fromURL(Vfs.java:91)  at
  org.reflections.Reflections.scan(Reflections.java:237)    at
  org.reflections.Reflections.scan(Reflections.java:204)    at
  org.reflections.Reflections.(Reflections.java:129)  at
  org.apache.kafka.connect.runtime.AbstractHerder.connectorPlugins(AbstractHerder.java:268)
    at
  org.apache.kafka.connect.runtime.AbstractHerder$1.run(AbstractHerder.java:377)
    at java.lang.Thread.run(Thread.java:745) [2018-10-05 15:32:27,981]
  WARN could not create Vfs.Dir from url. ignoring the exception and
  continuing (org.reflections.Reflections:208)
  org.reflections.ReflectionsException: could not create Vfs.Dir from
  url, no matching UrlType was found [file:/targ] either use
  fromURL(final URL url, final List urlTypes) or use the static
  setDefaultURLTypes(final List urlTypes) or
  addDefaultURLTypes(UrlType urlType) with your specialized UrlType.    at
  org.reflections.vfs.Vfs.fromURL(Vfs.java:109)     at
  org.reflections.vfs.Vfs.fromURL(Vfs.java:91)  at
  org.reflections.Reflections.scan(Reflections.java:237)    at
  org.reflections.Reflections.scan(Reflections.java:204)    at
  org.reflections.Reflections.(Reflections.java:129)  at
  org.apache.kafka.connect.runtime.AbstractHerder.connectorPlugins(AbstractHerder.java:268)
    at
  org.apache.kafka.connect.runtime.AbstractHerder$1.run(AbstractHerder.java:377)
    at java.lang.Thread.run(Thread.java:745) [2018-10-05 15:32:35,441]
  INFO Reflections took 12393 ms to scan 429 urls, producing 13521 keys
  and 95814 values  (org.reflections.Reflections:229)

*

*If you can resume the steps to connect to Kafka and keep on s3 from
another Kafka instance, how will you do?

*What means all these fields key.converter, value.converter, key.converter.schemas.enable, value.converter.schemas.enable, internal.key.converter,internal.value.converter, internal.key.converter.schemas.enable,  internal.value.converter.schemas.enable?

What are the possible values for key.converter, value.converter?
3) Once my raw data is in a bucket, I would like to use Amazon Glue to take these data, to deserialize Protobuffer, to change the format of some fields, and finally to store it in another bucket in Parquet. How can I use my own java protobuffer library in Amazon Glue?
4) If I want to query with Amazon Athena, how can I load the partitions automatically (year, month, day, hour)? With the crawlers and schedulers of Amazon Glue?

A: We use S3 Connect for hundreds of topics and process data using Hive, Athena, Spark, Presto, etc. Seems to work fine, though I feel like an actual database might return results faster.
In any case, to answer about Connect

Can I connect to my Kafka Cluster from other Kafka instance and run in a standalone way my Kafka Connector s3?

I'm not sure I understand the question, but Kafka Connect needs to connect to one cluster, you don't need two Kafka clusters to use it. You'd typically run Kafka Connect processes as part of their own cluster, not on the brokers.

What means this error "ERROR Task s3-sink-0 threw an uncaught an unrecoverable exception"?

It means you need to look at the logs to figure out what exception is being thrown and stopping the connector from reading data.
WARN could not create Dir using directory from url file:/targ ... If you're using HDFS connector, I don't think you should be using the default file:// URI

If you can resume the steps to connect to Kafka and keep on s3 from another Kafka instance, how will you do?

You can't "resume from another Kafka instance". As mentioned, Connect can only consume from a single Kafka cluster, and any consumed offsets and consumer groups are stored with it.

What means all these fields

These fields are removed from the latest Kafka releases, you can ignore them. You definitely should not change them
internal.key.converter,internal.value.converter, internal.key.converter.schemas.enable, internal.value.converter.schemas.enable
These are your serializers and deserializers like the regular producer consumer API have
key.converter, value.converter
I believe these are only important for JSON converters. See https://rmoff.net/2017/09/06/kafka-connect-jsondeserializer-with-schemas-enable-requires-schema-and-payload-fields
key.converter.schemas.enable, value.converter.schemas.enable

to deserialize Protobuf, to change the format of some fields, and finally to store it in another bucket in Parquet

Kafka Connect would need to be loaded with a Protobuf converter, and I don't know there is one (I think Blue Apron wrote something... Search github).
Generally speaking, Avro would be much easier to convert to Parquet because native libraries already exist to do that. S3 Connect by Confluent doesn't currently write Parquet format, but there in an open PR. The alternative is to use Pinterest Secor library.
I don't know Glue, but if it's like Hive, you would use ADD JAR during a query to load external code plugins and functions
I have minimal experience with Athena, but Glue maintains all the partitions as a Hive metastore. The automatic part would be the crawler, you can put a filter on the query to do partition pruning

A: To complement @cricket_007's answer

Can I connect to my Kafka Cluster from other Kafka instance and run in a standalone way my Kafka Connector s3?

Kafka S3 Connector is part of the Confluent distribution, which also includes Kafka, as well as other related services, but it is not meant to run on your brokers directly, rather:

*

*as a standalone worker running a Connector's configuration given when the service is launched

*or as an additional workers' cluster running on the side of your Kafka Brokers' cluster. In that case, interaction/running of connectors is better via the Kafka Connect REST API (Search for "Managing Kafka Connectors" for documentation with examples)

If you can resume the steps to connect to Kafka and keep on s3 from
  another Kafka instance, how will you do?

Are you talking about another Kafka Connect instance?

*

*if so, you can simply execute the Kafka Connect service in distributed mode which was meant to give the reliability you seem to be looking for...

Or do you mean another Kafka (brokers) cluster?

*

*in that case, you could try (but that would be experimental, and I haven't tried it myself...) to run Kafka Connect in standalone mode and simply update bootstrap.servers parameter of your connector's configuration to point to the new cluster. Why that might work: in standalone mode the offsets of your sink connector(s) are stored locally on your worker (contrarily to distributed mode where the offsets are stored on the Kafka cluster directly...). Why that might not work: it's simply not intended for this use and I'm guessing you might need your topics and partitions to be exactly the same...?

What are the possible values for key.converter, value.converter?

Check Confluent's documentation for kafka-connect-s3 ;)

How can I use my own java protobuffer library in Amazon Glue?

Not sure of the actual method, but Glue jobs spawn off an EMR cluster behind the scenes so I don't see why it shouldn't be possible...

If I want to query with Amazon Athena, how can I load the partitions automatically (year, month, day, hour)? With the crawlers and schedulers of Amazon Glue?

Yes.
Assuming a daily partitioning, you could actually have you're schedule run the crawler first thing in the morning, as soon as you can expect new data to have created that day's folder on S3 (so at least one object for that day exists on S3)... The crawler will add that day's partition which will then be available for querying with any newly added object.


text:
Q: Magento 2 graphql integration with Amazon Pay I am trying to implement payment for Amazon Pay in Magento 2.4 using graphql. Magento documentation provides steps for Pay Pal (e.g. PayPal Express Checkout: https://devdocs.magento.com/guides/v2.4/graphql/payment-methods/paypal-express-checkout.html). For Pay Pal works. How to implement this for Amazon Pay?
When I try to call
mutation {
  setPaymentMethodOnCart(input: {
cart_id: "EUZwlk3kflddMgPoGe6KVDjcWm5CEgid"
    payment_method: {
      code: "amazon_payment"
    }
  }) {
    cart {
    selected_payment_method {
        code
        title
      }
    }
  }
}

then I get the error:
[2020-10-15 11:31:46] main.ERROR: Call to a member function getAmazonOrderReferenceId() on null {"exception":"[object] (GraphQL\\Error\\Error(code: 0): Call to a member function getAmazonOrderReferenceId() on null at /var/www/magento2/vendor/webonyx/graphql-php/src/Error/Error.php:174, Error(code: 0): Call to a member function getAmazonOrderReferenceId() on null at /var/www/magento2/vendor/amzn/amazon-pay-module/Plugin/ConfirmOrderReference.php:109)"} []


text:
Q: render multiple markdown docs to HTML using editor.md I have such a template

        <textarea style="display:none;">
{{ article.content }}
        </textarea>

Which could be rendered as html using editor.md:
$(function(){
      editormd.markdownToHTML("article-editormd-view", {
      htmlDecode      : "style,script,iframe",  // you can filter tags decode
      emoji           : true,
      taskList        : true,
      lineNumbers     : false,
    });

article-editormd-view is ID,
When I tried to render multiple comments in a for loop like:
{% for comment in page.object_list %}

    <textarea style="display:none;">
 {{ comment.body }}
    </textarea>

{% endfor %}

editormd.markdownToHTML("comment-editormd-view", {
htmlDecode      : "style,script,iframe",  // you can filter tags decode
emoji           : true,
taskList        : true,
lineNumbers     : false,

It's not working,
I read through the official docs but not found a solution there.

A: comment-editormd-view is supposed to be the element's ID. So, your first example of a single textbox works because you've set it as the element's ID.
However, when you tried doing it with a for loop, you set it as element's class. So, editor.md is trying to work its magic on a single element with the selector #comment-editormd-view, rather than on all elements with the selector .comment-editormd-view.
A possible solution is simply by using a counter, with a different ID per div and a script that creates a textbox for each div. Something like this (code untested):

{% for comment in page.object_list %}

    <textarea style="display: none">
      {{ comment.body }}
    </textarea>

{% endfor %}

HTML element IDs: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
HTML element classes: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class


text:
Q: Cannot connect my nodejs to mysql My code is as below
    var JDBC = require('jdbc');
var jinst = require('jdbc/lib/jinst');
var Pool = require('jdbc/lib/pool');

// isJvmCreated will be true after the first java call.  When this happens, the
// options and classpath cannot be adjusted.
if (!jinst.isJvmCreated()) {
    // Add all java options required by your project here.  You get one chance to
    // setup the options before the first java call.
    jinst.addOption("-Xrs");
    // Add all jar files required by your project here.  You get one chance to
    // setup the classpath before the first java call.
    jinst.setupClasspath(['./jars/mysql-connector-java-5.1.38-bin.jar']);
}
var mySql = new JDBC({
    url: 'jdbc:mysql://localhost:3306/nodejs',
    drivername: 'com.mysql.jdbc.Driver',
    minpoolsize: 5,
    maxpoolsize: 10,
    user: 'root',
    password: 'root'
});
mySql.initialize(function(err) {
    if (err) {
        console.log(err);
    }
});

I have the jar in the folder and mysql running in my local. But i am getting the following error
    java.lang.NoClassDefFoundError: com/mysql/jdbc/Driver
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
] cause: nodeJava_java_lang_NoClassDefFoundError {} }
{ [Error: Error running static method
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/nodejs
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
] cause: nodeJava_java_sql_SQLException {} }

Please help. Is there any initialisation commands neede in nodejs?

A: I tried your code exactly and it works, I think your path is setupClasspath() is not good. Try using an absolute path, a relative path works only if the working directory is set like you expect:
if (!jinst.isJvmCreated()) {
    jinst.addOption("-Xrs");
    jinst.setupClasspath([__dirname + '/jars/mysql-connector-java-5.1.38-bin.jar']);
}


text:
Q: How can I pass content to a parent template from a child template in Silverstripe I want to pass some content from a elemental block up to a parent template (to change the page header)   - Is this possible?  I don't have any example code for what I'm trying because I don't have any idea how to implement it.
This would be similar to the content_for facility in Rails / ERB templates.
Parent:
Page Title <%= yield :title %>

Child Template:
<% content_for :title do %>
  <b>, A simple page</b>
<% end %>

Is there anything like this or some other way to do this in SS templates?

A: Silverstripe Templates are a one-way street - you can't pass values upstream.
What you can do in this case is add a method to the page object to fetch the correct title from the block:
public function getTitleForTemplate()
{
  return $this->MyBlock->PageTitle;
}

And then in your template you can simply call that method or as in this example treat it like a property:
Page Title $TitleForTemplate

If you want to use a template to render out this property (e.g. if you have different styling or markup for different blocks which belong to different pages) you can render the template in that method. There are many ways to do this but perhaps the most sensible would be to call renderWith() on the block object:
public function getTitleForTemplate()
{
  return $this->MyBlock->renderWith(['type' => 'Includes', 'templates' => ['MyBlockTitle']);
}

and then have a template in your theme's templates/Includes directory called MyBlockTitle.ss which renders out the title with any styling and markup you need for it.
In other words: data belongs in models, the template is just there to display that data. So if you need some specific data to be displayed in the page template, the page object should have that data available.
Disclaimer: I haven't tested this code, it was done from memory. Some of the syntax especially for the second example may be slightly different in reality.

A: To expand on Guy's answer, to find the block i wanted to use to add to the page title and breadcrumbs, I used the ElementalArea and it's Elements.
public function getTitleForTemplate(){
    $output = ""    ;
    foreach( $this->ElementalArea->Elements() as $element ){
      if($element->ClassName == 'MySite\AwardsElement'){
        if ( $element->Award() ){
          $output .= "{$element->Award()->title } ";
        }
      }
    }
    return $output;
}


text:
Q: C# parse non uniform bit sequences from array of bytes Question: Is there a more efficient way to parse bits out of a byte array to integer values? If so, what would that be?
Data is currently read off a stream with a packet consisting of a series of bytes (which are held in a byte array).  The data is compressed in these bytes such that a value may spread across multiple bytes (in sequence).  The bits making up the values vary in size depending on the "type" of packet (which is held in the first 5 bits (starting with MSB) of the first byte. E.g.,
byte[] bytes = {0x73, 0xa4};
// yields: 0111001110100100
// vals:   [ 1 ][  2  ]3[4]

Currently I use an extension method:
public static string ConvertToBinaryString(this byte[] bytes)
{
    return string.Join("", bytes.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));
}

to convert the byte array to a binary string.  Then I use one of these two extension methods to convert the binary string into an int or array of int:
static readonly Regex IsBinary = new Regex("^[01]{1,32}$", RegexOptions.Compiled);
public static bool TryParseBits(this string toParse, int start, int length, out int intVal)
{
    intVal = -1;
    if (!IsBinary.IsMatch(toParse)) return false;
    if ((start + length + 1) > toParse.Length) return false;
    intVal = Convert.ToInt32(toParse.Substring(start, length), 2);
    return true;
}
public static bool TryParseBits(this string toParse, Queue<int> lengths, out List<int> vals)
{
    vals = new List<int>();
    if (!IsBinary.IsMatch(toParse)) return false;
    var idx = 0;
    while (lengths.Count > 0)
    {
        var l = lengths.Dequeue();
        if ((idx + l) > toParse.Length) return false;
        vals.Add(Convert.ToInt32(toParse.Substring(idx, l), 2));
        idx += l;
    }
    return true;
}

Example Use:
int type;
var success = "0111001110100100".TryParseBits(0, 5, out type);

results in type = 14
Background: The stream that is being read can deliver up to 12 packets/second.  There is some preprocessing that occurs prior to the having to parse the bytes and there is significant post processing that occurs on the values.  The data packets are split across four threads using Parallel.ForEach.  The values are never greater than 28 bits so I don't worry about a sign bit when converting to int.

A: Have you tried something like a bitmask?
Knowing that for eg last 4 bits of the first byteArray is our first val we can do:
byte[] bytes = { 0x73, 0xa4 };
int v1 = bytes[0] & 0x0F;
//second val:
int v2 = bytes[2] & 0xF0;

OR
Before applying a mask just store everything in a lager nr.
 int total = 0;
 total = total | bytes[0];
 total = total << 8;
 total = total | bytes[1];
 //now the 2 bytes array is stored in a number in our case total will be: 111001110100100
 //after storing apply bit masks as described above:
 // to get the LAST 3 bytes
 int var1 = total & 0x7 //mask with last 3 bytes
 total = total >> 3; //take out last 3 bytes
 int var2 = total & 0x1 //last byte.
 total = total >>1;
 //and so on

A: For completeness, this is what I came up with based on an answer that was apparently deleted.
public static int ParseBits(this byte[] bytes, int start, int length)
{
    // Need to reverse the array to make it usable with BitArray
    Array.Reverse(bytes);
    var ba = new BitArray(bytes);
    var idx = 0;
    var shft = length - 1;
    // Iterate backwards through the bits and perform bitwise operations
    for (var i = start + length - 1; i >= 0; i--)
    {
        idx |= (Convert.ToInt32(ba.Get(i)) << shft);
        shft--;
    }
    return idx;
}

A: you just need to learn about bitwise operations.
byte[] bytes = {0x73, 0xa4};
// yields: 0111001110100100
// vals: [ 1 ][ 2 ]3[4]

int bits = bytes[1] | bytes [0] << 8;
int v1 = (bits & 0xf800) >> 11;
int v2 = (bits & 0x07f0) >> 5;
int v3 = (bits & 0x0008) >> 3;
int v4 = bits & 0x0007;


text:
Q: Setting the order of XML attributes via XSLT? I have HTML in XML format which I am parsing using XSLT. My HTML looks like this:

<meta charset="utf-8" />
<title>Test</title>

<img height=""  width="' src="google.gif?<>" />

After XSLT parsing it looks like this:

    <meta charset="utf-8" />
    <title>Test</title>

    <img height="" src="google.gif?<>" width=""/>

I want @src as last attribute like  <img height="" width="" src="google.gif?<>" />, but by default attributes are sorted in alphabetical order. I am not able to do it using <xsl:sort>.

A: Input HTML (with wellformation):

    <meta charset="utf-8" />
    <title>Test</title>

XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="img">
    <xsl:copy>
        <xsl:for-each select="@*[not(name()='src')]">
            <xsl:sort select="name()"/>
            <xsl:attribute name="{name()}">
                <xsl:value-of select="."/>
            </xsl:attribute>
        </xsl:for-each>
        <xsl:apply-templates select="@*[name()='src']"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Result:

  <meta charset="utf-8"/>
  <title>Test</title>

A: XSLT produces as output a result tree conforming to the XDM data model, and in the XDM model, attributes are unordered. Since they have no order, it follows that XSLT stylesheet instructions cannot control the order.
The only opportunity for controlling the order arises during serialization, when the unordered attribute nodes in the result tree are converted to an ordered sequence of name="value" pairs in the lexical XML output. The standard serialization properties available in XSLT (any version) do not provide any way of controlling this. Saxon however has an extension attribute saxon:attribute-order - see
http://www.saxonica.com/documentation/index.html#!extensions/output-extras/serialization-parameters

A: In addition to <img height="" width="' src="google.gif?<>" /> not being well-formed as commented by  Martin Honnen...
Attribute order is insignificant per the XML Recommendation:

Note that the order of attribute specifications in a start-tag or
  empty-element tag is not significant.

Therefore, XSLT provides no way to constrain attribute ordering.
If you refuse to embrace this recommendation to ignore ordering for attributes, see Martin Honnen's suggestions regarding how to control attribute ordering output to an earlier question on XSLT attribute ordering.


text:
Q: SQL Server 2008: Mirroring: Threshold Alerts at Database-Level Testing I have completed to date seems to indicate that the following Threshold Alerts need to be defined for the <all databases> Database Name rather than a single named database:

*

*Unsent Log Threshold (Error Message 32042)

*Oldest Unsent Transaction Threshold (Error Message 32040)

*Unrestored Log Threshold (Error Message 32043)

*Mirror Commit Overhead Threshold (Error Message 32044)

This is in contrast to the documentation provided by Microsoft:

*

*Technet: "Alerting on Database Mirroring Events"
I have confirmed that Error Numbers 32040, 32042, 32043 and 32044 are being written to the SQL Server Log, as per sp_altermessage:
/* Unsent Log Threshold (http://msdn.microsoft.com/en-us/library/aa337325.aspx) */
sp_altermessage 32042, 'WITH_LOG', TRUE

If you were successful, I would appreciate if you describe the actions you took to cause Threshold Alerts to occur for an individual database.
Thank you.

A: I'm assuming based on your listing that your alerts are firing when you select all databases, but not firing when selecting specific database.
The flow of the database monitoring SQL Agent job is as follows:

*

*Executes sys.dbmonitorupdate periodically (for example – once a minute). This call does the following:

*Retrieves values from sys.dm_os_performance_counters

*Inserts into msdb.dbo.dbm_monitor_data

*When a threshold is reached, an error is raised

*Regarding the alerts, it may not fire because sp_dbmmonitorupdate is in the context of msdb.  So you don't get a fire for individual databases, but you will for all databases.

I don't know if this is the universal behavior or was fixed later on - but I did see a case of this.
So if this describes your situation and don't want to use "all databases" – then you'll need to either write your own detection procedure and job to get around this (might be other solutions too – but you don't have the option to change the aforementioned system stored procedures and still keep things supported).


text:
Q: Creating a macro in excel that pauses at the stage I run VBA code I am creating a macro in excel.
I get to a particular stage in the automation when I need to run some VBA code.
During the automation process, I click on Developer and input the things that I need to input.
However, when I stop recording and try to run the macro from scratch it stops at the point of opening the developer tab and doesnt finish the process.
Sub CreatePortfolio()
'
' CreatePortfolio Macro
'

'
    Range("A2:H132").Select
    ActiveWindow.SmallScroll Down:=-144
    Range("D1").Select
    ActiveWindow.SmallScroll Down:=-6
    ActiveCell.FormulaR1C1 = "Blank"
    Range("H1").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = 11
        .ColorIndex = 11
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveCell.FormulaR1C1 = "Name"
    Cells.Select
    ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Add2 Key:=Range( _
        "B1:B132"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Add2 Key:=Range( _
        "C1:C132"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("INPUT_DATA").Sort
        .SetRange Range("A1:H132")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("H14").Select
    ActiveWindow.SmallScroll Down:=-15
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    ActiveWindow.SmallScroll Down:=126
    Range("A133:H133").Select
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-168
    Range("A1").Select
    ActiveSheet.Paste
    Range("I2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=COUNTIF(R2C8:R20000C8,RC[-8])"
    Range("I2").Select
    Selection.AutoFill Destination:=Range("I2:I133")
    Range("I2:I133").Select
    Range("J2").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-1]>0,1,0)"
    Range("J2").Select
    Selection.AutoFill Destination:=Range("J2:J133")
    Range("J2:J133").Select
    Range("I1").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = 11
        .ColorIndex = 11
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveCell.FormulaR1C1 = "IF1"
    Range("J1").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = 11
        .ColorIndex = 11
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    ActiveCell.FormulaR1C1 = "IF2"
    Rows("1:1").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$J$133").AutoFilter Field:=10, Criteria1:="0"
    Range("A1:J133").Select
    Selection.Copy
    Sheets("SORT1").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Columns("A:A").EntireColumn.AutoFit
    Range("K5").Select
    Columns("G:G").EntireColumn.AutoFit
    Columns("A:A").Select
    Application.CutCopyMode = False
    Selection.Copy
    Columns("L:L").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    ActiveSheet.Range("$L$1:$L$44").RemoveDuplicates Columns:=1, Header:=xlNo
    Columns("L:L").EntireColumn.AutoFit
    Range("M1").Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""",0,1)"
    Range("M1").Select
    Selection.AutoFill Destination:=Range("M1:M4")
    Range("M1:M4").Select
    Range("M21").Select
    ActiveCell.FormulaR1C1 = "=SUM(R[-20]C:R[-1]C)-1"
    Range("L21").Select
    ActiveCell.FormulaR1C1 = "Magic Number"

HERE IS WHEN I ATTEMPT TO CLICK DEVELOPER AND RUN THE VBA CODE
    Range("N21").Select
        ActiveWindow.SmallScroll Down:=-24
        Range("O2").Select
        Application.CutCopyMode = False
        ActiveCell.FormulaR1C1 = "=RC[-3]"
        Range("O2").Select
        Selection.AutoFill Destination:=Range("O2:O20"), Type:=xlFillDefault
        Range("O2:O20").Select
        ActiveWindow.SmallScroll Down:=-15
        Selection.ClearContents
        Range("O2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-3]="""","""",RC[-3])"
        Range("O2").Select
        Selection.AutoFill Destination:=Range("O2:O20"), Type:=xlFillDefault
        Range("O2:O20").Select
        ActiveWindow.SmallScroll Down:=-27
        Range("P2").Select
        Columns("P:P").EntireColumn.AutoFit
        Range("P2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-11])"
        Range("P2").Select
        Selection.AutoFill Destination:=Range("P2:P19"), Type:=xlFillDefault
        Range("P2:P19").Select
        ActiveWindow.SmallScroll Down:=-33
        Range("O8:Y10").Select
        ActiveWindow.ScrollColumn = 16
        ActiveWindow.ScrollColumn = 15
        ActiveWindow.ScrollColumn = 12
        ActiveWindow.ScrollColumn = 9
        ActiveWindow.ScrollColumn = 7
        ActiveWindow.ScrollColumn = 6
        ActiveWindow.ScrollColumn = 5
        ActiveWindow.ScrollColumn = 4
        ActiveWindow.ScrollColumn = 3
        ActiveWindow.ScrollColumn = 1
        ActiveWindow.ScrollColumn = 2
        ActiveWindow.ScrollColumn = 3
        ActiveWindow.ScrollColumn = 4
        ActiveWindow.ScrollColumn = 5
        ActiveWindow.ScrollColumn = 6
        ActiveWindow.ScrollColumn = 7
        ActiveWindow.ScrollColumn = 8
        ActiveWindow.ScrollColumn = 9
        ActiveWindow.SmallScroll Down:=3
        Range("O21").Select
        ActiveCell.FormulaR1C1 = "Returns "
        Range("O22").Select
        Sheets("CODE FOR VBA").Select
        ActiveWindow.SmallScroll Down:=-57
        Range("A1:A35").Select
        Selection.Copy
        Sheets("SORT1").Select
        Application.CutCopyMode = False
    End Sub
    Sub Macro2()
    '
    ' Macro2 Macro
    '

    '
        Cells.Select
        ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Add2 Key:=Range( _
            "B2:B133"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
            xlSortNormal
        ActiveWorkbook.Worksheets("INPUT_DATA").Sort.SortFields.Add2 Key:=Range( _
            "C2:C133"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
            xlSortNormal
        With ActiveWorkbook.Worksheets("INPUT_DATA").Sort
            .SetRange Range("A1:F133")
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        Range("H6").Select
        Columns("A:A").EntireColumn.AutoFit
        Range("G2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-2]="""",RC[-6],"""")"
        Range("G2").Select
        Selection.AutoFill Destination:=Range("G2:G132")
        Range("G2:G132").Select
        Columns("G:G").EntireColumn.AutoFit
        Range("G1").Select
        ActiveCell.FormulaR1C1 = "Missing Data"
        Range("H2").Select
        ActiveCell.FormulaR1C1 = "=COUNTIF(R2C8:R250C8,RC[-7])"
        Range("H2").Select
        ActiveCell.FormulaR1C1 = "=COUNTIF(R2C7:R2500C7,RC[-7])"
        Range("H2").Select
        Selection.AutoFill Destination:=Range("H2:H132")
        Range("H2:H132").Select
        Range("H1").Select
        ActiveCell.FormulaR1C1 = "IF1"
        Range("I1").Select
        ActiveCell.FormulaR1C1 = "IF2"
        Range("I2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-1]>0,1,0)"
        Range("I2").Select
        Selection.AutoFill Destination:=Range("I2:I132")
        Range("I2:I132").Select
        Rows("1:1").Select
        Range("B1").Activate
        Selection.AutoFilter
        ActiveWindow.ScrollColumn = 2
        ActiveSheet.Range("$A$1:$I$132").AutoFilter Field:=9, Criteria1:="1"
        ActiveSheet.Range("$A$1:$I$132").AutoFilter Field:=9, Criteria1:="0"
        ActiveWindow.SmallScroll Down:=-15
        Cells.Select
        Selection.Copy
        Sheets("SORT1").Select
        Cells.Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
        Columns("G:I").Select
        Application.CutCopyMode = False
        Selection.Delete Shift:=xlToLeft
        Columns("F:F").EntireColumn.AutoFit
        Columns("A:A").Select
        Selection.Copy
        Columns("I:I").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
        Application.CutCopyMode = False
        ActiveSheet.Range("$I$1:$I$43").RemoveDuplicates Columns:=1, Header:=xlNo
        Range("J1").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",1)"
        Range("J1").Select
        Selection.AutoFill Destination:=Range("J1:J4")
        Range("J1:J4").Select
        ActiveWindow.SmallScroll Down:=12
        Range("J50").Select
        ActiveCell.FormulaR1C1 = "=SUM(R[-49]C:R[-1]C)-1"
        Range("I50").Select
        ActiveCell.FormulaR1C1 = "Magic Number"
        Range("I51").Select
        ActiveWindow.SmallScroll Down:=-30
        Range("L1").Select
        ActiveWindow.SmallScroll Down:=-3
        ActiveCell.FormulaR1C1 = "Market Value"
        Range("L2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-3]="""","""",RC[-8])"
        Range("L2").Select
        Selection.AutoFill Destination:=Range("L2:L49"), Type:=xlFillDefault
        Range("L2:L49").Select
        ActiveWindow.SmallScroll Down:=-33
        Range("L5").Select
        ActiveWindow.SmallScroll Down:=24
        Range("L51").Select
        ActiveCell.FormulaR1C1 = "Returns"
        Range("M52").Select
        ActiveWindow.SmallScroll Down:=-27
        ActiveCell.FormulaR1C1 = ""
        Range("M52").Select
        ActiveWindow.SmallScroll Down:=-30
        Range("M2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""","""",RC[-1]*(1+R[50]C))"
        Range("M2").Select
        Selection.AutoFill Destination:=Range("M2:M34"), Type:=xlFillDefault
        Range("M2:M34").Select
        Selection.AutoFill Destination:=Range("M2:M44"), Type:=xlFillDefault
        Range("M2:M44").Select
        Selection.AutoFill Destination:=Range("M2:X44"), Type:=xlFillDefault
        Range("M2:X44").Select
        ActiveWindow.SmallScroll Down:=0
        Selection.AutoFill Destination:=Range("M2:Z44"), Type:=xlFillDefault
        Range("M2:Z44").Select
        ActiveWindow.SmallScroll Down:=-21
        Selection.AutoFill Destination:=Range("M2:AA44"), Type:=xlFillDefault
        Range("M2:AA44").Select
        ActiveWindow.SmallScroll Down:=-6
        Range("AA2:AA44").Select
        Selection.ClearContents
        Range("M2:Z44").Select
        ActiveWindow.SmallScroll Down:=9
        Range("L56").Select
        ActiveCell.FormulaR1C1 = "Equal Weighted "
        Range("M56").Select
        ActiveCell.FormulaR1C1 = "=IF(R[-4]C="""","""",AVERAGE(R[-4]C:R[-2]C))"
        Range("M56").Select
        Selection.AutoFill Destination:=Range("M56:Z56"), Type:=xlFillDefault
        Range("M56:Z56").Select
        Range("L57").Select
        ActiveCell.FormulaR1C1 = "Value Weighted"
        Range("M57").Select
        ActiveCell.FormulaR1C1 = _
            "=SUMPRODUCT(R[-55]C[-1]:R[-53]C[-1],R[-5]C:R[-3]C)/SUM(R[-55]C[-1]:R[-53]C[-1])"
        Range("M57").Select
        Selection.AutoFill Destination:=Range("M57:Z57"), Type:=xlFillDefault
        Range("M57:Z57").Select
        Range("R46").Select
        ActiveWindow.SmallScroll Down:=9
        Range("L56:Z57").Select
        Selection.Copy
        Sheets("SORT2").Select
        Range("A2").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
        Range("A1").Select
        Application.CutCopyMode = False
        ActiveCell.FormulaR1C1 = "Returns"
        Range("A2").Select
    End Sub

The VBA code that I run is,

    Sub SplitIntoCellsPerColumn()
    'updatebyExtendoffice 20160225
        Dim xRg As Range
        Dim xOutRg As Range
        Dim xCell As Range
        Dim xTxt As String
        Dim xOutArr As Variant
        Dim I As Long, K As Long
        On Error Resume Next
        xTxt = ActiveWindow.RangeSelection.Address
    Sel:
        Set xRg = Nothing
        Set xRg = Application.InputBox("please select data range:", "Kutools for Excel", xTxt, , , , , 8)
        If xRg Is Nothing Then Exit Sub
        If xRg.Areas.Count > 1 Then
            MsgBox "does not support multiple selections, please select again", vbInformation, "Kutools for Excel"
            GoTo Sel
        End If
        If xRg.Columns.Count > 1 Then
            MsgBox "does not support multiple columns,please select again", vbInformation, "Kutools for Excel"
            GoTo Sel
        End If
        Set xOutRg = Application.InputBox("please select a cell to put the result:", "Kutools for Excel", , , , , , 8)
        If xOutRg Is Nothing Then Exit Sub
        I = Application.InputBox("the number of cell per column:", "Kutools for Excel", , , , , , 1)
        If I < 1 Then
            MsgBox "incorrect enter", vbInformation, "Kutools for Excel"
            Exit Sub
        End If
        ReDim xOutArr(1 To I, 1 To Int(xRg.Rows.Count / I) + 1)
        For K = 0 To xRg.Rows.Count - 1
          xOutArr(1 + (K Mod I), 1 + Int(K / I)) = xRg.Cells(K + 1)
        Next
        xOutRg.Range("A1").Resize(I, UBound(xOutArr, 2)) = xOutArr
    End Sub

But this code is inserted as a module already into the worksheet, So I just open the developer tab and click F5 to enter some arguments for the code to run.


text:
Q: PowerShell: Is there a way to search an specific word in a file's name and open the file if it finds it? I haven't been able to figure out how to make this task that sounds simple in PowerShell.
I am trying to make a powershell variable that represents a file only using a part of it's name, since the rest of the name changes periodically. This should represent a little better what is my intention.
#Each day the number changes except for the Name part.
 Name1, Name2, Name3...

#Variable must be able to work regardless of the number it has since the Name part never changes.
 $Variable: Volume\Folder\Name(X).exe

I'm sorry if i'm not explaining myself well enough.
I'll provide any aditional information that is needed.

A: Run script where you want to search.
$all_files = ls
$filename = Read-Host "Enter File Name"
foreach ($item in $filename)
{
    if ($item -match $filename)
    {
        Get-Content $item
    }
}

A: Well, to me it seems to be two diiferent tasks at hand:
First your title suggests You are lokking for a way to check the filenames of files in a given directory i assume and run that file with the default filehandler (again i can only speculate)
# 1. task
$path="C:\myfolder\"
$mySearchKey="taxes"
$myItmes=Get-ChildItem -Path $myPath
foreach($item in $myItems){
   if($item.name -like "*$mySearchkey*"){
      $matchingPath=$path+$item.name
      Invoke-Item $matchingPath
   }
}

Secondly In your description and the code example the question seems to be evolving around the idea to create dynamic variables for filenames most likely for the files we where opening before, based on the day in relation to a start date:
 #2. task
    $afileName="Marry"
    $startdate= Get-Date "2022-12-06"
    $todays= get-date
    $numberOfDays = New-TimeSpan -Start $startdate -End $todays
    $numberOfDays++ # since a differnce of 0 days means your in the 1. day
    $newPath="Volume\Folder\"+$afileName+$numberOfDays+".exe"

But I yet have to figure out your end-game. How are the two coming together?


text:
Q: How to break out of select gracefuly in golang I have a program in golang that counts SHA1s and prints ones that start with two zeros. I want to use goroutines and channels. My problem is that I don't know how to gracefully exit select clause if I don't know how many results it will produce.
Many tutorials know that in advance and exit when counter hits. Other suggest using WaitGroups, but I don't want to do that: I want to print results in main thread as soon it appears in channel. Some suggest to close a channel when goroutines are finished, but I want to close it after asynchronous for finishes, so I don't know how.
Please help me to achieve my requirements:
package main

import (
    "crypto/sha1"
    "fmt"
    "time"
    "runtime"
    "math/rand"
)

type Hash struct {
    message string
    hash [sha1.Size]byte

}

var counter int = 0
var max int = 100000
var channel = make(chan Hash)
var source = rand.NewSource(time.Now().UnixNano())
var generator = rand.New(source)

func main() {
    nCPU := runtime.NumCPU()
    runtime.GOMAXPROCS(nCPU)
    fmt.Println("Number of CPUs: ", nCPU)
    start := time.Now()

    for i := 0 ; i < max ; i++ {
        go func(j int) {
            count(j)
        }(i)
    }
    // close channel here? I can't because asynchronous producers work now

    for {
        select {
                    // how to stop receiving if there are no producers left?
            case hash := <- channel:
                fmt.Printf("Hash is %v\n ", hash)
            }
    }
    fmt.Printf("Count of %v sha1 took %v\n", max, time.Since(start))
}

func count(i int) {
    random := fmt.Sprintf("This is a test %v", generator.Int())
    hash := sha1.Sum([]byte(random))

    if (hash[0] == 0 && hash[1] == 0) {
        channel <- Hash{random, hash}
    }
}

A: Firstly: if you don't know when your computation ends, how could you even model it? Make sure you know exactly when and under what circumstances your program terminates. If you're done you know how to write it in code.
You're basically dealing with a producer-consumer problem. A standard case. I would model
that this way (on play):
Producer
func producer(max int, out chan<- Hash, wg *sync.WaitGroup) {
    defer wg.Done()

    for i := 0; i < max; i++ {
        random := fmt.Sprintf("This is a test %v", rand.Int())
        hash := sha1.Sum([]byte(random))

        if hash[0] == 0 && hash[1] == 0 {
            out <- Hash{random, hash}
        }
    }

    close(out)
}

Obviously you're brute-forcing hashes, so the end is reached when the loop is finished.
We can close the channel here and signal the other goroutines that there is nothing more to listen for.
Consumer
func consumer(max int, in <-chan Hash, wg *sync.WaitGroup) {
    defer wg.Done()

    for {
        hash, ok := <-in

        if !ok {
            break
        }

        fmt.Printf("Hash is %v\n ", hash)
    }
}

The consumer takes all the incoming messages from the in channel and checks if it was closed (ok).
If it is closed, we're done. Otherwise print the received hashes.
Main
To start this all up we can write:
wg := &sync.WaitGroup{}
c := make(chan Hash)

wg.Add(1)
go producer(max, c, wg)

wg.Add(1)
go consumer(max, c, wg)

wg.Wait()

The WaitGroup's purpose is to wait until the spawned goroutines finished, signalled by
the call of wg.Done in the goroutines.
Sidenote
Also note that the Rand you're using is not safe for concurrent access. Use the one initialized
globally in math/rand. Example:
rand.Seed(time.Now().UnixNano())
rand.Int()

A: The structure of your program should probably be re-examined.
Here is a working example of what I presume you are looking for.
It can be run on the Go playground
package main

import (
    "crypto/sha1"
    "fmt"
    "math/rand"
    "runtime"
    "time"
)

type Hash struct {
    message string
    hash    [sha1.Size]byte
}

const Max int = 100000

func main() {
    nCPU := runtime.NumCPU()
    runtime.GOMAXPROCS(nCPU)

    fmt.Println("Number of CPUs: ", nCPU)

    hashes := Generate()
    start := time.Now()

    for hash := range hashes {
        fmt.Printf("Hash is %v\n ", hash)
    }

    fmt.Printf("Count of %v sha1 took %v\n", Max, time.Since(start))
}

func Generate() <-chan Hash {
    c := make(chan Hash, 1)

    go func() {
        defer close(c)

        source := rand.NewSource(time.Now().UnixNano())
        generator := rand.New(source)

        for i := 0; i < Max; i++ {
            random := fmt.Sprintf("This is a test %v", generator.Int())
            hash := sha1.Sum([]byte(random))

            if hash[0] == 0 && hash[1] == 0 {
                c <- Hash{random, hash}
            }
        }
    }()

    return c
}

Edit: This does not fire up a separate routine for each Hash computation,
but to be honest, I fail to see the value on doing so. The scheduling of all those routines will likely cost you far more than running the code in a single routine.
If need be, you can split it up into chunks of N routines, but a 1:1 mapping is not the way to go with this.


text:
Q: Optocoupler to switch 24V using Arduino I am currently redesigning a circuit to switch a spring applied brake using an Arduino Micro.
The current circuit looks like this (please excuse if I'm using wrong symbols, I'm learning by myself):

The the important part is the right half, BRAKE1 is the spring applied brake with a resistance of 137 Ohm. This is the datasheet and the brake is found on page 84 MCNB 2GR.
At the moment I am using a 2N3904 transistor to switch the 24V which is generated from a Mean Well RS-100-24 DC power supply.
I have found an issue with the circuit that I have soldered where when connecting the GND from the 24V DC source to the GND of the Arduino, I get a voltage of ~1.9V on my digital pins on the Arduino. If I disconnect the GND cable, the 1.9V are gone. (during this test, the 24V positive cable was disconnected)
I have also noticed that connecting an oscilloscope including its GND will remove the 1.9V.
From my research it leads me to believe that it might be a ground loop problem.
As such I would like to electrically isolate the Arduino and the 24V circuit using an optocoupler to switch the 24V on and off with a 5V digital signal from the Arduino.
There is so much information on optocouplers and here in chapter 3 I read that the available output current with an optocoupler is limited to small values. From the break datasheet I gather that it takes 0.175A of current which seems to be too much. How would I redesign my circuit to include an optocoupler and which optocoupler whould be necessary, considering I'm not sending data but only an on-off signal that doesn't need to switch back and forth too frequently?

A:
the available output current with an optocoupler is limited to small values.

You cannot directly switch a relatively high-current load with an optocoupler. But it can be used as a pre-amplifier (or pre-driver) for a switching transistor.

How would I redesign my circuit to include an optocoupler and which optocoupler whould be necessary, considering I'm not sending data but only an on-off signal that doesn't need to switch back and forth too frequently?

Recommending specific parts is rated as off-topic here. Nevertheless, I'll recommend you to use any 817 series optocouplers as they are too common and very easy to find anywhere in the world. The ones with relatively higher CTR (Current transfer ratio) would be better, so HCPL817 (any CTR rank starting from B) can be a good option.
CTR for an optocoupler is simply a ratio of collector current to LED current. You can think of it as something like hFE of BJTs.
As for using it to switch a load, here's a circuit you can use:

simulate this circuit – Schematic created using CircuitLab
I selected BC547 as the load switching transistor because it has relatively high hFE (I personally tend to use 2N390x for relatively faster switching applications). Since the BJT should operate in saturation mode here, a base current of one-twentieth to one-tenth of the load current is sufficient (this is a practical tip for small-signal BJTs). So, for \$\mathrm{I_C=175mA}\$, the minimum base current could be \$\mathrm{I_B=I_C/15=12mA}\$ is quite sufficient.
\$\mathrm{I_B}\$ of the BJT flows through the optocoupler's transistor. Assuming a 1V drop across the optocoupler's transistor at 12mA, the current limiter resistor for BJT's base could be \$\mathrm{R2 = (24V - 1V)/12mA = 1k9}\$. The nearest standard value is 1k8. R5 is there to guarantee the off state of BJT (i.e. to prevent any base-emitter instability which can cause an accidentally turn-on).
Assuming the minimum CTR of the optocoupler is 100%, the required minimum LED current is 12mA. The forward voltage drop of optocoupler LED is around 1.1V at 12mA, so the current limiter resistor is \$\mathrm{R1 = (5V - 1.1V)/12mA \approx 3k3}\$.

A: While this requires more investigation to find out why you are getting that voltage just by connecting the GND wire, here is the optocoupler circuit you want:

simulate this circuit – Schematic created using CircuitLab
LED and transistor combination is an optocoupler (PC817 for example). You drive it similar to how you would drive an LED. For the external transistor that is driving the brake, you attach a Pullup resistor. I have shown 1K but you can make the right calculations and set the right value. Whenever you want to turn the brake OFF, you need to give a HIGH signal to the optocoupler. The optocoupler output transistor will pull the gate of external transistor LOW and the brake will turn OFF.


text:
Q: Delete all the data of BBPress I would like to delete all the data related to bbPress Wordpress, some how millions of records are inserted into my blog and i will use this query to delete the records
DELETE from wp_btei_postmeta
where
Post_id IN (select distinct ID from wp_btei_posts where post_type in ('forum', 'topic', 'reply'))

I want to know is this the right thing I am doing ? Will it delete other data than my forum ? because i read on BBPress that they use the above three types of post and uses the main post table only.

A: bbPress includes a tool to delete all the bbPress data

*

*Install and activate the bbPress plugin again

*Go to Tools -> Forums -> "Reset Forums" tab

*Check the "Are you sure you want to do this?" checkbox

*Click "Reset bbPress"

*Deactivate and delete the bbPress plugin

This will remove all bbPress data from your WordPress database, including custom post types, topic tag taxonomy and user meta.


text:
Q: C++ Parsing a CSV file into vector of vectors: Loosing string 1st character I am reading a CSV file into vector of string vectors. I have written code below.
#include<iostream>
#include<fstream>
#include<string>
#include <vector>
#include <fstream>
#include <cmath>
#include <sstream>

using namespace std;

int main()
{
    ifstream mesh;
    mesh.open("mesh_reference.csv");

    vector<vector<string> > point_coordinates;
    string line, word;

    while (getline(mesh,line))
    {
        stringstream ss(line);
        vector<string> row;
        while (getline(ss, word, ','))
        {
            row.push_back(word);
        }
        point_coordinates.push_back(row);
    }

    for(int i=0; i<point_coordinates.size(); i++)
    {
        for(int j=0; j<3; j++)
            cout<<point_coordinates[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}

When I print out the vector of vectors, I see that I am loosing the first character of Element at 0 position in the vector row. Basically, point_coordinates[0][0] is displaying 0.0001 while the string is supposed to be -0.0001. I am not able to understand the reason for the same. Kindly help.
A typical output line is
 .0131 -0.019430324 0.051801

Whereas the CSV data is
0.0131,-0.019430324,0.051801

SAMPLE CSV DATA FROM FILE
    NODES__X,NODES__Y,NODES__Z
    0.0131,-0.019430324,0.051801
    0.0131,-0.019430324,0.06699588
    0.0131,-0.018630324,0.06699588
    0.0131,-0.018630324,0.051801
    0.0131,-0.017630324,0.050801
    0.0131,-0.017630324,0.050001
    0.0149,-0.017630324,0.050001
    0.0149,-0.019430324,0.051801

A: Although the problem is already solved, I would like to show you a solution using some modern C++ algorithms and eliminating minor issues.

*

*Do not use using namespace std;. You should not do this

*Ne need for a separate file.open. The std::ifstream constructor will open the file for you. And the destructor will close it

*Check if the file could be opened. The ifstreams ! operator is overloaded. So you can do a boolean check

*Do not use int in for loops where you compare against .size(). Use ````size_t instead

*Always initialize all variables, even if there is an assignement in the next line

*For tokenizing you should use std::sregex_token_iterator. It has exactly been designed for this purpose

*In modern C++ you are encouraged to use algorithms

Please see an improved version of your code below:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <regex>

const std::regex comma(",");

int main()
{
    // Open source file.
    std::ifstream mesh("r:\\mesh_reference.csv");

    // Here we will store the result
    std::vector<std::vector<std::string>> point_coordinates;

    // We want to read all lines of the file
    std::string line{};
    while (mesh && getline(mesh, line)) {
        // Tokenize the line and store result in vector. Use range constructor of std::vector
        std::vector<std::string> row{ std::sregex_token_iterator(line.begin(),line.end(),comma,-1), std::sregex_token_iterator() };
        point_coordinates.push_back(row);
    }
    // Print result. Go through all lines and then copy line elements to std::cout
    std::for_each(point_coordinates.begin(), point_coordinates.end(), [](std::vector<std::string> & vs) {
        std::copy(vs.begin(), vs.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << "\n"; });

    return 0;
}

Please consider, if you may want to use such an approach in the future


text:
Q: Error Occur During JAR File creation For JAVA in Net Beans 7.3.1 I am using Netbeans version 7.3.1. I am trying to create a JAR file for a Java application, but the following error was returned when I clicked the "Build" option on the context menu of the Java application in the Project window…
Created dir: D:\Java\Programe\JavaPrograme\build
Updating property file: D:\Java\Programe\JavaPrograme\build\built-jar.properties
Created dir: D:\Java\Programe\JavaPrograme\build\classes
Created dir: D:\Java\Programe\JavaPrograme\build\empty
Created dir: D:\Java\Programe\JavaPrograme\build\generated-sources\ap-source-output
D:\Java\Programe\JavaPrograme\nbproject\build-impl.xml:926: The following error occurred while executing this line:
D:\Java\Programe\JavaPrograme\nbproject\build-impl.xml:268: Class not found: javac1.8
BUILD FAILED (total time: 0 seconds)

Please share any solutions.

A: I guess your your Ant version is below 1.9.
Follow up these steps:-
Go to preferences > Java > Ant. (For older versions, it is under preferences > Miscellaneous > Ant).
Look for something like "Apache Ant version 1.9 compiled on". If your Apache ant version is lower than 1.9, you will need to update your Netbeans or download the latest version of it.
Hope this helps.


text:
Q: Proper methods for this case of repeated measures? I am measuring hormone changes in animals. I have three groups: Groups A, B, and C. In each group, blood was collected from the SAME individuals for hormone assay at 0, 15, 30, and 60 min. This was done in males and in females and I would like to keep in mind sex differences.
My question: do the changes we see in hormones over time differ between groups A,B, and C? And if so, how?
Does the variation of hormone change over time differ between groups A,B, and C?
I would like to analyze in one big model, but I'm not exactly confident in the test(s) I'm using. Any advice?

A: A graphical overview of the data would help inform which model to fit, however a possible fit would be as follows:
Fixed: the interaction between group and time. If the changes over time are not very linear, then time should be used as a factor. If time is a factor, then an intercept would not need to be included.
Random: random slopes with respect to time. Again, time could be a factor or numeric. If time is numeric, then random intercepts could be added if the starting point in each animal is different. If time is a factor, then an assumption will need to be made about correlations between the random effects at different time points.
Finally, if your sample size is small, then it may not be worthwhile fitting any model at all and a graphical/tabular overview should be used.
A basic model like this can be estimated using lme4 in R by running the following:
lmer(y ~ group:time + (time|animal))
If you want to have a specific variance structure for the random effects, then you'll need nlme instead of lme4
I've no idea about how to do this in JMP/SAS


text:
Q: Python: How to parse a CSV file containing NULL values? I have a csv file containing binary fields, and when I read it by csv.reader(f), I get

containing NULL values.

I've tried all kinds of solutions on the web such as this, this and this but still, the same error pops up. I managed to read it line by line and separate it by ,, but some fields have also , within it, so I'm wondering how I can read and extract the columns? An example of a row is as bellow:
212344408,"cp233.net","net","cp233","clientTransferProhibited,ClientDeleteProhibited","ENAME TECHNOLOGY CO., LTD.",1331,"DNS1.IIDNS.COM","DNS2.IIDNS.COM","2017-02-14","2018-02-14","2017-02-14","WANG MIN CHUN","wangminchun","WANG MIN CHUN","wangminchun","957596578@QQ.COM","QUANZHOUSHIANXIXIANCHANGKENGXIANGHUAMEICUN","QUAN ZHOU HI","FU,JIAN","362421","CN","+86.59523128184","+86.59523128184","%^^<AD>!^S\0<A8>E<98><AC>/^<A5><A0><C9>7","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM",0,"2017-03-14 21:33:15","2017-03-12 20:44:02",0,"whois_zone_snr","2017-03-14 21:33:15",\N

I would appreciate any suggestions.

A: Pandas worked great for my case and could retrieve the file and skip those rows that were broken because of weird characters.
import pandas as pd

df = pandas.read_csv(filename, verbose =True , warn_bad_lines = True, error_bad_lines=False, names = header)

A: This works fine on your example, I even replaced one string with NULL and it handled it just fine.
test.csv:
212344408,"cp233.net","net","cp233","clientTransferProhibited,ClientDeleteProhibited","ENAME TECHNOLOGY CO., LTD.",1331,"DNS1.IIDNS.COM","DNS2.IIDNS.COM","2017-02-14","2018-02-14","2017-02-14","WANG MIN CHUN","wangminchun","WANG MIN CHUN","wangminchun","957596578@QQ.COM","QUANZHOUSHIANXIXIANCHANGKENGXIANGHUAMEICUN","QUAN ZHOU HI","FU,JIAN","362421","CN","+86.59523128184","+86.59523128184","%^^<AD>!^S\0<A8>E<98><AC>/^<A5><A0><C9>7","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM",0,"2017-03-14 21:33:15","2017-03-12 20:44:02",0,"whois_zone_snr","2017-03-14 21:33:15",\N
212344408,NULL,"net","cp233","clientTransferProhibited,ClientDeleteProhibited","ENAME TECHNOLOGY CO., LTD.",1331,"DNS1.IIDNS.COM","DNS2.IIDNS.COM","2017-02-14","2018-02-14","2017-02-14","WANG MIN CHUN","wangminchun","WANG MIN CHUN","wangminchun","957596578@QQ.COM","QUANZHOUSHIANXIXIANCHANGKENGXIANGHUAMEICUN","QUAN ZHOU HI","FU,JIAN","362421","CN","+86.59523128184","+86.59523128184","%^^<AD>!^S\0<A8>E<98><AC>/^<A5><A0><C9>7","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM","WANG MIN CHUN","WANG MIN CHUN","957596578@QQ.COM",0,"2017-03-14 21:33:15","2017-03-12 20:44:02",0,"whois_zone_snr","2017-03-14 21:33:15",\N

code:
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

If that's not the behaviour you're experiencing could you provide a line where it fails?


text:
Q: Standard deviation showing up as NA in dplyr chain When I do the following:
data_control %>%
  group_by(politics, partner_politics) %>%
  summarize(pd_sent_amount = mean(as.numeric(pd_sent_amount)),
            n = n(),
            pd_sent_amount_sd =  sd(as.numeric(pd_sent_amount), na.rm = T)
           )

I get the current output:
# A tibble: 4 x 5
# Groups:   politics [?]
  politics   partner_politics pd_sent_amount     n pd_sent_amount_sd
  <fct>      <fct>                     <dbl> <int>             <dbl>
1 Democrat   Democrat                  0.598    76                NA
2 Democrat   Republican                0.479    34                NA
3 Republican Democrat                  0.404    34                NA
4 Republican Republican                0.404    70                NA

Not sure why the standard deviation calculations are coming up NA as I can calculate them manually by group, e.g.:
test = subset(data_control, politics == "Democrat" & partner_politics == "Democrat")
with(test, sd(pd_sent_amount) / sqrt(nrow(test)))

> with(test, sd(pd_sent_amount) / sqrt(nrow(test)))
[1] 0.05008275

Here's a dput of a sample of the data:
structure(list(politics = structure(c(1L, 2L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L,
1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L), .Label = c("Democrat", "Republican"
), class = "factor"), partner_politics = structure(c(2L, 1L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L), .Label = c("Democrat",
"Republican"), class = "factor"), pd_sent_amount = c(0.2, 0,
0.75, 0, 0, 0, 0, 0, 0.5, 0, 1, 0, 1, 0.5, 1, 1, 1, 0.5, 1, 0.5,
1, 1, 0.25, 0, 0, 0.25, 0, 0, 0.5, 1)), row.names = 5:34, class = "data.frame")

A: The call to sd() is referencing the in-place mutation (summarization) of pd_sent_amount. Give the summarized column a new name.
data_control %>%
  group_by(politics, partner_politics) %>%
  summarize(pd_sent_amount_mean = mean(as.numeric(pd_sent_amount)),
            n = n(),
            pd_sent_amount_sd =  sd(as.numeric(pd_sent_amount), na.rm = T)
           )

The fourth example given here on the dplyr website mentions that "newly created summaries immediately overwrite existing variables", and the example is actually the same case as yours with sequential calls to mean() and sd().


text:
Q: Apache2 behind NGINX: MOD_REWRITE only works without HTTPS For days I can't get my head around the following problem:
We have an application (Faveo) which has two requirements for going through the setup wizard:
HTTPS & MOD_REWRITE.
Faveo is running on Apache2 with a ReverseProxy in front of it in our DMZ.

If I run our ReverseProxy with a simple
location / {
          proxy_pass http://XXX.XXX.XXX.XXX;
}

mod_rewrite (which is enabled Apache-Side, which serves Faveo) seems to work and the Faveo-Wizard turns green.
However - The Application is not served with HTTPS.
Therefore I can't click "Continue":
Click me! (http; mod_rewrite)

If I now loop through the following arguments:
location / {
          proxy_pass http://xxx.xxx.xxx.xxx;

          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Faveo is now called with HTTPS, but mod_rewrite does not work this time:
Click me! (HTTPS; no mod_rewrite)
This does not allow a click on "continue" either.
Do you have any ideas? How can I pass HTTPS down to Apache and still be able to use mod_rewrite on the Apache side of things?
NGINX-Config:
server {
        listen       80;
        server_name helpdesk.someurl.de;
        return 301 https://$server_name$request_uri;
}

server {
        listen       443 ssl http2;
        ssl_protocols TLSv1.2;
        server_name helpdesk.someurl.de;

        # Enable SSL
        ssl                     on;
        ssl_certificate      /etc/letsencrypt/live/someurl.de/fullchain.pem;
        ssl_certificate_key  /etc/letsencrypt/live/someurl.de/privkey.pem;

        client_max_body_size    50M;
        ssl_session_timeout     5m;

        # Set global proxy settings
        proxy_read_timeout      360;

       location / {
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header Host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_pass http://XXX.XXX.XXX.XXX/;
        }

        error_log /var/log/nginx/helpdesk-ssl-error.log;
        access_log /var/log/nginx/helpdesk-ssl-access.log;
}

Apache2:
<VirtualHost *:80>
    ServerName helpdesk.someurl.de

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/faveo/public

    <Directory /var/www/faveo/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

If I now delete
proxy_set_header Host $http_host;

From the NGINX-Config, HTTPS is disabled but mod_rewrite works.
If it's enabled I get HTTPS served, but no mod_rewrite.