text:
Q: Local HTML File Form submit via Ajax to external URL I am stucking a bit with my little project.
I got an local HTML file where some Forms are in it.
All stylesheets and Javascript files are located on a webserver.
So my problem is. Im submitting all forms via AJAX. When i normally open the HTML file local on my desktop NOTHING happens.
When I uplod the html file on my webserver visit it, all is working fine.
So is there any solution to get the forms submitted local while the related JS / PHP Files are located on a webserver?
EDIT:
Information - All Stylesheets and Javascript files ( where also the ajax part is included ) are located on an runnning Webserver.
If its not working, maybe there is an other solution to get the forms submitted local by opening the html file with the browser and submitting without reloading the page?

A: Asuming you are using an apache server, you need to enabled cross-domain ajax requests in the webserver, in order to do so.
The easiest way to do so, is add this element to your apache vhosts configuration file:
Header set Access-Control-Allow-Origin "*"

I.E:
<VirtualHost www.test.com:80>
    ServerName www.chat.com
    DocumentRoot "/Applications/AMPPS/www/test"
    Header set Access-Control-Allow-Origin "*"
</VirtualHost>

You also need to enabled the header module in your apache config httpd.conf:
LoadModule headers_module modules/mod_headers.so


text:
Q: Error when accessing Persistant vector of object instances My Near contact contract returns an error when I attempt to access a Persistent vector of object instances in the listcourses function.
Log [dev-1642726071766-23690329778292]: ABORT: Cannot parse JSON, filename: "~lib/assemblyscript-json/decoder.ts" line: 144 col: 5
        Failure [dev-1642726071766-23690329778292]: Error: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: Cannot parse JSON, filename: \"~lib/assemblyscript-json/decoder.ts\" line: 144 col: 5"}}
ServerTransactionError: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: Cannot parse JSON, filename: \"~lib/assemblyscript-json/decoder.ts\" line: 144 col: 5"}}
    at Object.parseResultError (/home/jjsullivan/.nvm/versions/node/v17.2.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29)
    at Account.signAndSendTransactionV2 (/home/jjsullivan/.nvm/versions/node/v17.2.0/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:160:36)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async scheduleFunctionCall (/home/jjsullivan/.nvm/versions/node/v17.2.0/lib/node_modules/near-cli/commands/call.js:57:38)
    at async Object.handler (/home/jjsullivan/.nvm/versions/node/v17.2.0/lib/node_modules/near-cli/utils/exit-on-error.js:52:9) {
  type: 'FunctionCallError',

import { storage, context, PersistentVector } from "near-sdk-as";
import { Course } from "./course";

// return the string 'hello world'
export function helloWorld(): string {
    return 'hello world and \r\ngreetings earthlings from the Blockchain Academy'
}

export function welcomeUser(): string {
    return "Greetings " + context.sender + " .... :)"
}

let studentlist = new PersistentVector<string>('student');
let absentlist = new PersistentVector<string>('absent');
let roster = new PersistentVector<string>('list');
let courselist = new PersistentVector<Course>('courses');

@mutateState()
export function initial(): string{

    if(roster.length < 1 ){

        //let courselist = new PersistentVector<Course>('courses');
        let slist = new Array<string>();
        let courseqty = new Array<Course>();
        let scount: i32 = 0;
        let strstuds: string = "";
        let course0 = new Course(101, "Java", true);
        let crs: string = "";
        courselist.push(course0);
        let courseamt: i32 = 0;

        slist[0] = "Rob Sims";
        scount++;
        slist[1] = "Mike Dorgan";
        scount++;
        slist[2] = "Tom Reager";
        scount++;
        slist[3] = "Mary Smith";
        scount++;
        slist[4] = "Ryan Williams";
        scount++;
        slist[5] = "Bryant Nielson";
        scount++;
        slist[6] = "Ryan Kraz";
        scount++;
        for(let j = 0; j < scount; j++){
            studentlist.push(slist[j]);
            roster.push(slist[j]);
            const mystudent = slist[j];
            strstuds = strstuds + " " + j.toString() + ": " + mystudent + ", ";
        }
        courseamt = courselist.length;
        strstuds = strstuds + " \nThere is " + courseamt.toString() + " course.  The course is: " + course0.get_coursename();
        return strstuds;
     }else {

        return "Students may be initialized.";
    }
}

export function markabsent(studentnum: i32): string {

    if(studentlist.containsIndex(studentnum)){
            let abstudent: string = "";
            abstudent = studentlist[studentnum];
            studentlist.swap_remove(studentnum);
            absentlist.push(abstudent);
            return "Student " + abstudent + " marked absent.";
    }
    return "ok";
}

export function listabsent(): Array<string> {
    let abstudlist = new Array<string>();
    let indx = new Array<i32>();
    let i: i32 = 0;
    while (i < absentlist.length){
            indx[i] = i;
            abstudlist.push(indx[i].toString() + " : " + absentlist[i]);
            i++;
    }
    return abstudlist;

}

export function addStudent(student: string): string{

    let mystudent: string = "";
    mystudent = student;
    studentlist.push(mystudent);
    roster.push(mystudent);
    return "Student " + mystudent + " added. There are now " +      studentlist.length.toString() + " students.";

}

export function removeStudent(rmstud: string): string{

    let ablist = new Array<string>();
    let studlist = new Array<string>();
    let rmstudent: string = "";
    let abstudent: string = "";
    let stud: string = "";
    let abindx = new Array<i32>();
    let absentidx: i32;
    //let ridx = new Array<i32>();
    //let abidx = new Array<i32>();
    let x: i32 = 0;
    let y: i32 = 0;

    while (y < studentlist.length){
            //ridx[y] = y;
            stud = studentlist[y];
            if(stud == rmstud){

                    rmstudent = studentlist.swap_remove(y);
            }
            y++;
    }

    while (x < absentlist.length){

            abstudent = absentlist[x];
            if(abstudent == rmstud){

                    rmstudent = absentlist.swap_remove(x);
            }
            x++;

    }
    return "Removed " + rmstudent;
}

export function listStudents(): Array<string>{

    let studlist = new Array<string>();
    let indx = new Array<i32>();
    let i: i32 = 0;
    //
    while (i < studentlist.length){
            indx[i] = i;
            studlist.push(indx[i].toString() + " : " + studentlist[i]);
            i++;
    }
    return studlist;
}

export function movePresent(abstudnum: i32): string {

    if(absentlist.containsIndex(abstudnum)){

            let abstudent: string = "";
            abstudent = absentlist[abstudnum];
            absentlist.swap_remove(abstudnum);
            studentlist.push(abstudent);
            return "Student " + abstudent + " moved from absent tp present.";
    }else {
            return "Cannot find student with index " + abstudnum.toString() + ".";
    }

}

export function addCourse(id: i32, cnm: string, offered: boolean): string{

    let id0: i32 = 0;
    let cnm0: string = "";
    let offered0: boolean;
    let clist: string = "";

    id0 = id;
    cnm0 = cnm;
    offered0 = offered;

    let len: i32 = 0;
    len = courselist.length;
    let newcourse = new Course(id0, cnm0, offered0);
    courselist.push(newcourse);
    len = courselist.length;

    let addedcourse: string = "";
    let courseid: i32 = 0;
    let mycrs_name: string = "";
    let noffered: boolean;

    courseid = newcourse.get_coursenum();
    mycrs_name = newcourse.get_coursename();
    noffered = newcourse.get_offered();

    //const thecourse = courselist[id];

    addedcourse = "Added course. ID: " + courseid.toString() + " Name: " + newcourse.get_coursename() + " Offered: " + noffered.toString();
    addedcourse = addedcourse + ". The course list length: " + len.toString();

    return addedcourse;
}

@mutateState()
export function listcourses(): string{

    let clist = new Array<Course>();
    let z: i32 = 0;
    let coursedata: string = "";
    let myid: i32 = 0;
    let mycname: string = "";
    let myoffered: boolean;
    //let courseinfo: Course;

    while (z < courselist.length){

            clist.push(courselist[z]);
            coursedata = coursedata + " " + myid.toString() + " "+ mycname;
            z++;
    }
    return coursedata + " " + z.toString();

}

Class code
//@nearBindgen
export class Course {

    private coursenum: i32
    private cname: string;
    private offered: boolean;

    constructor (coursenum: i32, cname: string, offered: boolean) {

        this.cname = cname;
        this.coursenum = coursenum;
        this.offered = offered;

    }

    set_coursenum(): void {
        this.coursenum = coursenum;
    }

    set_coursename(): void {

        this.cname = cname;
    }

    set_offered(): void {
        this.offered = true;
    }

    set_notoffered(): void {
        this.offered = false;

    }

    get_coursenum(): i32 {
        return this.coursenum;
    }

    get_coursename(): string {
        return  this.cname;
    }

    get_offered(): boolean {
        return this.offered;
    }

}

A: You have to enable the @nearBindgen annotation in your class.
It looks like it's commented out in the top of your class code. Remove the first two slashes "//" before // @nearBindgen.
That way, you're able to serialize and deserialize the class to and from JSON
@nearBindgen  // remove the "//"
export class Course {
...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spanning tree with unique paths. Let $G$ be a connected graph and let $r∈V(G)$. Prove that $G$ has a spanning tree $T$ such that for every edge of $G$ with ends $u$ and $v$, either $u$ belongs to the unique path in $T$ with ends $v$ and $r$, or $v$ belongs to the unique path in $T$ with ends $u$ and $r$.
I can't figure this problem out or even know what it is asking for. Can we try to prove this using contradiction? Assume $u$ belongs to the path $T$ with ends $v$ and $r$ "and" $v$ belongs to the path in $T$ with ends $u$ and $r$. Thus there exists a cycle in the spanning tree T which is a contradiction. Does this work? Any solutions or hints are greatly appreciated.

A: The 'either' here is ambiguous, and I hate it when they do this.
For some, "either A or B" means just "A or B" (at least one, but it could be both).
For others, "either A or B" means "A exclusive-or B" (at least one, but not both).
So the minimum would be to prove that at least one of the two holds.
Actually in this case, it's and exclusive-or, so let's prove that exactly one holds.
Let's not care about spanning trees and show that the statement holds for any tree $T$.
We first show that $u$ is on the $v-r$ path, or $v$ is on the $u-r$ path (simple 'or').
Let $uu_1u_2 \ldots u_kr$ be the unique path between $u$ and $r$.  If this path contains $v$, then the statement holds ($v$ is on the $u-r$ path).  Otherwise, look at the path $vuu_1 \ldots u_kr$.  It is the unique $v-r$ path, and it contains $u$.
But actually, this also shows that both cannot hold.  Say that the $u-r$ path contains $v$ (without loss of generality), and let $uu_1 \ldots u_kv v_1 \ldots v_jr$ be this path (actually $u_1 = v$, but let's not bother proving this).
Then $vv_1 \ldots v_jr$ is the unique $v-r$ path, and it does not contain $u$.


text:
Q: Python twisted dataReceived method receive complete data at once This is my code
`
class TestProtocol(Protocol):
    def connectionMade(self):
        print 'Got connection from', self.transport.client

    def dataReceived(self, data):
            print(data)

class Test(Factory, HoneypotService):
    NAME = 'test'
    protocol = TestProtocol

    def __init__(self, config=None, logger=None):
        HoneypotService.__init__(self, config=config, logger=logger)
        self.port = 8888

    def getService(self):
        return internet.TCPServer(self.port, self)

When I use the telnet 127.0.0.1 8888  command to connect to this service, and input abcdef,Method dataReceived is executed twice,execute result is as follows:
output picture:
enter image description here
Is there any way to execute dataReceived only once, And the output information is abcdef.
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
The output information is abcdef.

A: As explained in the Twisted FAQ:

TCP is a stream-oriented transport. This means that when you call transport.write, the data may be broken up into arbitrarily-sized chunks for transmission over the network. There is no way for Twisted to determine how large the data originally written to the transport was.
If you want to send a message and receive it whole on the other end of a connection, you must decide on a format for the message and parse it. For example, prefixing the message with a length or terminating it with a message boundary.

https://github.com/twisted/trac-wiki-archive/blob/trunk/FrequentlyAskedQuestions.mediawiki#why-is-protocoldatareceived-called-with-only-part-of-the-data-i-called-transportwrite-with


text:
Q: Getting route undefined error for POST after upgrade from Laravel 4.2 to 5.0 I am upgrading my app from Laravel 4.2 => 5.x
I was using routes such as
Route::post('/cancelaccount',["as"=>"/cancelaccount",'uses'=>'UserController@cancelAccount']);

But when I try to load the page, I get "/cancelaccount" undefined error. I do not get this error if it's a GET request, I have problem with all my POST requests which are submitting to controller methods.
Currently as a workaround, I am replacing all actions to Controller@method format from URL format
Am I missing anything?

A: So after searching high and low for the answer on internet, I realized that I was looking at wrong place. I was looking at Route for an answer which is not where the problem lies.
So here's the answer if some poor soul is facing the same issue. Route undefined error will be encountered only for Form actions. In Laravel 5, Form "action" is reserved for only Controller methods. If you want to POST to named route, Open your form like this
Form::open('route'=>'your-named-route')

In my case I changed my form definition to
Form::open('route'=>'/cancelaccount','method'=>'post')

Ofcourse you can still use Form::open('action'=>'Controller@method')
Hope this helps!


text:
Q: How do I make toolbars that look like the ones in Keynote? Here's a screenshot of keynote on the ipad:

(source: scottyallen.com)
The toolbar is pretty flat - it doesn't have a vertical gradient the way the builtin toolbar styles do. I've played with the different styles, the translucent flag, and the tint color, and haven't been able to replicate it.
How are they doing this?  How would I implement it?

A: I think your talking about the UIToolbar on top, not the toolbar-ish controls at the bottom.
Changing the looks of a UINavigationBar or UIToolbar is really easy, you can just use an image instead of the calculated tintColor and default gradient.
To do this, you'll need to subclass (or make a category of) the UINavigationBar or UIToolbar and overwrite the drawRect: method, like this:
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"toolbarBackground.png"];
    [image drawInRect:rect];
}

This image then gets drawn at the exact rect of the UINavigationBar or UIToolbar, functioning as a background image.


text:
Q: Подобрать все дочерние элементы и запушить в объект в виде массива | .each() let obj = [ // сюда должны добавить новое св-во из html
    {id: 0, name: 'Murray', job: 'frontend', experience: 6},
    {id: 1, name: 'Bob', job: 'cybersec', experience: 4},
    {id: 2, name: 'Muhammad', job: 'backend', experience: 8},
    {id: 3, name: 'Vova', job: 'projmanager', experience: 12},
]

        <smth...></smth...>
        Audi QQQ
        <smth...></smth...>

        <smth...></smth...>
        Mers S
        <smth...></smth...>

        <smth...></smth...>
        Chevy C
        <smth...></smth...>

        <smth...></smth...>
        Ford M
        Ford F
        <smth...></smth...>

let obj = [ // output
    {id: 0, name: 'Murray', job: 'frontend', experience: 6, cars: ['Audi QQQ']},
    {id: 1, name: 'Bob', job: 'cybersec', experience: 4, cars: ['Mers S']},
    {id: 2, name: 'Muhammad', job: 'backend', experience: 8, cars: ['Chevy C']},
    {id: 3, name: 'Vova', job: 'projmanager', experience: 12, cars: ['Ford M', 'Ford F']},
]

Нужно все это проделать с помощью функции jquery ".each()"

A: Залипушно конечно, но по описанию вопроса только так (нет)

let obj = [ // сюда должны добавить новое св-во из html
        {id: 0, name: 'Murray', job: 'frontend', experience: 6},
        {id: 1, name: 'Bob', job: 'cybersec', experience: 4},
        {id: 2, name: 'Muhammad', job: 'backend', experience: 8},
        {id: 3, name: 'Vova', job: 'projmanager', experience: 12},
    ]

$('.carsWrap').find('.col').each((index, element)=>
    {
        if(obj[index] && !obj[index].cars)
        {
            obj[index].cars = [];
        }
        $(element).find('.car').each((i, e)=>{
            obj[index].cars.push($(e).text())
        })
    })
    console.log(obj)

        <smth...></smth...>
        Audi QQQ
        <smth...></smth...>

        <smth...></smth...>
        Mers S
        <smth...></smth...>

        <smth...></smth...>
        Chevy C
        <smth...></smth...>

        <smth...></smth...>
        Ford M
        Ford F
        <smth...></smth...>


text:
Q: adapting the size of a function iteratively in matlab/ convert string to function I want to convert a string which is in a cell (size 2*len(x) × 4) into a function handle f=@(x) F.
The first line of F is
'x(1)'   'cos(2*pi*'  'F(1)'  '*1/Fe)'

The following lines are similar but the input of x is counting up. Fe and F are actually variables.
The size of the matrix F depends on the length of the vector x. It should be 2*len(x) x 1
Is this possible?
What I actually wanted to do is to write a function which size changes dependent on the size of the vector x. The only way I saw to adapt the size was to introduce the string.

A: I'm still quite fuzzy on the details (or why you want to do what you want to do), but I guess this (or something similar) would do the trick:
f = str2func(['@(x)' F{:}]);


text:
Q: C# Building a Method Variable inside another Method Variable I have a method and I am trying to add another method as a list variable so that I can add multiple Error's per file. I am currently passing the files list variable to multiple different functions. I would like the Error variable to be contained in the files, but I have been unable to figure it out. Thanks!
    class AllFiles
    {
        public string FileName { get; set; }
        public string FileType { get; set; }
        ...
        public List<ErrorClass> Error { get; set; }
    }

    class ErrorClass
    {
        public int ErrorCode { get; set; }
        public int Total { get; set; }
        public string ErrorMessage { get; set; }
        ...
    }

I use the following to initialize my files as a list so I can add multiple files.
        List<AllFiles> files = new List<AllFiles>();
        files.Add(new AllFiles());

I am wanting it to look like the following:
files[0]
   Error[0]
   Error[1]
files[1]
   Error[0]
   Error[1]
   Error[2]
files[2]
   Error[0]
   ...

A: You need to create an instance of the List<ErrorClass> (ideally) inside the AllFiles class' constructor, and assign it to the Error property.
Some other recommendations:

*

*AllFiles is not a good name for a class that represents one file

*ErrorClass could maybe just be called Error or FileError

*The Error property inside AllFiles should be named Errors and should have a private setter.

E.g.:
class MyFile {
  public MyFile() {
    Errors = new List<MyFileError>();
  }

  public string Name { get; set; }
  public string Type { get; set; }
  ...
  public List<MyFileError> Errors { get; private set; }
}

class MyFileError {
  public int Code { get; set; }
  public int Total { get; set; }
  public string Message { get; set; }
  ...
}

Depending on your design, you could better encapsulate the error list inside MyFile and just expose an IEnumerable<MyFileError> and an AddError(MyFileError) method.


text:
Q: How to update color on clientside_callback in plotly dash I am trying to create an app in dash that would use default plotly color palette for Piechart. However default palette for plotly.js is different from py version, so I am trying to edit this.
But the argument I pass into marker seems not to make any change whatsoever.
My current code is:
EDIT: This code actually works, but by the default, plotly.js starts coloring from the smallest value passed(I think). When I passed sorted values, it works exactly the same
@app.callback(
    Output('pie-store', 'data'),
    Input('key_input', 'value')
)
def update_store_data(key):
    accs, counts = zip(*crud.key_account_counts(db, key))
    return [{
        'values': counts,
        'labels': accs,
        'names': accs,
        'type': 'pie',
        'marker':{
            'colors' : plotly.colors.DEFAULT_PLOTLY_COLORS
        },
    }]

app.clientside_callback(
    """
    function(data) {
        return {
            'data': data,
        }
    }
    """,
    Output('clientside-pie', 'figure'),
    Input('pie-store', 'data'),
)


text:
Q: Can't load WASM in a Vue component In main.cpp:
#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
extern "C" {
    const char *testFunc(const char *parameter) {
        return parameter;
    }
}

Compilation command:
em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -o wasm_module.js;

In the Vue component:
import wasmModule from "./wasm/wasm_module.js"; // I put both WASM and JS wrapper in the same folder

export default {
  created() {
    console.log(wasmModule);
  }
};

In vue.config.js, I've added:
module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.wasm$/,
          loaders: ["wasm-loader"]
        }
      ]
    }
  }
};

But, I'm getting:
Uncaught (in promise) RuntimeError: abort(CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0) at Error

UPDATE
I ended using a slightly different compilation command, which was given by a member of the official WebAssembly Discord server:
em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS'["call", "cwrap"]' -s MODULARIZE -s ENVIRONMENT="web" -s EXPORTED_FUNCTIONS='["_testFunc"]' -o wasm_module.js

Then, I dug up in the wasm_module.js and found a variable scriptDirectory, which is responsible for locating the wasm_module.wasm file
After logging it to the console, it outputted:
http://localhost:8080/js/

So, I moved the .wasm file into public/js, and by the way, deleted the configureWebpack entry as it's now useless
Now, I could:
import wasmModule from "./wasm/wasm_module.js";
export default {
  async created() {
    const instance = await wasmModule();
    const func = instance._testFunc();
  }
};

However, there is still one problem:
No matter the arguments I pass into _testFunc, I'm getting the output 0 every single time

A: Turns out the solution was pretty simple
main.cpp
#include <emscripten.h>
#include <string>

EMSCRIPTEN_KEEPALIVE
extern "C" {
  std::string* testFunc(std::string* parameter) {
    return parameter;
  }
}

Compilation:
em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -s MODULARIZE -s EXPORTED_FUNCTIONS='["_testFunc"]' -o wasm_module.js

The wasm_module.js should be somewhere under src/
The wasm_module.wasm should be under public/js/
Then, the Vue component:
import moduleWasm from "./path/to/wasm_module.js";

export default {
  async created() {
    const instance = await moduleWasm();
    const func = instance.cwrap("testFunc", "string", ["string"]); // Note that: (func_name, return_type, [parameter_types])
    console.log(func("Hello World") === "Hello World"); // true
  }
};


text:
Q: API Gateway exposing DynamoDB (Complex mapping template or Lambda Function needed?) I am exposing my DDB via the AWS API Gateway. I have it working, but when I pass my "PUT" it's requiring me to include every field from my DDB in the body request. Some clients may only want to POST 5 fields of the 10 in my DDB. Would this be done as a POST or a PATCH? If so, what does my mapping template look like for these?
Second: I'd like to add an auto-generated order_number to each entry in the DDB. So now each PUT or POST will have a unique order_number. So my Primary Key will be a variable, and the secondary key would be a customer sku number, or vice versa.
Thanks for the help.

A: Body Template: I still need it to generate the "order_number"
   automatically for each new entry.
#set($inputSep = $input.path('$'))
#set($thisLoop =
'{"CustomerNm":"1","ShipDate":"2","Shipping":"3","commentId":"4"}')
#set($myPlaces = $util.parseJson($thisLoop))
#set($allKeys = '')
#set($myVals = '"')
{
"TableName": "BRPI",
"Key": {
    "CustomerID": {
        "S": "$input.path('$.CustomerID')"
    }
},
#foreach($type in $inputSep.keySet())
#if($type == "CustomerID")
#else
    #set($thisPlace = $myPlaces.get($type))
    #set($params = $inputSep.get($type))
    #set($thisKey = "$type" + " = :val" + "$thisPlace")
    #set($thisPath = "$params")
    #if($foreach.hasNext)
        #set($myComma = ",")
        #set($myReturn = '"')
    #else
        #set($myComma = "")
        #set($myReturn = "")
    #end
    #set($allKeys = "$allKeys" + "$thisKey" + "$myComma")
    #set($myVals = "$myVals" + ":val" + "$thisPlace" + '": {"S": "' +
"$thisPath" + '"}' + "$myComma" + "$myReturn")
#end
#end
"UpdateExpression": "SET $allKeys",
"ExpressionAttributeValues": {
    $myVals
},
"ReturnValues":"UPDATED_NEW"
}


text:
Q: Gaussian elimination algorithm performance I am developing the quadratic sieve algorithm and I reached a new bottle neck: The matrix processing.
I been reading quit a lot about this topic and I found many solutions

*

*Gaussian elimination: This perhaps the most common approach for this problem. It's running time is $O(N^3)$ above GF (2)

*Method of Four Russians: It optimize the classic Gaussian elimination to $O(\frac{N^3}{\log{N}})$ by partition the matrix into small square blocks of size $\log N$. You can read more about it here(section 3.2).

*Block Wiedemann algorithm is used to parallelize the matrix of several machines in order to speed up the process. Here is a good example of such implementation over GAPP, they use a little bit different algorithm for that.

But non of the above was good enough for me, so I created my own algorithm.
It's based on Gaussian elimination, but instead of searching for pivot in each column I represent the columns with hash table and linked list(This is how HashMap in java is implemented) where each node of the list is stored in hash table and contain the pivot index of the original matrix. So I can iterate over all the pivots of column.
When I start to perform Gaussian elimination it only takes $O(1)$ to find the first pivot of a column, once I find such pivot I store it in another hash  table, so I want pick it for the next column I will operate. Next I iterate over the reset of the pivot of the first column and xor the rows to eliminate all the reset of the pivot of the first column. I do the same trick with the rows, so I got duplicate representation of the matrix, by hash-table rows and columns. This allows me to speed up the row xoring process as I only iterate over the row pivot. The xor operation itself of each node is $O(1)$ but it evolves 2 hash operations and it's by it self quite expensive. And so this is the part where this algorithm fails. Even so that I estimate it's performance as sub-quadratic on average.
I ended up implementing classic Gaussian elimination using bit operators and it allows me to process square matrices with up to $10,000$ lines in minutes time. But it's not fast enough for me, my goal is factoring 100 digits number, this require around 1M square matrix size, and this impossible with my current approach.
Is there any other methods that I missed? What is the best non parallel method to solve this problem?

A: Your approach to Gaussian elimination is fundamentally at odds with the currect state of hardware. You are up against the memory wall, i.e. the fact that floating point operations can be completed at a rate which is far higher than the speed at which data can be retrieved from may memory. By processing your matrix one column at a time, your are constantly experiencing cache misses and you CPU is running at a fraction of the peak rate. A truly enourmous amount of research involving many good people working together for many years, has gone into developing blocked algorithms which facilitate reuse of the data stored in the cache hierarchy.
On a "standard" desktop with a Haswell chip, running at 3.6 GHz a random matrix of dimension $N=10,000$ can be factored using around 4.5 seconds using the dense factorization routine in LAPACK.
It is possible to write fast matrix factorization routines based on Strassens matrix matrix multiplication with roughly $O(N^{2.6})$ complexity, but I cannot recommend this approach due to unresolved stability issues.
So to answer you question, the best sequential algorithms for GE currently available is are implementations of LAPACK's DGETRF/DGETRS which factors and solves general nonsingular linear systems. You should be able to obtain an implementation through www.netlib.org.


text:
Q: Urldecode in PHP I was wondering...my friend and I were having a debate over this.
Is there anything I could pass in the url to get to the echo call (The one that says "Yay potatoes!!!" sorry was unclear)?
<?
if(eregi("potato",$_GET[id])) {
  echo("
Awww no potatoes :c </3
");
  exit();
}

$_GET[id] = urldecode($_GET[id]);
if($_GET[id] == "potato")
{
  echo "
Yay potatoes!!!!!
";
}
?>

A: Yes.  You can double-encode a character (or more)
?id=%2570otato

PHP will decode the first one and give you:
$_GET['id'] = "%70otato"

This will pass eregi() without exiting.  Then, you run urldecode() on it, which gives you potato.
Yay, potatoes.  Codepad example:  http://codepad.org/IYwizCXK


text:
Q: How do I Check previous data in LINQ? I have a collection of data that checks if there is a change in a particular field to get the sum for another column.
Total = Details.Where(s=>s.indicator != *prior indicator before this...).Sum(s => s.amount);

A: I dont think that LINQ by itself can get you the state of the data before it was changed. What I guess you could do is to set an event when the data is about to change (OnChanging) and subscribe to that event, then you would send the amount before the change on the event's parameter.
Now if you want to do all of this in a LINQ-ish way, you should check out the Rx (Reactive) API that MS is working on, its all about using events in a LINQ way.
If you are using a collection that notifies you of the change in the element.. then there might be a parameter being passed that tells you the data that changed.

A: You could use a partial class and then use the OnFIELDChanging event to detect the change and call an event elsewhere.
So if you have a User table in your .dbml file which has a property called say FirstName then you could create another class like this;
public partial class User
{
    partial void OnFirstNameChanging(string value)
    {
    }
}

The value passed over is the new value the property is changing to.
Does this help or am I off base with regards to your requirements?

A: If you have two collcection of data you could use the zip method (.Net 4.0) like so
var Total = currentData.Zip(previousData,(current,previous) => current.indicator != previous.indicator ? current.amount : 0).Sum();

if you don't use .net 4.0 you could use this implementation of zip :
static class Enumerable
{
 public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func)
 {
  var ie1 = first.GetEnumerator();
  var ie2 = second.GetEnumerator();

  while (ie1.MoveNext() && ie2.MoveNext())
   yield return func(ie1.Current, ie2.Current);
 }
}

source


text:
Q: Consider the stability of a equilibrium point
For
$$
\dot{x}=x+f(x,y),\quad \dot{y}=-y+g(x,y)
$$
where $f,g\in$ Lip $(\mathbb{R}^2,\mathbb{R})$ and
$$
|f(x,y)|\leq c(x^2+y^2),\quad |g(x,y)|\leq c(x^2+y^2)
$$
in a neighborhood of the origin, consider the stability of $(0,0)$.

After I tried several special $f,g$, I believe the origin is Lyapunov stable, but I do not know how to prove the general case. I tried to constuct some Lyapunov function but failed. I have no idea how to use the Lipschitz condition.
Could you give me some hint to find a Lyapunov function? Or you can suggest your own way. Appreciate any help!


text:
Q: $\lim_{k \to \infty} A^k$ where $A$ is diagonalizable I'm reviewing diagonalization and am wondering if the following makes sense. Let $A \in \mathcal{M}_{n \times n}(\mathbb{R})$ be a diagonalizable matrix. That is, there exist matrices $D$ and $P$ such that
$$
A = PDP^{-1}
$$
where the columns of $P$ are linearly independent eigenvectors of $A$ and the $D$ is a diagonal matrix whose diagonal entries are the eigenvalues of $A$ (repeated based on their respective multiplicities). Does it follow that
$$
\lim_{k \to \infty} A^k = 0
$$
if each eigenvalue of $A$ is in the range $(-1, 1)$? My reasoning is that (from elementary linear algebra) we can show that
$$
A = PD^kP^{-1}
$$
if $A$ is diagonalizable. Since $P$ and $P^{-1}$ are finite, the product should approach zero since each (diagonal) entry of $D$ will approach zero since
$$
\lim_{k \to \infty} \lambda^k = 0
$$
if $-1 < \lambda < 1$. Does this make sense or is my reasoning flawed?

A: Taking into account that all the operations (sums and products of real numbers) involved in the product $PD^kP^{-1}$ are continuous, you get
$$
\mathrm{lim}_{k\rightarrow \infty}\ A^k = P\cdot \mathrm{lim}_{k\rightarrow \infty}\ D^k\cdot P^{-1}  \ .
$$
Then, for
$$
D =
\begin{pmatrix}
\lambda_1  &  0         & \dots & 0         \\
0          & \lambda_2  & \dots & 0         \\
\dots                                       \\
0          &  0         & \dots & \lambda_n
\end{pmatrix}
$$
you obviously also have
$$
\mathrm{lim}_{k\rightarrow \infty}\
D^k =
\mathrm{lim}_{k\rightarrow \infty}\
\begin{pmatrix}
\lambda_1^k  &  0         & \dots & 0         \\
0          & \lambda_2^k  & \dots & 0         \\
\dots                                       \\
0          &  0         & \dots & \lambda_n^k
\end{pmatrix}
=
\begin{pmatrix}
\mathrm{lim}_{k\rightarrow \infty}\ \lambda_1^k  &  0         & \dots & 0         \\
0          & \mathrm{lim}_{k\rightarrow \infty}\ \lambda_2^k  & \dots & 0         \\
\dots                                       \\
0          &  0         & \dots & \mathrm{lim}_{k\rightarrow \infty}\ \lambda_n^k
\end{pmatrix}
$$
from which your conclusion follows: if for all $\lambda_i$ you have $|\lambda_i | < 1$, then $\mathrm{lim}_{k\rightarrow \infty}\ \lambda_i^k = 0$, hence $\mathrm{lim}_{k\rightarrow \infty}\ D^k = 0$, hence $\mathrm{lim}_{k\rightarrow \infty}\ A^k = P \cdot 0 \cdot P^{-1} = 0$.
Remark. To be picky, that "obviously" over there means something like you are considering the product topology in the space of matrices ${\cal M}_{m\times n}(\mathbb{R}) = \mathbb{R}^{m\times n}$ and then the continuity of a function of matrices is checked component-wise. So the limit of a function of matrices is the limit of everyone of its components. A similar remark applies for the first statement about the continuity of $PD^kP^{-1}$.


text:
Q: What happens when I close/abort a WCF channel/proxy? I'm trying to get a better understanding of what's going on when I use a WCF proxy. I'm having trouble understanding what happens when I close (or don't close) a proxy.

*

*What's going on when I call Close() or Abort() on a WCF proxy? What's the difference?

*How does it differ between types of bindings (like, a sessionless BasicHttpBinding vs. something sessionful)?

*Why can Close() throw in certain situations and why can it be a blocking operation?

A: Closing WCF client
A client has an inherited responsibility of gracefully closing the connection. It is always recommended to close a proxy client. If the binding between a client and a service is transport-layer sessionful, then closing a proxy is essential to tear down the connection between both parties. Service has a payload threshold defined for concurrent connections. If the number of concurrent connections goes above this threshold linearly then the overall service performance decreases exponentially. This is why it is crucial to dispose of the connection as soon as possible. Closing the proxy also notifies the service instance that it is no longer in use and may be collected by GC (subject to service instance management). If the client does not close a connection, it is still automatically torn down by WCF timeouts (found in the configuration files).
Aborting WCF client
In the situation where there is a fault in the service-client interaction, the objects on both ends are potentially totally broken. Thus using a proxy after the exception is not advised. Given the WCF binding use transport sessions, the client after a fault would not even be able to close it (if there was no transport layer session then the client could use or close the proxy, but this is not recommended as the configuration of sessions could change). So after a fault has happened the only safe operation is to abort a proxy.
Close is a synchronous operation, it can throw if the transport session has been damaged by a fault and it is a blocking operation until a confirmatory response from service is received (true for some bindings).


text:
Q: The system cannot find the reference specified for an assembly I have a VB.NET solution which have a few projects and a 'References' folder in the root directory.
Now I want to add a new dll reference to one of the projects from this References folder but getting the following message:

The system cannot find the reference specified

How can this be solved?

A: I encountered this many times. Here I was trying to execute a jar file when a picturebox was clicked. I added my jar to my resources :
Private Sub PictureBox9_Click(sender As Object, e As System.EventArgs) Handles _PictureBox9.Click
        Dim dir As String = My.Computer.FileSystem.SpecialDirectories.Temp
        Dim filename As String = dir + "minecraft.jar" 'Look Below
        IO.File.WriteAllBytes(filename, My.Resources.minecraft)
        Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "minecraft.jar")
End Sub
The following worked for other programs though, but not minecraft, :
Private Sub Panel9_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel9.Click
        proc = Process.Start("vbexpress.exe", "")
End Sub
*proc was a New System.Diagnostics.Process()
But for actual files, you have manually lure them out of their location.
So I did Me.Resources.1234.png which saved me writing the directory. But this still did not work with minecraft, so I kept that long paragraph about in place.


text:
Q: Quasar 2 Vue 3 Cypress component test fails to locate existing src/css/app.scss Running cypress component test bump into the folllowing error:
The following error originated from your test code, not from Cypress.

> Cannot find module 'src/css/app.scss'

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

The existing src/css/app.scss is referenced in test/cypress/support/component.js with the following content added by running quasar ext add @quasar/testing-e2e-cypress:
import './commands';

// Change this if you have a different entrypoint for the main scss.
import 'src/css/app.scss';
// Quasar styles
import 'quasar/src/css/index.sass';

// ICON SETS
// If you use multiple or different icon-sets then the default, be sure to import them here.
import 'quasar/dist/icon-set/material-icons.umd.prod';
import '@quasar/extras/material-icons/material-icons.css';

import { installQuasarPlugin } from '@quasar/quasar-app-extension-testing-e2e-cypress';
import { config } from '@vue/test-utils';
import { Dialog } from 'quasar';

// Example to import i18n from boot and use as plugin
// import { i18n } from 'src/boot/i18n';

// You can modify the global config here for all tests or pass in the configuration per test
// For example use the actual i18n instance or mock it
// config.global.plugins.push(i18n);
config.global.mocks = {
  $t: () => '',
};

// Overwrite the transition and transition-group stubs which are stubbed by test-utils by default.
// We do want transitions to show when doing visual testing :)
config.global.stubs = {};

installQuasarPlugin({ plugins: { Dialog } });

https://github.com/quasarframework/quasar-testing/issues/278


text:
Q: How do I create barplots with categories instead of numbers? I'm just getting started in R and I'm trying to wrap my head around barplot for a university assignment. Specifically, I am using the General Social Survey 2018 dataset (for codebook: https://www.thearda.com/Archive/Files/Codebooks/GSS2018_CB.asp) and I am trying to figure out if religion has any effect on the way people seek out help for mental health. I want to use reliten (self-assessment of religiousness - from strong to no religion) as the IV and tlkclrgy, (asks if a person with mental health issues should reach out to a religious leader - yes or no) as the DV. For a better visualization of the data, I want to create a side-by-side barplot with reliten on the x-axis and see how many people answered yes and no on tlkclrgy. My problem is that on the barplot I get numbers instead of categories (from strong to no religion). This is what I tried, but I keep getting NA on the x-axis:
GSS$reliten <- factor(as.character(GSS$reliten),
                      levels = c("No religion", "Somewhat
                                 strong", "Not very strong",
                                 "Strong"))
GSS <- GSS18[!GSS18$tlkclrgy %in% c(0, 8, 9),]
GSS$reliten <- as_factor(GSS$reliten)
GSS$tlkclrgy <- as_factor(GSS$tlkclrgy)
ggplot(data=GSS,mapping=aes(x=reliten,fill=tlkclrgy))+
  geom_bar(position="dodge")

Does anybody have any tips?

A: Here is complete code to download the codebook and data, table the two columns of interest and plot the frequencies.
1. Read the data
Data will be downloaded to a temporary directory, to keep my disk palatable. Use of these first two instructions is optional
od <- getwd()
setwd("~/Temp")

These are the links to the two files that need to be read and the filenames.
cols_url <- "https://osf.io/ydxu4/download"
cols_file <- "General Social Survey, 2018.col"
data_url <- "https://osf.io/e76rv/download"
data_file <- "General Social Survey, 2018.dat"

download.file(cols_url, cols_file, mode = "wb")
download.file(data_url, data_file, mode = "wb")

Now read in the codebook and process it, extracting the column widths and column names.
cols <- readLines(cols_file)
cols <- strsplit(cols, ": ")
widths_char <- sapply(cols, '[', 2)
i_widths <- grepl("-", widths_char)

f <- function(x) -eval(parse(text = x)) + 1L
widths <- rep(1L, length(widths_char))
widths[i_widths] <- f(widths[i_widths])

col_names <- sapply(cols, '[', 1)
col_names <- trimws(sub("^.[^ ]* ", "", col_names))
col_names <- tolower(col_names)

Finally, read the fixed width text file.
df1 <- read.fwf(data_file, widths = widths, header = FALSE, na.strings = "-", col.names = col_names)

2. Table the data
Find out where are the two columns we want with grep.
i_cols <- c(
  grep("reliten", col_names, ignore.case = TRUE),
  grep("tlkclrgy", col_names, ignore.case = TRUE)
)

head(df1[i_cols])

Table those columns and coerce to data.frame. Then coerce the columns to factor.
Here there is a problem, there is no answer 3 for tlkclrgy in the published survey but there are answers 3 in the data file. So I have created an extra factor level.
GSS <- as.data.frame(table(df1[i_cols]))

labels_reliten <- c(
  "Not applicable",
  "Strong",
  "Not very strong",
  "Somewhat Strong",
  "No religion",
  "Don't know",
  "No answer"
)
levels_reliten <- c(0, 1, 2, 3, 4, 8, 9)
labels_tlkclrgy <- c(
  "Not applicable",
  "Yes",
  "No",
  "Not in codebook",
  "Don't know",
  "No answer"
)
levels_tlkclrgy <- c(0, 1, 2, 3, 8, 9)

GSS$reliten <- factor(
  GSS$reliten,
  labels = labels_reliten,
  levels = levels_reliten
)
GSS$tlkclrgy <- factor(
  GSS$tlkclrgy,
  labels = labels_tlkclrgy,
  levels = levels_tlkclrgy
)

3. Plot the frequencies table
library(ggplot2)

ggplot(data = GSS, mapping = aes(x = reliten, y = Freq, fill = tlkclrgy)) +
  geom_col(position = "dodge")


text:
Q: Converting Multiset Count into a List Java Is there any way to pull the count from a Multiset into a list?
String[] data = loadStrings("data/data.txt");

Multiset<String> myMultiset = ImmutableMultiset.copyOf(data);

for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
    System.out.println(word + ": " + myMultiset.count(word));
    // ...
}

As it stands I can output the most commonly occurring words into the console in Processing. I was wondering if it is at all possible to add the corresponding words and their count into an array or a list. I have tried like so:
for (String word : Multisets.copyHighestCountFirst(myMultiset).elementSet()) {
    float a[] = myMultiset.count(word);
}

but only received errors stating I cannot convert an int to a float[]
Is this even possible? Am I going about it all wrong? I've never used Multisets before so any help would be really useful
UPDATE:
I have used this to get a copy of the highest count but am unable to convert it into a list.
Multiset<String> sortedList = Multisets.copyHighestCountFirst(myMultiset);

A: Please see Multiset.entrySet() docs:

Returns a view of the contents of this multiset, grouped into Multiset.Entry instances, each providing an element of the multiset and the count of that element.

So, i.e. to get the top 5 most occurring owrds, I'd loop over the entrySet():
ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);

Iterator<Multiset.Entry<String>> it = top.entrySet().iterator();

for (int i = 0; (i < 5) && it.hasNext(); i++) {
    Multiset.Entry<String> entry = it.next();

    String word = entry.getElement();
    int count = entry.getCount();

    // do something fancy with word and count...
}

I'm assuming you need to show the top 5 most occurring words and their frequencies. If you only need the words, just use asList() method:
ImmutableMultiset<String> top = Multisets.copyHighestCountFirst(myMultiset);

ImmutableList<String> list = top.asList();

and iterate over list to get the first 5 elements.


text:
Q: Why use the value "mIsBootImageOnDisk " in service DeviceStorageMonitorService I see the git log and find the change If53c236058a7237d735c2344a715cf0a36301f9b, it added a final value mIsBootImageOnDisk in the constructor function DeviceStorageMonitorService. But, it seems useless! Who can tell me?
I see the modification is for Bug: 17679443. Who can tell me where to see the bug information ?
enter image description here

A: There seems to be no entry for 17679443 in the Android Open Source Project - Issue Tracker. I'm going to guess that this is an internal bug number. The error comes from what the documentation describes as retrieving the boot class path from disk storage rather than the dirty pages in memory (the method itself calls isBootClassPathOnDisk which has a native implementation in the art runtime dalvik_system_VMRuntime.cc). I'm experiencing this error now as it processed the arm instruction set (the only instruction set processed by the system). I'm wondering if I'm experiencing a permission issue of some sort that does not allow the image header to be read properly.
The error message that results from not having enough storage space is completing misleading as I'm looking at a df listing where my system partition has 730 MB free and the data partition has 4.8 GB free (actually all the mounted partitions > 250 MB).
Hopefully, someone else will have a solution to this issue. I would hate to have to resort to stubbing out the method with a return true just to get rid of the notification -- there is probably an issue elsewhere in my firmware that needs to be fixed.
So my answer to this question, which I don't need clarification from the OP on to answer, is that there is nothing you can do right now. There are no obvious user forums either here on StackOverflow, in the AOSP issue tracker, or on another user forum like NXP/Freescale (for example) where a better answer or even background to this bug is provided.


text: Q: Razor Engine with layout page outside of a web project I am currently using the razor engine in a class library to render HTML for emails for an application.  This is working fine but as the number of email templates have gone up I would now like to implement master pages as well.  Is it possible to do this?  When I tried it, it gives me a null reference exception when parsing the view


text:
Q: Better Grid for VB6 that supports row and column spanning? Can anyone suggest me better grid for vb 6 which have row-span, column-span facility and can work with around 150000 rows.
So we can achieve following kind of solution.

A: We use VSFlexGrid. They have products for ActiveX that incorporate nicely with VB6 and the IDE. It's not free.
The row-span and column-span can probably be accomplished with its cell-merging features.

The other configuration can be done through a GUI at design-time or through code at run-time.

A: I've been using Spread in my application for 10+ years.  You can do colspan and rowspan plus a whole lot more.
Spread

A: I've always used Infragistics and ComponentOne products, but I did a quick search and found SCGrid (http://scgrid.com/).  It has RowSpan and ColSpan properties and has a free version available.


text:
Q: How to locate the element by using dynamic x-path for link? I am trying to find the element using Dynamic x path but my code is not working for the element
+Our Services

Want to select sub-menu by using Action class but here i am unable to locate the element

A: To click() on the sub-menu you can use either of the following Locator Strategies (Java Solution):

*

*cssSelector:
driver.findElement(By.cssSelector("a.has-submenu[href='/corporate-checkups/our-corporate-services.html']>span.sub-arrow")).click();

*xpath:
driver.findElement(By.xpath("//a[@class='has-submenu' and @href='/corporate-checkups/our-corporate-services.html']/span[@class='sub-arrow']")).click();

A: Basically your locator its a link so you have to very simple options :
driver.findElement(By.partialLinkText("Element LINKTEXT"));

driver.findElement(By.LinkText("Element LINKTEXT"));

Choose which one you think works better for you.


text:
Q: Передача кастомных элементов в bundle | Android Как мне передать кастомный тип элементы в Bundle. Например, я хочу передать List, но не понимаю как. Почитал статьи и прочее, но после всех попыток получал только ошибки. Сейчас уже не могу сказать, какие точно. Может ли кто-то объяснить мне, как сделать это правильно?

A: Есть несколько вариантов отправки списка List. Первый способ как и второй  - заполнение списка объектами класса который вам нужен и отправка. При это класс должен быть либо parcelable либо serializable, но лучше использовать parcelable. Пример serializable класса:
public class Person implements Serializable {
    private int id;
    private String name;

    public Hospitals(int id, String name)
    {
       this.id = id;
       this.name = name;
    }
  ....
}

Дальше вы из этого list делаете arraylist:
List<ClassObject> yourList = ...;
ArrayList<ClassObject> arrList = new ArrayList<>(yourList.size());
arrList.addAll(yourList);

и отправляете через bundle:
Bundle bundle = new Bundle();
bundle.putSerializable("valuesArray", arrList);

Второй вариант - конвертируем ваш объект в json и отправляем в через bundle как стринг:
String jsonList = gson.toJson(yourList);
Bundle bundle = new Bundle();
bundle.putString(...);

Но стоить помнить что у bundle есть ограничение на 1MB (пруф):

The Binder transaction buffer has a limited fixed size, currently 1MB,
which is shared by all transactions in progress for the process.

Поэтому третий вариант будет без использования bundle вообще. Нужно создать класс в котором будет поле вашего списка и после заполнения этого списка в активности вы должны сетить этот список в отдельный класс. После того как список теперь находится и в другом классе тоже, то значит вы можете его взять откуда угодно в том числе и с целевой активности. Для начала создаем класс-синглтон:
public class Single {

    private static final Single INSTANCE = new Single();

    private Single(){}

    public static Single getInstance(){
        return INSTANCE;
    }
}

дальше создаем в нем поле вашего массива и метод чтобы взять этот массив и добавить в него данные:
List<YourObject> myList = new List()
public List<YourObject> getArray() {
     return this.myList ;
}
public void addToArray(YourObject obj) {
     myList.add(obj);
}

и теперь вы можете засетить данные:
Sindle.getInstance().getArray()

и взять данные:
Sindle.getInstance().myList

Вот пример работы с синглтоном. Если же вам нужно добавить сразу весь список а не по одному элементу то нужно использовать addAll(). Вот документация про List. Ну и последний вариант - использовать sharedPreference. Этот метод не совсем хорош для таких целей но задачу тоже можно выполнить:
Set<String> tasksSet = new HashSet<String>(objList);
PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("tasks_set", tasksSet)
    .commit();

и считываем его где вам нужно:
Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
    .getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);

Так же в sharedPreferences можно записать стринг json (конвертировать так как я выше показывал) и взять где вам нужно. Запись:
SharedPreferences settings = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", value).apply();

и считываем где вам нужно:
SharedPreferences settings = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
String data = settings.getString("some_key", "defaultValue");

A: @Andrew забыл только указать (упомянул вскольз) про штатный вариант с Parcelable.
Между тем, это штатный (нативный для Android) вариант, который в силу своей реализации обеспечивает очень быструю передачу и без использования сериализации и связанных с этим ограничений, в частности в документации пишется, что:

Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport.

То есть по сути Parcelable - это специальный протокол передачи данных между разными процессами, который опирается на низкоуровневую реализацию с использованием особенностей реализации ядра ОС Android.
Для использования этого протокола нужно своем классе реализовать интерфейс Parcelable со статическим полем CREATOR, далее уже как обычно: putParcelable()/getParcelable()
Для сравнения эффективность Parcelable vs. Serializable


text:
Q: How to set AWS Appsync request timeout limit || AWSAppSync Client not giving callback I'm using AWS Appsync for the current App I'm developing and facing a serious issue that is Whenever I fire queries in Appsync client, when there is slow internet connection the request never end with a callback. I checked over internet there is limited source of information on this topic and also found this issue that is still open.
This is the code I used to get the response
func getAllApi(completion:@escaping DataCallback){
    guard isInternetAvailabele() else {
        completion(nil)
        return
    }
    // AppSyncManager.Client() is AWSAppSyncClient Object
    AppSyncManager.Client().fetch(query: GetlAllPostQuery(input: allInputs), cachePolicy:.fetchIgnoringCacheData) {
        (result, error) in
        var haveError:Bool = error != nil
        if let _ = result?.data?.getAllPostings?.responseCode {haveError = false} else {haveError = true}
        if haveError  {
            print(error?.localizedDescription ?? "")
            completion(nil)
            return
        }

        if result != nil{
            completion(result)
        }else{
            completion(nil)
        }
    }
}

The code works fine with internet connection and I have already checked at the top if there is no internet but when there is slow internet connection or the wifi is connected to a hotspot that I created with my mobile with internet data disabled the request doesn't return any callback it should give failed alert like we get in other apis when the request time out.
Is there any support for request for request time out or did I miss something?

Note : I recieved these logs in Terminal

Task <06E9BBF4-5731-471B-9B7D-19E5E504E57F>.<45> HTTP load failed (error code: -1001 [1:60])
Task <D91CA952-DBB5-4DBD-9A90-98E2069DBE2D>.<46> HTTP load failed (error code: -1001 [1:60])
Task <06E9BBF4-5731-471B-9B7D-19E5E504E57F>.<45> finished with error - code: -1001
Task <D91CA952-DBB5-4DBD-9A90-98E2069DBE2D>.<46> finished with error - code: -1001

A: Actually there could be two possible ways to fix the issue,
1) While configuring AWSAppSyncClientConfiguration, provide a custom URLSessionConfiguration and set the request timeout to your needs,
extension URLSessionConfiguration {

    /// A `URLSessionConfiguration` to have a request timeout of 1 minutes.
    static let customDelayed: URLSessionConfiguration = {
        let secondsInOneMinute = 60
        let numberOfMinutesForTimeout = 1
        let timoutInterval = TimeInterval(numberOfMinutesForTimeout * secondsInOneMinute)

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = timoutInterval
        configuration.timeoutIntervalForResource = timoutInterval
        return configuration
    }()
}

And pass this session configuration i.e URLSessionConfiguration.customDelayed when initializing AWSAppSyncClientConfiguration as it accepts the URLSessionConfiguration in the below constructor,
public convenience init(url: URL,
                        serviceRegion: AWSRegionType,
                        credentialsProvider: AWSCredentialsProvider,
                        urlSessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default,
                        databaseURL: URL? = nil,
                        connectionStateChangeHandler: ConnectionStateChangeHandler? = nil,
                        s3ObjectManager: AWSS3ObjectManager? = nil,
                        presignedURLClient: AWSS3ObjectPresignedURLGenerator? = nil) throws {

2) If the first doesn't work then you have another option to edit/unlock the pod files directly. There is a class AWSAppSyncRetryHandler where you can change the logic for retrying request. If you are able to fix the issue then you can fork the original repo, clone your repo, make changes in your repo and in pods file point this pod to use your repository. This should be done as changing the pod files directly is absolutely wrong until you are really stuck and want to find some solution.
Update: This issue has been fixed with AppSync SDK 2.7.0


text:
Q: Why does xarray DataArray only contain NaNs after combining it with a xarray DataSet? I want to create daily histograms from a pandas Dataframe (df) and export them to xarray to combine it with another Dataset (data).  When I create the DataArray I can access it without problems, but once I combine it with the Dataset the array I added only consists of nan-entries. I think I made sure that all coordinates correctly align, by normalizing the time coordinate and making sure that the spatial coordinates are the same. Something is going wrong and I am running out of ideas. Any help would be greatly appreciated!
df=pd.read_csv(filepath+dfname)
data=xr.open_dataset(filepath+bgc_xarray)

df['date'] =  pd.to_datetime(df['date'])
data['time'] = data.indexes['time'].normalize()

xedges = np.arange(lonmin,lonmax+2*spacing,spacing)
yedges = np.arange(latmin,latmax+2*spacing,spacing)
latitude = xedges[:-1]
longitude = yedges[:-1]

for i in range(2):
    df_i=df[df['date'] == data.time[i].values]

    x = df_i['cell_ll_lon']
    y = df_i['cell_ll_lat']
    weights = df_i['fishing_hours']
    hist, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges), weights=weights)
    fishing_effort = hist.T

    Xarray_i = xr.DataArray(
        data=fishing_effort,
        dims=['longitude', 'latitude'],
        coords=dict(
            longitude=(['longitude'], longitude),
            latitude=(['latitude'], latitude),
            time = data.time[i].values),
        attrs=dict(
            description='Fishing Effort',
            units='hours',),)

    if i == 0:
        Xarray = Xarray_i
    else:
        Xarray = xr.concat([Xarray, Xarray_i], 'time')

data['fishing_effort'] = Xarray

A: Oh ok, the problem was with the spatial coordinates apparently. This fixed it:
longitude=(['longitude'], data.longitude.values),
latitude=(['latitude'], data.latitude.values),


text:
Q: MySQL very long number data type Which data type should I use to store a number(ID) like "10196385171799537224"(21 digits) in MySQL database?

A: You can store it as numeric(21,0)
See SQL Fiddle Demo

A: Per the MySQL docs, you'd need a NUMERIC(21,0).
However, that's a unfeasibly large ID. Adding entries at a rate of one per microsecond, it would take over 300,000 years to reach that number. You might want to reconsider your design.


text:
Q: Error in shinyApp(ui, server) : `server` missing from shinyApp I have this below code:
library(shinydashboard)
library(shiny)

ui <- shinyUI( dashboardPage(dashboardHeader(title = "example"),
    dashboardSidebar(),
    dashboardBody(h3("text format"),
    mainPanel(
    infoBox("123", "Today's work", "Lots of pending", width = 6)
    infoBox("234", "Today's work", "completed", width = 6)
    ))))
server <- shinyServer({})
shinyApp(ui, server)

Can someone help me out on the error?
Also I want  "Today's work" text in infoBox to be in normal case letters, not in bold case letters.

A: This should solve it:
server <- shinyServer(function(input, output){})

Here is the complete code:
library(shinydashboard)
library(shiny)

ui <- shinyUI( dashboardPage(dashboardHeader(title = "example"),
                             dashboardSidebar(),
                             dashboardBody(h3("text format"),
                                           mainPanel(
                                             infoBox("123", "Today's work", "Lots of pending", width = 6),
                                             infoBox("234", "Today's work", "completed", width = 6)
                                           ))))
server <- shinyServer(function(input, output){})
shinyApp(ui, server)

Result:


text:
Q: Path not printing string values I recently found this really handy library for pdf conversion. I am trying to convert a pdf to string values. In order to parse the data and convert to a csv file. I want to automate this for future so I cannot use Tabula.
I am calling some modules in order to convert pdf to string.
The part for string conversion is not working. (pdf2string.py)
Here is part for the pdf conversion to string.
I get no error. Success. But, there is no output.
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import HTMLConverter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
import re
import csv
import sys

def convert_pdf_to_html(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = HTMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0 #is for all
    caching = True
    pagenos=set()
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True):
        interpreter.process_page(page)
    fp.close()
    device.close()
    str = retstr.getvalue()
    retstr.close()
    return str

    print str

if __name__ == '__main__':
    if len(sys.argv) == 2:
        path = sys.argv[1]
        convert_pdf_to_html(path)

This is my bash.
python pdf2string.py example.pdf

Script is pdf2string.py and path is example.pdf.
I am also new to high-level logic in python.

A: Edit: you are returning before printing - remove return str, or remove print str and use the advice below.
You're not printing the output of convert_pdf_to_html(), or saving it somewhere.
print convert_pdf_to_html(path)


text:
Q: Cassandra multi-column Filtering After a lot of searching I cannot find good documentation on "many-to-many" relationships which I want to filter multiple values on.
I will use games as an example
Games have 1 to many Distributors
Games have 1 to many Producers
Games have 1 to many Developers

my goal is find all games which have filters on distributor, producer or developers.
now from research, I can use the "in" operator, although I have read that is not the recommended practice due to one node reaching out to multiple nodes, instead of the server simply reaching out to those nodes directly. (correct me if I am wrong)
now the question I have is, how granular should I go with the data?
do I simply need this, then cross reference the results locally?
GamesByDistributor
GamesByProducer
GamesByDeveloper

or should I get even more granular like this:
GamesByDistributorANDProducer
GamesByDistributorANDDeveloper
GamesByDeveloperANDProducer
GamesByDeveloperProducerANDDistributor

the granular options would allow me to query on 1 to all of the items and all of their combinations to get back only the items I want, instead of cross referencing the values from each of the Distributor, producer and developer partitions.
is this recommended, or are there better ways to handle this specific situation?

A: You can model 1-to-many via the various collection data types (there are some limitations on volumes). Have you tried that?
The best way to model your data is by your queries so, potentially yes - the even more granular approach you mention might be appropriate (remember writes are cheap).
Another option would be to look at a (kindof) bitmap index based around your partition keys.
You can also look at secondary indexes - Depending on your version you could use SASI indexes (https://issues.apache.org/jira/browse/CASSANDRA/component/12328927/?selectedTab=com.atlassian.jira.jira-projects-plugin:component-summary-panel) or even a lucene approach via https://github.com/Stratio/cassandra-lucene-index or DataStax Enterprise Search.
Hope that helps.

A: You may want to consider DSE Graph or Open Source Titan for your data model.


text:
Q: Undefined reference to `(anonymous namespace):: I have a namespace that I am currently using in two classes. When I try to compile my project, I get that error but my namespace is not anonymous!
One of my classes looks like this:
//margin.cpp
#include <math.h>
#include "margin.h"
#include "anotherClass.h"
#include "specificMath.nsp.h" //My namespace

double margin::doSomeMath(double a, double b){
    return specificMath::math_function1(0, 1, 0);
    // Just a simpler, random example
}

My namespace looks like this:
//specificMath.nsp.h
#ifndef specificMath
#define specificMath
namespace specificMath {
     double math_function1(double, double, double);
     double math_function1(double);
     //more functions
}

 //specificMath.nsp.cpp
 #include <stdlib.h>
 #include "constants.h"
 #include "specificMath.nsp.h"

 namespace specificMath{
     double math_function1(double a, double b, double c){
          //some code
     }
     ... more functions
 }

When I try to compile, it seems to compile fine, but when linking (and I've been doing "make clean" to make sure it's using the new files) I get an error saying:
margin.o: In function `margin::doSomeMath(double, double)':
margin.cpp:(.text+0x3d): undefined reference to `(anonymous namespace)::math_function1(double, double, double)'

Why does it think it's an anonymous namespace? How can I fix this?
I compile doing this:
g++ -I. -c -w *.h *.cpp

And then...
g++ -o myProgram *.o

A: You #defined the namespace name away. After the preprocessor sees #define specificMath, then it finds all instances of specificMath after that and replaces them with what you #defined it to, which in this case, is nothing. So it simply eliminates it.
#ifndef specificMath
#define specificMath
namespace specificMath {

After the preprocessor runs
namespace {

Always use all capitals for macros, and never prepend underscores to them.
#ifndef SPECIFIC_MATH_FUNCTIONS

for example.

A: It think it is an anonymous namespace because you made it anonymous with
#define specificMath

so "specificMath" will expand to nothing.
You could give the definition an identifier, e.g.
#define specificMath specificMath

or just don't use the same identifier for both the include guard and namespace.
#ifndef SPECIFIC_MATH_H
#define SPECIFIC_MATH_H
namespace specificMath { ... }
#endif

A: Your ifdef macros are interfering with your mamespace names.


text:
Q: Conditional write using cloud dataflow and pubsub I am trying to use cloud dataflow's Python API to write a simple program that accepts input from a pubsub publisher, checks the input for a condition, and then outputs data to a topic. I have gotten the program written to where it is accepting and transforming input, as well as publishing data to a topic. My problem is that I want to only publish to the topic if a condition is true. For instance, if a keyword is present in the json data, then I want to publish a message to the pubsub topic, but not publish a message when the keyword doesn't exist. I have tried adding a global boolean flag that becomes true when a keyword is found, and wrapped it around these lines:
output = (lines
          | 'format' >> beam.Map(format_result)
          | 'encode' >> beam.Map(lambda x: x.encode('utf-8')).with_output_types(six.binary_type))
output | beam.io.WriteStringsToPubSub(self.output_topic)

That did not work. And I'm running out of ideas. Does anyone know if this can be done?

A: You can use a ParDo that yields elements only when the condition is satisfied. For example, consider the following message structure where the publish field indicates whether the processed message should be outputted by the ParDo or not:
{"publish":"true","body":"This message should be published"}
{"publish":"false","body":"This message should *NOT* be published"}

We will only yield the values when publish is set to true:
class FilterFn(beam.DoFn):
    def process(self, element):
        if (element['publish'] == 'true'):
          yield element['body']

and the main pipeline code:
lines = p | 'Read messages' >> beam.io.ReadStringsFromPubSub(topic=known_args.input)
jsons = lines | 'Load into JSON' >> beam.Map(lambda x: json.loads(x))
filtered = jsons | 'Filter messages' >> beam.ParDo(FilterFn())
filtered | 'Publish messages' >> beam.io.WriteStringsToPubSub(topic=known_args.output)

Pulling the messages from the output subscription will return only one message:

This message should be published


text:
Q: Not working onClick scroll left or right products in React I have a list of products displayed horizontally.

I need to make a working on click Left or Right btns, to scroll next product into view.
This is my scrollProducts function which not working:
  const scrollProducts = isRight => {
    const $document = document.querySelector(".prodcuts")
    if (!$document) {
      return
    }
    productsRef.current.scrollLeft = isRight
      ? productsRef.current.scrollLeft + $document.clientWidth
      : productsRef.current.scrollLeft - $document.clientWidth
  }

JSX part:

          <button onClick={() => scrollProducts(false)}>Left</button>
          <button onClick={() => scrollProducts(true)}>Right</button>

        <Row styles={styles.productCards}>
          {site.siteMetadata.data.map(product => (
            <ProductCard key={product.name} {...product} />
          ))}
        </Row>

Any advice?


text:
Q: In React-Bootstrap 2.5.0 is there a way to put the Navbar.Brand next to the Navbar.Toggle? Currently, I have the following where the Navbar.Toggle is on the left and my Navbar.Brand is on the far right. Since my toggle opens an offcanvas from the left hand side, I wanted the toggle button to be on the left. However, I want my Navbar.Brand to either be centered or left-aligned. I am new to react-bootstrap so apologizes for the dumb question.

Here is the current code:
<Navbar
        key="md"
        collapseOnSelect
        className="sm md"
        expand="md"
        bg="dark"
        variant="dark">
  <Container fluid>
          <Navbar.Toggle aria-controls="offcanvasNavbarLabel-expand-md" />
          <Navbar.Brand href="#home">
            <img
              alt=""
              src={Logo}
              width="30"
              height="30"
              className="d-inline-block align-top"
            />
            My App
          </Navbar.Brand>
  </Container>
</Navbar>

I have tried adding the following className values to Navbar.Brand and on NavBar but have not gotten what I wanted:

*

*justify-content-center-md

*justify-content-center

A: You either want justify-content-start (for left-alignment of the brand), or add an empty third element and use justify-content-between (for center alignment). This would probably go on the container, not the navbar.
https://getbootstrap.com/docs/5.2/utilities/flex/#justify-content


text:
Q: What does `apt-get -b source ` do exactly? It downloads source and patches, then what ? How can someone build the downloaded source just as the apt-get does manually ?

A: apt-get -b alone doesn't do anything, it has to be used in conjunction with two other options.

*

*Run sudo apt-get build-dep <prog_name> to build dependencies for the program first

*Run sudo apt-get -b source <prog_name> to actually download the source code and build it.

In my test just now with nano text editor, after running sudo apt-get build-dep nano and then sudo apt-get -b source nano, apt actually ran make file to compile all *.c source files and then deb-buildpackage to actually build the deb package for installation.


text:
Q: Div in wrong position while loading I have a JavaScript slide-out menu on my page. As the page is loading the menu shows in the wrong place and as opened (it should be closed by default). It then jumps into the correct position and state once the page has loaded.
I would like the menu to either load last or be in the correct position to start with. I have tried making the style for the menu hidden and the display it as a block on page load with JavaScript but the menu just stays hidden.
<link rel="stylesheet" type="text/css" media="all" href="<css/style.css" />
<link rel="stylesheet" type="text/css" media="all" href="</css/reset.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tabSlideOut.v1.3.js"></script>
<script type="text/javascript" src="js/jquery.cycle.all.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('.slide-out-div').tabSlideOut({
        tabHandle: '.handle',
        pathToTabImage: 'images/closed_menu.png', //class of the element that will become your tab
        imageHeight: '230px',                     //height of tab image           //Optionally can be set using css
        imageWidth: '62px',                       //width of tab image            //Optionally can be set using css
        tabLocation: 'left',                      //side of screen where tab lives, top, right, bottom, or left
        speed: 600,                               //speed of animation
        action: 'hover',                          //options: 'click' or 'hover', action to trigger animation
        topPos: '270px',                          //position from the top/ use if tabLocation is left or right
        leftPos: '30px',                          //position from left/ use if tabLocation is bottom or top
        fixedPosition: false                      //options: true makes it stick(fixed position) on scroll
    });

$("div.slide-out-div").mouseover(function(){
$('.handle').css("background-image", "url(images/open_menu.png)");
  }).mouseout(function(){
      $('.handle').css("background-image", "url(images/closed_menu.png)");
  });

$('#sliderimages').cycle({
    fx:     'fade',
    speed:  'fast',
    timeout: 0,
    next:   '#next',
    prev:   '#prev'
});

 });
</script>

<body onload="javascript:document.getElementByClass('slide-out-div').style.display = 'block';">

and then the CSS
.slide-out-div {
display: none;
padding-left: 0px;
width: 200px;
z-index: 3;
position: relative;
}

A: A possible solution might be this. In the <head> of your html add:
<script>document.documentElement.className += ' js'</script>
This will add a "js" class onto the <html> element.
Next, in your css file style your menu as you would normally, but immediately after, hide it by adding the .js class. For example:
.menu { /* your normal styling goes here */ }
.js .menu { display: none; }

This makes sure that your menu is shown in clients that do, for whatever reason, not support JavaScript but hidden in clients that do support JavaScript.
Next up, adapt your JavaScript file to show the slide-out menu when needed.

A: Looked at this with fresh eyes this morning and just realised I was using trying to use a Class in my Javascript and not an ID.
I changed from this
<body onload="javascript:document.getElementByClass('slide-out-div').style.display = 'block';">

to this
<body onload="javascript:document.getElementById('menu').style.display = 'block';">


text:
Q: How to uninstall two applications at a time in Windows System? I need to uninstall 2 Programs/Applications from the Application Wizard (Control Panel).
enter image description here
When I try to uninstall the non related application to the current uninstalling application also, I'm getting this dialogue box:
enter image description here
May I Know that We can uninstall more than one application from the application wizard in the Windows OS?


text:
Q: JavaScript to Python (Using JS2PY) I have a seed-calculating thing that uses JavaScript (Functions properly). I'm attempting to convert it into Python (For a more detailed project) using the JS2PY library.
My code:
import js2py

hasCode = js2py.eval_js('function hashCode(s) {let h = 0; for (let i = 0; i < s.length; i++) {h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;} return h;}')
getSeed = js2py.eval_js('function getSeed(s) {let x = BigInt(hashCode(s)); if (/^[\-\+0-9]*$/.test(s)) {try {let y = BigInt(s); if (BigInt.asIntN(64, y) !== y) {throw RangeError();} x = y;} catch (err) {}} return { high: x >> 32n, low: BigInt.asIntN(32, x) };}')
output = js2py.eval_js('function output() {let seed = -734744700160476640; print("Copy this output - " + seed.high, seed.low);}')

output()

Should you use this in, say, a HTML file, the JavaScript will produce a "High" and "Low" of the seed input (Here it is -734744700160476640, but I would allow users to input their own seed).
The command log explains that there's syntax errors in files that I'm assuming is from the library. You can probably tell I'm a little inexperienced so if it's my own code that's broken, shout it out. I don't know if JS2PY is outdated or if there's better options out there. I couldn't find any myself.


text:
Q: Open workbooks that contain a certain string in their file name There are 13 files in a folder called Folder_1. These 13 files are named like this:

*

*2020-01_Template_XYZ.xlsm

*2020-02_Template_XYZ.xlsm

*2020-03_Template_XYZ.xlsm

*2020-04_Template_XYZ.xlsm

*2020-05_Template_XYZ.xlsm

*2020-06_Template_XYZ.xlsm

*2020-07_Template_XYZ.xlsm

*2020-08_Template_XYZ.xlsm

*2020-09_Template_XYZ.xlsm

*2020-10_Template_XYZ.xlsm

*2020-11_Template_XYZ.xlsm

*2020-12_Template_XYZ.xlsm

*Master_file.xlsm
Master_file.xlsm contains a macro that looks like this:
Option Explicit

Sub OpenWorksheets()

Dim workbook_1 As Workbook
Dim workbook_2 As Workbook
Dim workbook_3 As Workbook
Dim workbook_4 As Workbook
Dim workbook_5 As Workbook
Dim workbook_6 As Workbook
Dim workbook_7 As Workbook
Dim workbook_8 As Workbook
Dim workbook_9 As Workbook
Dim workbook_10 As Workbook
Dim workbook_11 As Workbook
Dim workbook_12 As Workbook
Dim active_workbook As Workbook

Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-01_Template_XYZ.xlsm")
Set workbook_2 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-02_Template_XYZ.xlsm")
Set workbook_3 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-03_Template_XYZ.xlsm")
Set workbook_4 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-04_Template_XYZ.xlsm")
Set workbook_5 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-05_Template_XYZ.xlsm")
Set workbook_6 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-06_Template_XYZ.xlsm")
Set workbook_7 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-07_Template_XYZ.xlsm")
Set workbook_8 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-08_Template_XYZ.xlsm")
Set workbook_9 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-09_Template_XYZ.xlsm")
Set workbook_10 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-10_Template_XYZ.xlsm")
Set workbook_11 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-11_Template_XYZ.xlsm")
Set workbook_12 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2020-12_Template_XYZ.xlsm")
Set active_workbook = Workbooks.Open(Application.ActiveWorkbook.FullName)

End Sub

Folder_2 also contains 13 files. These 13 files are named like this:

*

*2021-01_Template_ABC.xlsm

*2021-02_Template_ABC.xlsm

*2021-03_Template_ABC.xlsm

*2021-04_Template_ABC.xlsm

*2021-05_Template_ABC.xlsm

*2021-06_Template_ABC.xlsm

*2021-07_Template_ABC.xlsm

*2021-08_Template_ABC.xlsm

*2021-09_Template_ABC.xlsm

*2021-10_Template_ABC.xlsm

*2021-11_Template_ABC.xlsm

*2021-12_Template_ABC.xlsm

*Master_file.xlsm
If the macro code in Master_file.xlsm did not change, I would have to adapt the macro accordingly by writing code that looks like this:
Option Explicit

Sub OpenWorksheets()

Dim workbook_1 As Workbook
Dim workbook_2 As Workbook
Dim workbook_3 As Workbook
Dim workbook_4 As Workbook
Dim workbook_5 As Workbook
Dim workbook_6 As Workbook
Dim workbook_7 As Workbook
Dim workbook_8 As Workbook
Dim workbook_9 As Workbook
Dim workbook_10 As Workbook
Dim workbook_11 As Workbook
Dim workbook_12 As Workbook
Dim active_workbook As Workbook

Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-01_Template_ABC.xlsm")
Set workbook_2 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-02_Template_ABC.xlsm")
Set workbook_3 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-03_Template_ABC.xlsm")
Set workbook_4 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-04_Template_ABC.xlsm")
Set workbook_5 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-05_Template_ABC.xlsm")
Set workbook_6 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-06_Template_ABC.xlsm")
Set workbook_7 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-07_Template_ABC.xlsm")
Set workbook_8 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-08_Template_ABC.xlsm")
Set workbook_9 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-09_Template_ABC.xlsm")
Set workbook_10 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-10_Template_ABC.xlsm")
Set workbook_11 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-11_Template_ABC.xlsm")
Set workbook_12 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-12_Template_ABC.xlsm")
Set active_workbook = Workbooks.Open(Application.ActiveWorkbook.FullName)

End Sub

Instead of doing this, I would like the macro code of Master_file.xlsm to be able to look for files in its folder where the file names contain the string -01_Template_, -02_Template_, …, -12_Template_ and assign them to workbook_1, workbook_2, …, workbook_12.
Writing something like Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\*-01_Template_*.xlsm") does not work and I have inspected countless other questions regarding the problems with changing file names.
So, how can I solve the problem that I just described?

A: You could use Dir.
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dir-function
Otherwise consider constructing part of the path into a string variable and appending the part that changes, then passing that variable into your open command.
For example, you could put:
Dim sPathLeader$
sPathLeader = Application.ActiveWorkbook.Path & "\2021-"

Then, where you have the following line:
Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\2021-01_Template_ABC.xlsm")

You could replace it with:
Set workbook_1 = Workbooks.Open(sPathLeader & "01_Template_ABC.xlsm")

Then, if you have lots of years, you could put the whole thing in a For loop, where each iteration starts by rebuilding sPathLader with a different year.
But, that is less optimal, though it may help if in a pinch in a single use case.
It is better to use Dir to determine the filenames in that path dynamically.
Otherwise, you will have a lot of validation checking and error trapping to do, to set up how to react if a file name is not found etc.

A: The below code can be used to get a list of file names in a directory.  You can then open each file up one at at time.
Public Function Test()

    Dim dirPath As String: dirPath = "C:\Temp\"     ' must end in \
    Dim coll As Collection
    Set coll = GetFilesInDirectory(dirPath, "*.*")
    Dim fileName As Variant
    For Each fileName In coll
        Debug.Print dirPath & fileName
    Next fileName

End Function

Public Function GetFilesInDirectory(dirPath As String, Optional criteria As String = "*.*") As Collection

    ' Send in a directory path and criteria for file names (*.*) ; directory must end in \
    ' Returns all files names found that are like criteria ; does not return directories

    Dim coll As New Collection
    Dim fileName As String
    fileName = dir(dirPath & criteria)
    Do While fileName <> ""
        coll.Add fileName
        fileName = dir
    Loop
    Set GetFilesInDirectory = coll

End Function

A: since you have so many individual workbook objects you want to refer to then you could do something like this:
Sub test()
Dim workbook1 As Workbook, workbook2 As Workbook, active_workbook As Workbook

Set active_workbook = ThisWorkbook '? not sure why this wouldn't be okay in your case     since this runs from master book

For i = 1 To 12:
    Select Case i:
    Case i = 1:
        Set workbook1 = Workbooks.Open(ThisWorkbook.Path & "\2020-" & Format(i, "00") & "_Template_ABC.xlsm")
    Case i = 2:
        Set workbook2 = Workbooks.Open(ThisWorkbook.Path & "\2020-" & Format(i, "00") & "_Template_ABC.xlsm")
    'you get the pattern i'm sure
    End Select
Next i
end sub

There may be better ways to organize any dependent code though, like looping through and working with each workbook one at a time, instead of needing all of them handed over at once.

A: Ok, I think I have found the answer. The solution is to write something like this:
Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\" & Dir(Application.ActiveWorkbook.Path & "\" & "*-01_Template_*.xlsm"))

Instead of something like this:
Set workbook_1 = Workbooks.Open(Application.ActiveWorkbook.Path & "\" & Dir(Application.ActiveWorkbook.Path & "\*-01_Template_*.xlsm"))

The first asterisk * seems to require a certain position in order to be interpreted correctly.


text:
Q: How to access to folders not to files in a specific folder in c++? Suppose i have a folder, In this folder exist some files and folders, I want to access to folders not to files. How do i do that. I know to exist this function in c++ :FindFirstFileA and i write following code, but this work for files.
WIN32_FIND_DATAA ffd;
string s = "E:\\OpenCV\\SABT\\Old";

HANDLE hFind = FindFirstFileA(s.c_str(), &ffd);

if (INVALID_HANDLE_VALUE == hFind)
{
    printf("no file found");
    return -1;
}

if (ffd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{

    do
    {
        std::string fn = path + ffd.cFileName;
        printf("file %s\n", fn.c_str());

    } while (FindNextFileA(hFind, &ffd) != 0);
}

A: You are checking ffd.dwFileAttributes the wrong way.  It is a bitmask, and a directory can have multiple attributes at a time, so you need to use the & bitwise AND operator instead of the == equality operator.
Don't forget to also check/ignore the "." and ".." entries when enumerating subfolders. And call FindClose() when you are done enumerating.
Try something more like this instead:
WIN32_FIND_DATAA ffd;
string path = "E:\\OpenCV\\SABT\\Old\\";

HANDLE hFind = FindFirstFileA((path + "*.*").c_str(), &ffd);

if (INVALID_HANDLE_VALUE == hFind)
{
    if (GetLastError() == ERROR_FILE_NOT_FOUND)
       printf("no folders found\n");
    else
       printf("error searching for folders\n");
    return -1;
}

do
{
    if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
        if ((lstrcmpA(ffd.cFileName, ".") != 0) &&
            (lstrcmpA(ffd.cFileName, "..") != 0))
        {
            std::string fn = path + ffd.cFileName;
            printf("%s\n", fn.c_str());
        }
    }
}
while (FindNextFileA(hFind, &ffd));

if (GetLastError() != ERROR_NO_MORE_FILES)
{
    printf("error searching for folders\n");
}

FindClose(hFind);

A: You want this:
WIN32_FIND_DATAA ffd;
string s = "E:\\OpenCV\\SABT\\Old";

HANDLE hFind = FindFirstFileA(s.c_str(), &ffd);

if (INVALID_HANDLE_VALUE == hFind)
{
   printf("no file found");
   return -1;
}

do
{
   if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
   {
     std::string fn = path + ffd.cFileName;
     printf("file %s\n", fn.c_str());
   }
} while (FindNextFileA(hFind, &ffd) != 0);


text:
Q: Relaxation of Helmholtz equation in L-shaped domain: is my ansatz correct? My motivation in this problem is to show that one can approximate the eigenvalues of the Helmholtz equation on an L-shaped domain with Dirichlet boundary conditions (famously has no closed-form solutions) by solving a system of equations that govern the solution of a Schrodinger equation with sufficiently large potential. Are there any issues with my problem here? I am mostly concerned if my ansatz in equation (2) makes sense. In 1D for a finite potential well problem, one can use the fact that the solutions must be $C^1$... but is this the case for the 2D finite potential well problems? I suppose my solution here works if we have for a bounded smooth domain $\Omega \subset \mathbb R^2$ and piecewise constant $V$, are the Schrodinger equation solutions in $C^1(\Omega)$. Is that true?
Problem:
*Consider the regions $S = (0,2)^2$ and the L-shaped region $L = S \setminus (1,2)^2$. Solve the time-independent Schrodinger equation with Dirichlet boundary conditions for the Schrodinger operator $\hat H_{V_0} = -\Delta + V(x,y;V_0)$ with $V(x,y;V_0) = V_0 \chi_{S\setminus L} (x,y) $ where $\chi_{S\setminus L} (x,y)$ is the indicator function on ${S\setminus L}$ and we consider large $V_0 \gg 1$:
\begin{equation}(1)\qquad \hat H_{V_0} u_{k,\ell} = \lambda_{k,\ell}(V_0) u_{k,\ell},\quad  \left.u\right\vert_{(x,y) \in \partial S} = 0\end{equation}
My Attempt:
We label the following quadrants of $S$:
\begin{equation}
\begin{aligned}
    {\operatorname{I}} &= [0,1)\times[0,1), \qquad {\operatorname{II}} &= [0,1) \times [1,2) \\
    {\operatorname{III}} &= [1,2) \times [0,1), \qquad {\operatorname{IV}} &= [1,2)\times [1,2)
    \end{aligned}
\end{equation}
Any solution on a quadrant solves (1), and we have from the boundary conditions on each quadrant that solutions are of the form:
\begin{equation}
\begin{aligned}(2)\qquad
u_{k,\ell}(x,y) &= \begin{cases} A_{k,\ell} \sin( \xi^{\operatorname{I}}_k x) \sin(\eta^{\operatorname{I}}_\ell y), & (x,y) \in {\operatorname{I}} \\
 B_{k,\ell} \sin( \xi^{\operatorname{II}}_k x) \sin(\eta^{\operatorname{II}}_\ell (2-y)), & (x,y) \in {\operatorname{II}} \\
  C_{k,\ell} \sin( \xi^{\operatorname{III}}_k (2-x)) \sin(\eta^{\operatorname{III}}_\ell y), & (x,y) \in {\operatorname{III}} \\
    \sinh( \xi^{{\operatorname{IV}}}_k (2-x)) \sinh(\eta^{{\operatorname{IV}}}_\ell(2- y)), & (x,y) \in {\operatorname{IV}} \end{cases}\\
   \lambda_{k,\ell} &= (\xi^{i}_k)^2 + (\eta^i_\ell)^2 = -(\xi^{{\operatorname{IV}}}_k)^2 - (\eta^{{\operatorname{IV}}}_\ell)^2 + V_0,\ \text{for } i \in \{\operatorname{I},\operatorname{II},\operatorname{III}\}.
   \end{aligned}
\end{equation}
After requiring the solution to be in $C^1(S)$ and piecing together along the lines $x=1$ and $y=1$, we then have the following system of 11 equations for 11 unknowns (for fixed $k$ and $\ell$):
\begin{align}
A\xi^{\operatorname{I}} \sin( \xi^{\operatorname{I}})\sin(\eta^{\operatorname{I}} y) &= C\sin(\xi^{\operatorname{III}}) \sin(\eta^{\operatorname{III}} y) \label{eq:s1}\\
A \xi^{\operatorname{I}} \cos(\xi^{\operatorname{I}})\sin(\eta^{\operatorname{I}} y) &= - C \xi ^{\operatorname{III}} \cos( \xi^{\operatorname{III}} )\sin(\eta^{\operatorname{III}} y) \label{eq:s2} \\
B \sin( \xi^{\operatorname{II}} ) \sin( \eta^{\operatorname{II}}(2-y)) &=   \sinh( \xi^{{\operatorname{IV}}} ) \sinh(\eta^{{\operatorname{IV}}}(2-y)) \label{eq:s3}\\
B \xi^{\operatorname{II}} \cos(\xi^{\operatorname{II}})\sin(\eta^{\operatorname{II}} (2 -y))&= -  \xi^{{\operatorname{IV}}} \cosh (\xi^{{\operatorname{IV}}}) \sinh( \eta^{{\operatorname{IV}}} (2 - y))\label{eq:s4} \\
A \sin(\eta^ I)\sin(\xi^{\operatorname{I}} x) & = B\sin(\eta^{\operatorname{II}})\sin(\xi^{\operatorname{II}} x) \label{eq:s5} \\
A \eta^{\operatorname{I}} \cos(\eta^{\operatorname{I}})\sin(\xi^{\operatorname{I}} x)  &= -B\eta^{\operatorname{II}}\cos(\eta^{\operatorname{II}})\sin(\xi^{\operatorname{II}} x) \label{eq:s6} \\
C \sin(\xi^{\operatorname{III}}(2-x))\sin(\eta^{\operatorname{I}}) &=   \sinh (\xi^{{\operatorname{IV}}}(2-x)) \sinh( \eta^{{\operatorname{IV}}} ) \label{eq:s7}\\
C \eta^{\operatorname{I}} \sin( \xi^{\operatorname{III}}(2-x)) \cos(\eta^{\operatorname{I}}) &= -  \eta^{{\operatorname{IV}}}\sinh(\xi^{{\operatorname{IV}}}(2-x))\cosh(\eta^{{\operatorname{IV}}}) \label{eq:s8} \\
(\xi^{\operatorname{I}})^2 + (\eta^{\operatorname{I}})^2 &= -(\xi^{{\operatorname{IV}}})^2 - (\eta^{{\operatorname{IV}}})^2 + V_0 \label{eq:s9} \\
(\xi^{\operatorname{II}})^2 + (\eta^{\operatorname{II}})^2 &= -(\xi^{{\operatorname{IV}}})^2 - (\eta^{{\operatorname{IV}}})^2 + V_0 \label{eq:s10}\\
(\xi^{\operatorname{III}})^2 + (\eta^{\operatorname{III}})^2 &= -(\xi^{{\operatorname{IV}}})^2 - (\eta^{{\operatorname{IV}}})^2 + V_0. \label{eq:s11}
\end{align}
Since these functions are all analytic, this system has a solution.


text:
Q: getting a "NSOrderedSetArrayProxy was mutated while being enumerated" error without mutation I have two functions:
one that returns an array that is filled in a block
- (NSArray *)getArray {
    NSArray *someValues = @[@0, @42, @23, @5, @8, @2013];
    NSArray *filter = @[@42, @23, @5];

    //replacing this NSMutableOrderedSet with a NSMutableArray
    //and return just matched then, resolves the problem.
    //so the exception has to do something with that set.
    NSMutableOrderedSet *matched = [[NSMutableOrderedSet alloc] init];

    for (id value in someValues) {
        [filter enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj isEqual:value])
                [matched addObject:value];
        }];
    }
    return [matched array];
}

and another one that enumerates the returned array from the first method
- (void)enumArray:(NSArray *)array {
    NSEnumerator *enumerator = [array objectEnumerator];
    for (id obj in enumerator) {
        if ([obj isEqual:@42])
            [enumerator nextObject]; // <== this line causes the error!
    }
}

If i now do something like that
NSArray *array = [foo getArray];
[foo enumArray:array];

i will get a NSGenericException with following message:

Collection <__NSOrderedSetArrayProxy: 0x123456> was mutated while
  being enumerated

where the hell is something mutated. i don't get it. returning a copy from that array solves the problem, but i still don't get it.
The error has do something with the NSMutableOrderedSet, if i replace the set with an array i don't get an exception.
some screenshots, of exception thrown

A: You are using fast enumeration while altering an enumerator instance.
Basically it is a big no-no to modify an object that you fast enumerate over (that form of the for loop you are using uses fast enumeration).  However, you use [enumerator nextObject]; to access the next object from the enumerator, but this modifies the enumerator by removing the current object from it. So it is your use of nextObject within a for...in loop that is mutating the enumerator.
Get past this problem quickly by using a while loop instead of the for loop, a bit like this:
- (void)enumArray:(NSArray *)array {
    NSEnumerator *enumerator = [array objectEnumerator];
    while ((id obj = [enumerator nextObject])) {
        if ([obj isEqual:@42])
            [enumerator nextObject];
    }
}

This should get past the fast enumeration/mutation problem. Note, I have absolutely no idea why you want to move the enumerator on a step when obj is equal to 42, but am presuming within the context of the entire code-base that this makes sense!

A: The basic reason is, you can't edit/modify a mutable array while you're going through it.
So here are the two solutions,
1.Please use @synchronized() directive to lock the array while you mutate it.
- (void)enumArray:(NSArray *)array {

    NSEnumerator *enumerator = [array objectEnumerator];
    for (id obj in enumerator)
    {
        if ([obj isEqual:@42])
        {
            @synchronized(enumerator)
            {
              [enumerator nextObject]; // <== this line causes the error!
            }
        }
    }
}

2.Just do a copy of you NSArray and use it
- (void)enumArray:(NSArray *)array {

    NSEnumerator *enumerator = [[array copy] objectEnumerator];

    for (id obj in enumerator)
    {
        if ([obj isEqual:@42])
        {
          [enumerator nextObject]; // <== this line causes the error!
        }
    }
}