text:
Q: Http error 405 when trying to scrape data with Python 3.3 I want to scrape data from a website; however I keep getting the HTTP: Error 405: Not Allowed. What am I doing wrong?
(I have looked at the documentation, and tried their code, with only my url in place of the example's; I still have the same error.)
Here's the code:
import requests, urllib
from urllib.request import Request, urlopen

list_url= ["http://www.glassdoor.com/Reviews/WhiteWave-Reviews-E9768.htm"]

for url in list_url:
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    response=urllib.request.urlopen(req).read()

If I skip the user-agent term, I get HTTP Error 403: Forbidden.
In the past, I have successfully scraped data (from another website) using the following:
for url in list_url:
    raw_html = urllib.request.urlopen(url).read()
    soup=None
    soup = BeautifulSoup(raw_html,"lxml")

Ideally, I would like to keep a similar structure, that is, pass the content of the fetched url to BeautifulSoup.
Thanks!

A: The error you are getting is "Pardon our Interruption. something about your browser made us think you were a bot". Implies scraping ain't permitted and they have anti-scraping bots on their webpages.
Try using a fake-browser. Link to how to make requests using a fake-browser. (How to use Python requests to fake a browser visit? )
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
url = 'http://www.glassdoor.com/Reviews/WhiteWave-Reviews-E9768.htm'
web_page = requests.get(url,headers=headers)

I tried this and what I found is their page is getting loaded via JS. So I think you might want to use a headless Browser ( Selenium / PhantomJS ) and scrape rendered html pages. Hope it helps.

A: Not sure about exactly reason of the issue, but try this code it is working for me:
import http.client

connection = http.client.HTTPSConnection("www.glassdoor.com")
connection.request("GET", "/Reviews/WhiteWave-Reviews-E9768.htm")

res = connection.getresponse()
data = res.read()


text:
Q: Node.js connect ECONNREFUSED 127.0.0.1:8000 DynamoDB Local Error I'm using this NPM plugin to handle creating a local DynamoDB local server within my Node app. For some reason sometimes it gives me the following error. Can't figure out why but it seems to always happen when running tests during a specific section of tests.
It definitely doesn't happen every time. Maybe 50% or so. Very strange.
I have read that the error means starting the DynamoDB local server failed. But I have no idea why since it doesn't give any more details.
DynamoDB Local failed to start with code 1
{ Error: connect ECONNREFUSED 127.0.0.1:8000
    at Object.exports._errnoException (util.js:1012:11)
    at exports._exceptionWithHostPort (util.js:1035:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
  message: 'connect ECONNREFUSED 127.0.0.1:8000',
  code: 'NetworkingError',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8000,
  region: 'us-west-2',
  hostname: 'localhost',
  retryable: true,
  time: 2016-09-13T03:26:05.804Z }

Oh and here is my code to create the server.
    dynamodbLocal.start({port : dbport, /* Port to listen on. Default: 8000 */
         cors : '*', /* Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for cors is an asterisk (*), which allows public access. */
         inMemory : false, /* DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both dbPath and inMemory at once. */
         dbPath : __dirname + '/dynamodb/', /* The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both dbPath and inMemory at once. For the path, current working directory is <projectroot>/node_modules/dynamodb-localhost/dynamob. For example to create <projectroot>/node_modules/dynamodb-localhost/dynamob/<mypath> you should specify '<mypath>/' with a forwardslash at the end. */
         sharedDb : false, /* DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration. */
         delayTransientStatuses : false, /* Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.) */
         optimizeDbBeforeStartup : true /* Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter. */
        });

Any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to determine traffic flow from server How can I  determine the path traffic takes from a server with 2 Ethernet ports, each port connecting to a separate switch.
The switches are not cable of layer3 so I cannot use HSPR where I could make the one switch the default gateway.
Is there a layer two solution I can Implement?

A: Each server decides based on it's own routing table which interface to use when connecting out. Unless you use some special features like bonding, you should get useful output by entering sudo ip route show.
For example in my case the output looks like this:
root@mr-burns:~ ssh# ip route show
default via 10.60.0.1 dev em1
10.20.0.0/16 via 10.60.0.165 dev em2
10.60.0.0/16 dev em1  proto kernel  scope link  src 10.60.1.150
10.60.0.0/16 dev em2  proto kernel  scope link  src 10.60.1.151
127.0.0.0/8 dev lo  scope link

I read this like following:
Let's say the destination is inside the network 10.20.0.0/16, it will use the interface em2 because of the second rule.
But if the destination is using the default gw because its not in any of the listed destination networks, it uses em1.


text:
Q: Application of Bayes' theorem - probability problem Suppose that the reliability of a HIV test is specified as follows : Of people having HIV, ... Bayes' Theorem States : *If $E_1,E_2,....E_n$ are n non empty evnents which constitute a partition of sample space S, ie.e. $E_1,E_2,....E_n$ are pairwise disjoint and $E_1 \cup E_2 ......\cup E_n$ = S and A is any event of non zero probability , then $ P(E_i |A) = \frac{P(E_i)P(A|E_i)}{\sum^n_{j=1} P(E_j) P(A | E_j)}$ for any i = 1,2,3,.......n.*
Problem :
Suppose that the reliability of a HIV test is specified as follows : Of people having HIV, 90% of the test detect the disease but 10% go undetected. Of people free of HIV, 99% of the test judged HIV -ve but 1% are diagnosed as showing HIV +ve . From a large population of which only 0.1% have HIV, one person is selected at random , given the HIV test, and the pathologist reports him / her as HIV +ve. What is the probability that the person actually has HIV ?
Request you to please help how to proceed in such problem by using Bayes' theorem.. Thanks in advance

A: Let $A$ be the event "tested positive." Let $E_1$ be the event "has HIV" and $E_2$ the event "doesn't have HIV."
We want $\Pr(E_1|A)$.
On the top of the right-hand side of the formula you quoted, we have $\Pr(E_1)\Pr(A|E_1)$.
We are told that $\Pr(E_1)=0.001$. We are also told $\Pr(A|E_1)= 0.90$. So now we know the top.
For the bottom, we know $\Pr(E_1)\Pr(A|E_1)$, since we just have calculated it. We want $\Pr(E_2)\Pr(A|E_2)$. By the information we were given, the product is $(0.999)(0.01)$.
Now you have all the ingredients.


text:
Q: Why is this pointer valid when its object should be out of scope? (And some other weird behaviors) I'm still new to c++ and have been studying object scope.
I've tested the code below and witnessed some weird behaviors.
struct Test
{
    int value, value2;
    Test() : value(1), value2(10) {};
};

Test* GetTestPointer() {
    Test t;
    t.value = 20;
    return &t;
}

int main() {
    Test* tp = GetTestPointer();
    int a = tp->value;
    int b = tp->value2;
    cout << a << endl;
    cout << b << endl;

    return 0;
}

Output:
20
10

I thought Test t would go out of scope so dereferencing its values in main would either throw an exception or an empty value. Why is it getting valid values as if the object is still alive?
Actually this is what I originally tried:
Test* tp = GetTestPointer();
cout << tp->value << endl;
cout << tp->value2 << endl;

Output:
20
18223279

Here value2 is acting like it's invalid but I can get value just fine.
Conversely I tried reordering them:
Test* tp = GetTestPointer();
cout << tp->value2 << endl;
cout << tp->value << endl;

Output:
10
1459403656

Note that none of this happened when I properly initiated tp with new, as expected.
I know I would never write code like this in real life but I got really curious as to why any of this is happening.

*

*When does t go out of scope in this case?

*What does the ordering of cout have anything to do with what tp is dereferencing?

*Why when I save them in buffers can I get the correct values?

A: You just got lucky to be correct value, but in general it is undefined behavior and your compiler should warn you about this.
Try to extend your example to something like this:
int my_sum(int a, int b) {return a + b;}
int main() {
    int res;
    Test* tp = GetTestPointer();
    res = my_sum(1, 2);
    int a = tp->value;
    int b = tp->value2;
    cout << a << endl;
    cout << b << endl;

    return 0;
}

You will see different output because your local scoped Test object was overwritten by another function call.
WHen you use new statement, then your object is not created locally, but on the HEAP memory and therefore it is valid when you go out of function scope. In this case, you have to use delete, to delete this object later.


text:
Q: NoSQL databases alternatives/patterns/equivalences to Relational DB From what I saw in this video...
http://www.youtube.com/watch?v=LhnGarRsKnA
pretty much all the traditional RDBM operations (JOINS, GROUP BY, HAVING, etc) can be done in NoSQL databases through a combination of MapReduce/denormalization techniques.
Is there any article/document that has all these equivalences clearly described. Something like... the equivalence of a JOIN in a NoSQL database would be... bla bla
I just can't find this kind of documentation anywhere :(

A: There's a reason you can't find that type of documentation. For a start, unlike SQL, there is no such thing as a standard NoSQL database. Have you tried searching for specific NoSQL data stores?
Also, trying to convert relational operations to non relational systems will just get you into trouble. Instead you need to look at what you are trying to do with those relational operations. For example is group by for sorting a list with categories or for handling heirarchical objects when you don't have multiple value fields? Is join assembling a single object stored in multiple tables or calculating a set intersection?
One of the biggest strengths of SQL is that any data can be represented in a standard way and any query can be run on that data. It won't necessarily be the best fit for that data, but it is standard and there is a single correct answer for almost any question. NoSQL is mostly about being able to optimize your data store for what you actually need by sacrificing the generality of SQL. That may be performance, handling a large dataset, handling inconsistent data, or just simpler code. In short you need to understand your requirements and the tradeoffs involved in optimizing for them rather than just choosing SQL by default.
Your best option is to pick a datastore that fits what you need (a good comparison of high level features is at
http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis ) and look for some examples of how systems are designed using that data store. With luck you will find something close to what you are working on.

A: This article has a some good info on NoSQL vs using SQL
http://www.develop.com/mongoDB

A: Be very careful... you probably don't want to join a 1 trillion row table with something.  Think about patterns of partitioning your data.  For example with playOrm you can partition your data and do S-SQL(Scalable SQL) so you can do all the joins you want to within a partition which in many OLTP apps is exactly what you need as if your customers are businesses, each business is in it's own partition and you can join all you want all the tables related to that one business.

A: Here is a list of patterns to help you gain ground in the noSql world....(it's a work in progress).
https://github.com/deanhiller/playorm/wiki/Patterns-Page


text:
Q: Reading lines from text file and appear on screen i am kinda new to programming and here is my question. I need to do a text editor(something like microsoft notepad but more simple). Im trying to do it step by step like first i need to open file, then read it and etc. But this code clears my programme and i cant properly understand how do i read it line by line(probably using for or while). Thanks
  #include <iostream>
#include <fstream>

using namespace std;

/*
void openFile()
{
    ofstream file2("text2.txt"); // create and open text file
    file2 << "Hello there"; // write in file
    file2.close(); // close file
}
*/

void readFile(char text[4050])
{

    ifstream file("text2.txt"); // read from file
    if (!file.is_open()) // if file is not opened then write "file is not found". else
        cout << "File is not found!" << endl;
    else
    {
        file.getline(text, 4050); // to where(text), max symbols(4050)
        cout << text << endl;
        file.close();
    }
}

using namespace std;

int main()
{

    char text[4050];

    ofstream file2("text2.txt");
    readFile(text);
    return 0;
}

My code is probably wrong and weird but i'll try my best to fix it once i figure it out how.

A: Here is the simplest way to read a file line by line.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("MyFile.txt");
  if (myfile.is_open()) {
    while ( getline (myfile,line) ) {
      cout << line << '\n';
    }
    myfile.close();
  }
  else {
    cout << "Unable to open file";
  }
  return 0;
}


text:
Q: How to Sign an Already Compiled Apk I've decoded an APK with apktool (as the original source code was lost) so I could fix some issues with the layout xml files. I've then rebuilt it back up with apktool and when I tried to install it on my device (using adb: adb install appname.apk) it gave me this error:
[INSTALL_PARSE_FAILED_NO_CERTIFICATES]

the original apk however was signed by a keystore (on eclipse IDE), this one isn't, how can I sign it properly with it's original keystone file outside Eclipse!?

A: You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

A: For those of you who don't want to create a bat file to edit for every project, or dont want to remember all the commands associated with the keytools and jarsigner programs and just want to get it done in one process use this program:
http://lukealderton.com/projects/programs/android-apk-signer-aligner.aspx
I built it because I was fed up with the lengthy process of having to type all the file locations every time.
This program can save your configuration so the next time you start it, you just need to hit Generate an it will handle it for you. That's it.
No install required, it's completely portable and saves its configurations in a CSV in the same folder.

A: create a key using
keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

A: Updated answer
Check https://shatter-box.com/knowledgebase/android-apk-signing-tool-apk-signer/
Old answer
check apk-signer a nice way to sign your app

A: fastest way is by signing with the debug keystore:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android

or on Windows:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android

A: Automated Process:
Use this tool (uses the new apksigner from Google):
https://github.com/patrickfav/uber-apk-signer
Disclaimer: Im the developer :)
Manual Process:
Step 1: Generate Keystore (only once)
You need to generate a keystore once and use it to sign your unsigned apk.
Use the keytool provided by the JDK found in %JAVA_HOME%/bin/
keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign
zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.
zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).
You can verify the alignment with
zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify
Using build-tools 24.0.2 and older
Use jarsigner which, like the keytool, comes with the JDK distribution found in  %JAVA_HOME%/bin/ and use it like so:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with
jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer
Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called apksigner (duh!)
The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this
apksigner sign --ks-key-alias alias_name --ks my.keystore my-app.apk

and can be verified with
apksigner verify my-app.apk

The official documentation can be found here.


text:
Q: Generate l3keys meta key from subkey I've created a simple package with options settable via l3keys2e. I was able to figure out how to make the syntax
\usepackage[format = international]{phone}

work, but I'd like to make the syntax
\usepackage[international]{phone}

be a synonym. The method I'm using in the code below works, but is very repetitive, especially when I've got more formatting options. Is there a simpler way?
Here's the code:
\RequirePackage{expl3, l3keys2e, xparse}
\ProvidesExplPackage
    {phone}{2013/06/19}{0.1}{Format phone numbers}

\cs_new_nopar:Npn \phone_international_fmt:NNN  #1#2#3
  { +1 - #1 - #2 - #3 }

\cs_new_nopar:Npn \phone_parendash_fmt:NNN  #1#2#3
  { (#1) \nobreakspace #2 - #3 }

\keys_define:nn { phone }
  {
    format .choice_code:n =
      {
        \cs_new_eq:Nc \phone_fmt:NNN
          { phone_ \tl_use:N \l_keys_choice_tl _fmt:NNN }
      },
    format .generate_choices:n =
      {
        international,
        parendash,
      },
% These next lines will become repetitive if I have many more formatting options
    international .meta:n = { format = international },
    parendash     .meta:n = { format = parendash     },
  }

\ProcessKeysOptions { phone }

\NewDocumentCommand \phone
  { >{ \SplitArgument {2} {-} } m }
  { \phone_fmt:NNN #1 }

\endinput

A minimal example using this package looks like this:
\documentclass{article}

% \usepackage[parendash]{phone}
\usepackage[format = parendash]{phone}

\begin{document}

\phone{212-555-1212}

\end{document}

This yields the desired result

(212) 555-1212

A: The approach you've taken looks correct. Internally, the .meta:n property is creating a standard key which is more-or-less equivalent to
key-name-1 .code:n = { \keys_set:nn { module } { key-name-2 = #1 } }

If you have a large number of these meta keys to create, you might want to use a comma-list mapping
\clist_map_inline:nn { key-one , key-two , key-three ... }
  { \keys_define:nn { mymodule } { #1 .meta:n = { format = #1 } }

but for just a couple this is probably making your code more not less complex.

A: You could use an unknown key handler for this whereby you pass any unknown key back into the system as format = <unknown key> (a similar system is used by TikZ to recognise colours and node shapes).  Here's an example which uses that.  It gives a warning if there isn't a corresponding format.
I have to use a helper command to feed the unknown key back into the key handler since if I just did format / unknown .code:n = { \keys_set:nn { phone} { format = #1 } } then the #1 would be \l_keys_key_tl and L3 would be extremely careful and not expand the \l_keys_key_tl until the last minute, by which time it would have changed its value from the unknown key to format.  The helper macro allows me to use the value of \l_keys_key_tl instead of the token list variable.
I also fixed the NNN to nnn.  Because I wanted to set a default, the setter inside the key handler is now \cs_set_eq:Nc instead of \cs_new_eq:Nc.
\documentclass{article}
%\url{http://tex.stackexchange.com/q/120102/86}
\usepackage{filecontents}

\begin{filecontents}{phone.sty}
\RequirePackage{expl3, l3keys2e, xparse}
\ProvidesExplPackage
    {phone}{2013/06/19}{0.1}{Format phone numbers}

\cs_new_nopar:Npn \phone_international_fmt:nnn  #1#2#3
  { +1 - #1 - #2 - #3 }

\cs_new_nopar:Npn \phone_parendash_fmt:nnn  #1#2#3
  { (#1) \nobreakspace #2 - #3 }

% Set a default
\cs_set_eq:NN \phone_fmt:nnn \phone_parendash_fmt:nnn

\msg_new:nnnn {phone} {no~ format} {Format~ `#1'~ is~ not~ recognised~ by~ this~ package,~ using~ the~ default~ `parendash'~ instead.} {}

\keys_define:nn { phone }
  {
    format .choice:,
    format .choice_code:n =
      {
        \cs_set_eq:Nc \phone_fmt:nnn
        { phone_ \tl_use:N \l_keys_choice_tl _fmt:nnn }
      },
    format .generate_choices:n =
      {
        international,
        parendash,
      },
      format / unknown .code:n = {
        \msg_warning:nnn {phone} {no~ format} {#1}
      },
    unknown .code:n = {
      \phone_unknown_key:V \l_keys_key_tl
    },
  }

\cs_new:Npn \phone_unknown_key:n #1
{
  \keys_set:nn { phone} { format = #1 }
}

\cs_generate_variant:Nn \phone_unknown_key:n {V}

\ProcessKeysOptions { phone }

\NewDocumentCommand \phone
  { >{ \SplitArgument {2} {-} } m }
  { \phone_fmt:nnn #1 }

\endinput
\end{filecontents}
 \usepackage[british]{phone}

\begin{document}

\phone{212-555-1212}

\end{document}


text:
Q: Angular 6 - reset form after submit don't work I have some big form which contains multiple child components (values are send to them as @input). After clicking submit button all fields should be cleared (and no validation errors should be displayed). I tried to reset form in couple different ways, but nothing works.
I wrote createForm.reset() or createForm.resetForm() inside .html
 file
<form #createForm="ngForm" (ngSubmit)="addExpense(createForm.value); createForm.resetForm()">

Second way to do it
.ts
@ViewChild('createForm') formValues;

  addExpense(form): void {
    this.expenseService.addExpense(this.expense).subscribe(() => {
      this.formValues.resetForm();
      console.log('Form reset done!');
    );
  }

.html:
<form #createForm="ngForm" (ngSubmit)="addExpense(createForm.value)">

This also don't reset the form, no errors are displayed. When I looked into console I saw 'Form reset done!'.

A: Use ChangeDetectorRef to detect the changes
constructor(private cd:ChangeDetectorRef){
}

@ViewChild('createForm') formValues;

  addExpense(form): void {
    this.expenseService.addExpense(this.expense).subscribe(() => {
      this.formValues.resetForm();
      this.cd.markForCheck()
      console.log('Form reset done!');
    );
  }


text:
Q: Ошибки "Undefined variable" и "Uninitialized string offset" Есть код с ошибками, нужно его поправить. Кода всего на 1 страницу. Здесь его показать не могу, т.к. его покупал и поэтому тем самым нарушу авторские права.

PHP Notice:  Undefined variable: nxt in

и

PHP Notice:  Uninitialized string offset: 0 in

Также, возможно, Вы найдете и другие ошибки.
A: Полагаю достаточно вставить в начале скрипта
 $nxt = '';

Тем самым явно указать, что переменная существует, до её использования.
A: Нотис не еррор, ошибка не предупреждение. А вообще, советую обратиться к автору, ибо нефиг продавать код такого качества.


text:
Q: jQuery Countdown until server's midnight time I use Keith Wood jQuery Countdown (http://keith-wood.name/countdown.html) and call it like this:
var midnight = new Date(2020, 4-1, 29, 23, 59, 59);
$('#defaultCountdown').countdown(
{
until: midnight,
format: 'HMS',
padZeroes: true,
compact: true
});

There is no problem taking the midnight time on the client side, but how to get the midnight from the server? I tried it like this but no success:
var midnight = '<?= date("Y, n, j, G, i, s", strtotime('tomorrow')); ?>'

I'll be grateful for any ideas!

A: I solved it like this:
$('#defaultCountdown').countdown(
{
until: +<?= strtotime('tomorrow') - time() ?>,
format: 'HMS',
padZeroes: true,
compact: true
});


text:
Q: How do I retrieve a reference to a subobject using Reflection in C#? I'm trying to use duck typing using reflection in C#. I have an object of some random type and I want to find if it implements an interface with a specific name and if it does - retrieve a reference to that interface subobject so that I can later read (get) a property value via that interface.
Effectively I need as using Reflection.
The first part is easy
var interfaceOfInterest =
   randomObject.GetType().GetInterface("Full.Interface.Name.Here");

which will either retrieve the interface description or null. Let's assume it's not null.
So now I have an object reference to an object that surely implements that interface.
How do I have the "cast" like retrieval of the subobject using Reflection only?

A: You don't need to, simply access the properties of the interface, through the interface type, but whenever you need to pass an instance, simply pass the original object instance.
Here is a LINQPad program that demonstrates:
void Main()
{
    var c = new C();
    // TODO: Check if C implements I
    var i = typeof(I);
    var valueProperty = i.GetProperty("Value");
    var value = valueProperty.GetValue(c);
    Debug.WriteLine(value);
}

public interface I
{
    string Value { get; }
}

public class C : I
{
    string I.Value { get { return "Test"; } }
}

Output:
Test

If you want to access it much more using names:
void Main()
{
    var c = new C();
    // TODO: Check if C implements I
    var i = c.GetType().GetInterface("I");
    if (i != null)
    {
        var valueProperty = i.GetProperty("Value");
        var value = valueProperty.GetValue(c);
        Debug.WriteLine(value);
    }
}

public interface I
{
    string Value { get; }
}

public class C : I
{
    string I.Value { get { return "Test"; } }
}


text:
Q: HTMLParser python turn data into string? Hi I'm using this following python parser to read an html file
https://docs.python.org/2/library/htmlparser.html
class MyHTMLParser(HTMLParser):
def __init__(self):
    HTMLParser.__init__(self)
    self.inLink = False
    self.dataArray = []
    self.countLanguages = 0
    self.lasttag = None
    self.lastname = None
    self.lastvalue = None

def handle_starttag(self, tag, attrs):
    self.inLink = False
    if tag == 'window':
        for name, value in attrs:
            if name == 'mode':
                #value = 0
                #print(value)
                self.countLanguages += 1
                self.inLink = True
                self.lasttag = tag

def handle_endtag(self, tag):
    if tag == "window":
        self.inlink = False

def handle_data(self, data):
    self.data = data
    #print(self.data)
    print data
    if data.strip():
        self.inlink = False
        #print data

  parser = MyHTMLParser()
  input_file = open('xmlfile.xml')
  feed_data = input_file.read().strip()
  feed_data = parser.feed(feed_data)
  print(feed_data.data)
  input_file.close()

However, I cant seem to find a way to turn the data returned from html parser into a string.
I'm basically modyfing an attribute using html parser, then I want to turn the data into a string - any idea how to do that?
I've tried adding a "self.data" to the "handle_data" function, but I cant seem to print any data coming back. Is there a way to just print everything held in the parser?

A: This is another way that might suit your needs for this specific question:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import urllib.request
url = "http://www.google.com"

with urllib.request.urlopen(url) as response:
    html = response.read().decode('utf-8')

print (html)

A: After reading the source code, I found that the feed() function doesn't return anything.

def feed(self, data):
    r"""Feed data to the parser.

    Call this as often as you want, with as little or as much text
    as you want (may include '\n').
    """
    self.rawdata = self.rawdata + data
    self.goahead(0)

So we can rewrite it as:
# -*- coding=utf-8 -*-
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.Myrawdata = ""

    def feed(self, data):
        self.rawdata = self.rawdata + data
        self.Myrawdata = self.Myrawdata + data
        self.goahead(0)

    # your code...

parser = MyHTMLParser()
parser.feed('

')
print "Rawdata:", parser.Myrawdata

The reason why not use self.rawdata is that it will be empty when feed() end.


text:
Q: Need explanation about KeyId/CertId/CertPathId/PassPhraseId In onvif i come across the term KeyId/CertId/CertPathId and PassPhraseId what are these? How these are all created ?

A: They are data types defined for the ONVIF Security Service.
As you can see in advancedsecurity.wsdl, they are all defined as xs:NCName with length 64.
Non Colonized Names are strings that stat with a letter or _ and that cannot have colons.
In ONVIF these values are just used to reference keys, certificates and so on, you can think about them as regular tokens.


text:
Q: Devise Custom Strategies: Still Setting Session Cookies I am using Devise to authenticate users to my Ruby on Rails application. Up to this point, I have been using the standard Cookie-based session to authenticate users, but now I have requirements to allow a token-based authentication, and I implemented this through a custom Warden strategy.
For the sake of this example, my custom strategy code is:
module Devise
  module Strategies
    class CustomAuthenticatable < Base
      def valid?
        params.has_key? :email
      end

      def authenticate!
        success!(User.find_by(email: params[:email]))
        #fail
      end
    end
  end
end

So this works as expected for the first request: when I GET /api/my_controller/url?email=user@example.com the user is authenticated, and I get the expected response.
But wait: when I then make a second request: GET /api/my_controller/url, the user is still authenticated.
Upon further inspection, I see that a Set-Cookie is being sent, with a Devise session.
So here's my question:
How do I disable the Set-Cookie when using a custom strategy?

A: You can prevent the creation of a session, like described in here.
Prevent session creation on rails 3.2.2 for RESTful api
resource = warden.authenticate!(:scope => resource_name, :store => !(request.format.xml? || request.format.json?))

For some other options, please consider Rails 3 disabling session cookies.


text:
Q: Display react component name in attribute While working with React, i would like to display component name in an attribute of the component. E.g. if I have a component <LoginBox /> I would like it to be rendered as

...

But I want this to be done automatically for each transpiled component. Reason for this is automated testing when I'd check for rendered elements in HTML/DOM, currently a component is not differentiated by the name in rendered HTML.
I thought I'd write a babel plugin, but I have no idea what visitors I'd use and how to make it robust enough. I tried google for such a plugin but I have no idea how it would be called and found nothing useful.
So is there any plugin or any way to achieve this?
Thanks

A: Now after a year, as I'm rethinking, it should be quite easy.
For more details on writing plugins see handbook.
Use ASTexplorer to inspect what AST would your code result in. And then, for generated tree, prepare visitors. So e.g. with code:

<Custom some-prop="prop">Some text</Custom>

we would infer, that we need to use visitor JSXOpeningElement and alter node's property attribute. To this property - array we would add a new element that we would create by Babel.types.jsxAttribute(name, value). We will get the name of tag from node's property .name.name (the name string is nested inside name object). We also need to use appropriate types. So it would look like this:
module.exports =  function(Babel) {
        return {
                visitor: {
                        JSXOpeningElement(path) {
                                const name = Babel.types.jsxIdentifier('data-testname');
                                const value = Babel.types.stringLiteral(path.node.name.name);
                                path.node.attributes.push(Babel.types.jsxAttribute(name, value));
                        }
                }
        };
};

The code is tested with the ASTExplorer.


text:
Q: How to append list inside list in kotlin I have created an empty lists using
var lift = mutableListOf<Any(mutableListOf<Any(),mutableListOf<Any>())

But
lift[0].add(1)
Gives me error.
How to add elements to list inside list

A: The problem is that you have upcast the list type to Any instead of MutableList<Any>.
If you just typed:
mutableListOf(mutableListOf<Any>(),mutableListOf<Any>())

the type of items in the list is implicitly MutableList<Any>. But since you added <Any> like this:
mutableListOf<Any>(mutableListOf<Any>(),mutableListOf<Any>())

the compiler treats retrieved items as type Any instead of the specific type MutableList<Any> so you can't call functions on them.
You could also explicitly state the type like this, but it is not necessary:
mutableListOf<MutableList<Any>>(mutableListOf<Any>(),mutableListOf<Any>())

A: Try this:
val lift: MutableList<MutableList<Any>> = mutableListOf<MutableList<Any>>(mutableListOf<Any>(),mutableListOf<Any>())


text:
Q: deleting lines from a text file with bash I have two sets of text files. First set is in AA folder. Second set is in BB folder. The content of ff.txt file from first set(AA folder) is shown below.
Name        number     marks
john            1         60
maria           2         54
samuel          3         62
ben             4         63

I would like to print the second column(number) from this file if marks>60. The output will be 3,4. Next, read the ff.txt file in BB folder  and delete the lines containing numbers 3,4. How can I do this with bash?
files in BB folder looks like this. second column is the number.
   marks       1      11.824  24.015  41.220  1.00 13.65
   marks       1      13.058  24.521  40.718  1.00 11.82
   marks       3      12.120  13.472  46.317  1.00 10.62
   marks       4      10.343  24.731  47.771  1.00  8.18

A: awk 'FNR == NR && $3 > 60 {array[$2] = 1; next} {if ($2 in array) next; print}' AA/ff.txt BB/filename

A: This works, but is not efficient (is that matter?)
gawk 'BEGIN {getline} $3>60{print $2}' AA/ff.txt | while read number; do gawk -v number=$number '$2 != number' BB/ff.txt > /tmp/ff.txt; mv /tmp/ff.txt BB/ff.txt; done

Of course, the second awk can be replaced with sed -i

For multi files:
ls -1 AA/*.txt | while read file
do
    bn=`basename $file`
    gawk 'BEGIN {getline} $3>60{print $2}' AA/$bn | while read number
    do
        gawk -v number=$number '$2 != number' BB/$bn > /tmp/$bn
        mv /tmp/$bn BB/$bn
    done
done

I didn't test it, so if there is a problem, please comment.


text:
Q: My navigation drawer doesn't show up and i get an Error inflating class fragment I am trying to implement a navigation drawer, i have an issue where the page loads and the hamburger icon shows up. When i click the icon however, it changes into an arrow like it always does, but my drawer does not show up. and when i try to force one of the fragments to show up by default i get an Error inflating class fragment error.
Below is my page layout that holds the drawer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".app.index">

    <include layout="@layout/toolbar">
    </include>

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- The main content view -->
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <!-- The navigation drawer -->
        <fragment
            android:id="@+id/nav_drwr_fragment"
            class="com.mobile.map.mapversion20.helpers.NavDrawerManager"
            android:layout_width="280dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/nav_drawer_layout"
            tools:layout="@layout/nav_drawer_layout"/>

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

Below is my drawer layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:background="@color/colorPrimary">

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_centerInParent="true"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_profile"/>

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/drawerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"/>
</LinearLayout>

Down here is my Fragment manager
public class NavDrawerManager extends Fragment
{
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private static boolean isLaunch = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.nav_drawer_layout, container, false);

        setUpRecyclerView(view);

        return view;
    }
    private void setUpRecyclerView(View view) {

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);

        NavDrawerAdapter adapter = new NavDrawerAdapter(getActivity(), drawerItem.getData());
        NavDrawerManager manager = new NavDrawerManager();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        if(isLaunch)
        {
            isLaunch = false;
            manager.selectItem("DashBoard");
        }
    }

    public void setUpDrawer(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
        mDrawerLayout = drawerLayout;
        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
//                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
//                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                // Do something of Slide of Drawer
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });
    }
    public void selectItem(String title)
    {
        FragmentManager fragmentManager = getChildFragmentManager();

        switch (title)
        {
            case "Dashboard":
                Fragment dashFragment = new dashboard();
                        fragmentManager.beginTransaction()
                        .replace(R.id.content_frame,dashFragment)
                        .commit();
                break;
            case "Profile":
                Fragment profileFragment = new profile();
                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame,profileFragment)
                        .commit();
                break;
            case "Notifications":
                Fragment notificationsFragment = new notifications();
                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame,notificationsFragment)
                        .commit();
                break;
            case "Contact":
                Fragment contactFragment = new contact();
                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame,contactFragment)
                        .commit();
                break;
            default:
                Fragment defaultFrag = new dashboard();
                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame,defaultFrag)
                        .commit();
                break;
        }
    }
}

A: The issue is you need to make the DrawerLayout as the parent of you layout file like below :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The main content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/toolbar"/>

       <FrameLayout
           android:id="@+id/content_frame"
           android:layout_width="match_parent"
           android:layout_height="match_parent" />

    </LinearLayout>

    <!-- The navigation drawer -->
    <fragment
        android:id="@+id/nav_drwr_fragment"
        class="com.mobile.map.mapversion20.helpers.NavDrawerManager"
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/nav_drawer_layout"
        tools:layout="@layout/nav_drawer_layout"/>

</android.support.v4.widget.DrawerLayout>


text:
Q: Is it okay to extend a base view in Django's error pages (HTTP 404 and 500)? Django's views documentation states that "the default 500 view passes no variables to this template and is rendered with an empty Context to lessen the chance of additional errors," but is it okay to use the {% extends %} tag to re-use a base view in the 500 Server Error page (500.html)?

A: Yes, we have a very basic template that we extend our 404 and 500 templates from.  As long as your base template doesn't rely on a custom context, you should be good.


text:
Q: How can I redirect to a file a system error from running an executable without a needed library? I am trying to put into a file an error that the system gives me.
I have the following script:
#!/bin/bash

logfile="output.log"

echo "Starting" > $logfile

./cpi 2>&1 >> $logfile

echo "Ending" >> $logfile

exit

And the output I get in the file output.log is the following:
Starting
Ending

But in the screen I see this:
./cpi: error while loading shared libraries: libmpich.so.3: cannot open shared object file: No such file or directory

The error is on purpose. I took the path to that lib out of my #LD_LIBRARY_PATH. The point is, if the script runs in another machine and the library isn't there, I would like to get the error that goes to the screen.
I also need the output of my own program, thus I need the 2>&1 >> $logfile after its execution.
Any thoughts?

A: I may be misunderstanding.
If you want both the standard output and standard error from cpi to go to $logfile, swap the order of the redirections:
./cpi >> $logfile 2>&1

A: This error is reported by the loader and not the cpi binary so the redirection does not work here. You can test this by generating a cpi internal error. You might be able to log this error if you use a wrapper script to launch cpi.


text:
Q: Am I using IF COUNTA the correct way? I am using a IF COUNTA to count the number of spaces which contains data and according to that amount of cells containing data I want to categorize them in different zones.

This is my current sheet I am using. Block A is the random Pen teams draw and according to that they are inserted into the space next to their pen. I use VLOOKUP for every cell (TEAM, NAME & SURNAME) to find the pen and then pulls data from that pen which gives me the person's team, name and surname.

Here is where teams are inserted and the random pens are pulled. In the example they all pulled 1 - 16 just for easier test.
Using image one I reference the table name "Zone" for help: What I currently have inside that cell is the following...
=IF(COUNTA($B$2:$B$21)<=13,"Zone A",IF(COUNTA($B$2:$B$21)*13>=20,"Zone B","Test Again"))

So what I am trying to say here in my mind is that if COUNTA counts 13 or less then it should mark them "Zone A", else if COUNTA counts more than 13 or equal to 20 it should mark them "Zone B". So this works like that because there are 200 entries but I want the first 13 to be marked "Zone A" and everything else after 13 should be "Zone B". How do I formulate such a scenario?
In Cells B1:D21 I am using the following VLOOKUP formula...
=IF(ISNA(VLOOKUP([@[Pen Pulled]],'Team Entry'!$A$3:$G$35, 2, FALSE)), "",VLOOKUP([@[Pen Pulled]],'Team Entry'!$A$3:$G$35, 2, FALSE))

This is to not show NA when someone have not yet pulled the next pin.

A: i'm not exactly sure why u have this
IF(COUNTA($B$2:$B$21)*13>=20
that is asking if the count times 13 is => 20
Anything more than 13 would include 20 so I would think
IF(COUNTA($B$2:$B$21)>13
would give u what u r defining.


text:
Q: Morphism between formal groups and cohomology theories Background:
$FGL(R)$ will be the category of formal group laws over the ring $R$. If $(E,x_E)$ is an oriented spectrum (i.e. $x_E \in \tilde{E}^2(\mathbb{P}^{\infty})$ is sent to the unit $1 \in \tilde{E}^2(\mathbb{P}^1)$ by the pullback of the inclusion $i: \mathbb{P}^1 \hookrightarrow \mathbb{P}^\infty$), then the pullback of the multiplication $\mu$ as H-space of $\mathbb{P}^\infty$ define an element in $FGL(E^*(*))$ in the following way:
$
\mu^*:E^*(*)[[x_E]] \cong E^*(\mathbb{P}^\infty) \to E^*(\mathbb{P}^\infty \times \mathbb{P}^\infty) \cong E^*(*)[[x_1,x_2]]
$
where $x_i : = p_i^*(x_E)$ and the isomorphism are given by the collapsing of the Atiyah Hirzebruch spectral sequence. The fgl associated to $(E,x_E)$ is by definition $\mu^*(x_E) \in FGL(E^*(*))$. The Landweber exact theorem 'reverse' this contruction: let $f \in FGL(R)$ be a formal group law over $R$, then by certein hypothesis on $f$ the association
$ X \to MU^\bullet(X)\otimes_{\pi_*(MU)} R$
is a cohomology theory on CW-complexes ($MU$ is the complex cobordism spectrum and the $\pi_*(MU)$-module structure on $R$ is given by the classification map $\pi_*(MU) \to R$, since by Quillen's theorem the fgl of the complex cobordism is the universal one). This correspondence given by the Landweber's theorem seems to be only objectwise.
Question:
Given a morphism of formal group laws $\varphi$ over $R$, which is a power series in $R[[x]]$, is there a way to produce a natural transformation of the related cohomology theories induced by $\varphi$? Is there any reference in the literature where i could find an answer?

A: Yes, if $E$ and $E'$ are Landweber exact, then ring maps $E\to E'$ biject with isomorphisms of the associated formal groups, suitably interpreted.  One version of this (for the context where $E$ and $E'$ are $2$-periodic) is explained in Proposition 8.43 of this Memoir.  There is also a rather terse account in Proposition 11 of this lecture of Lurie.


text:
Q: WHILE and IF combination in Python I am a newbie in Python so I am trying to do some basic code.
Below you can see a simple code, but it gives me subsequent error:
File "", line 9
print('Not your number.')
^
IndentationError: expected an indented block
c = 0

while c < 5:

    print(f'The current number is: {c}')
    c = c + 1

    if c == 4:
    print('Not your number.')

else:
    print ('You have reached your limit.')

Could you please help me in finding the mistake? Thank you in advance!

A: Just as you indent in your bottom else clause, you must indent for your if clause in your while loop. The below should work.
c = 0

while c < 5:

    print(f'The current number is: {c}')
    c = c + 1

    if c == 4:
        print('Not your number.')

else:
    print ('You have reached your limit.')

A: Indentation in python matters. When you have a statement which expects a block of code to execute after it like an if statement or a while loop if you don't provide a properly indented block you will get a syntax error.
c = 0

while c < 5:

    print(f'The current number is: {c}')
    c = c + 1

    if c == 4:
        print('Not your number.') # this statement has to be indented because of the if statement
else:
    print ('You have reached your limit.')


text:
Q: Numpy Find Indices of Common Points in 2D Array System
OS: Windows 10 (x64), Build 1909
Python Version: 3.8.10
Numpy Version: 1.21.2
Question
Given two 2D (N, 3) Numpy arrays of (x, y, z) floating-point data points, what is the Pythonic (vectorized) way to find the indices in one array where points are equal to the points in the other array?
(NOTE: My question differs in that I need this to work with real-world data sets where the two data sets may differ by floating point error. Please read on below for details.)
History
Very similar questions have been asked many times:

*

*how to find indices of a 2d numpy array occuring in another 2d array

*test for membership in a 2d numpy array

*Get indices of intersecting rows of Numpy 2d Array

*Find indices of rows of numpy 2d array in another 2D array

*Indices of intersecting rows of Numpy 2d Array

*Find indices of rows of numpy 2d array in another 2D array
Previous Attempts
SO Post 1 provides a working list comprehension solution, but I am looking for a solution that will scale well to large data sets (i.e. millions of points):
Code 1:
import numpy as np

if __name__ == "__main__":
    big_array = np.array(
        [
            [1.0, 2.0, 1.2],
            [5.0, 3.0, 0.12],
            [-1.0, 14.0, 0.0],
            [-9.0, 0.0, 13.0],
        ]
    )

    small_array = np.array(
        [
            [5.0, 3.0, 0.12],
            [-9.0, 0.0, 13.0],
        ]
    )

    inds = [
        ndx
        for ndx, barr in enumerate(big_array)
        for sarr in small_array
        if all(sarr == barr)
    ]

    print(inds)

Output 1:
[1, 2]

Attempting the solution of SO Post 3 (similar to SO Post 2), but using floats does not work (and I suspect something using np.isclose will be needed):
Code 3:
import numpy as np

if __name__ == "__main__":
    big_array = np.array(
        [
            [1.0, 2.0, 1.2],
            [5.0, 3.0, 0.12],
            [-1.0, 14.0, 0.0],
            [-9.0, 0.0, 13.0],
        ],
        dtype=float,
    )

    small_array = np.array(
        [
            [5.0, 3.0, 0.12],
            [-9.0, 0.0, 13.0],
        ],
        dtype=float,
    )

    inds = np.nonzero(
        np.in1d(big_array.view("f,f").reshape(-1), small_array.view("f,f").reshape(-1))
    )[0]

    print(inds)

Output 3:
[ 3  4  5  8  9 10 11]

My Attempt
I have tried numpy.isin with np.all and np.argwhere
inds = np.argwhere(np.all(np.isin(big_array, small_array), axis=1)).reshape(-1)

which works (and, I argue, much more readable and understandable; i.e. pythonic), but will not work for real-world data sets containing floating-point errors:
import numpy as np

if __name__ == "__main__":
    big_array = np.array(
        [
            [1.0, 2.0, 1.2],
            [5.0, 3.0, 0.12],
            [-1.0, 14.0, 0.0],
            [-9.0, 0.0, 13.0],
        ],
        dtype=float,
    )

    small_array = np.array(
        [
            [5.0, 3.0, 0.12],
            [-9.0, 0.0, 13.0],
        ],
        dtype=float,
    )

    small_array_fpe = np.array(
        [
            [5.0 + 1e-9, 3.0 + 1e-9, 0.12 + 1e-9],
            [-9.0 + 1e-9, 0.0 + 1e-9, 13.0 + 1e-9],
        ],
        dtype=float,
    )

    inds_no_fpe = np.argwhere(np.all(np.isin(big_array, small_array), axis=1)).reshape(-1)

    inds_with_fpe = np.argwhere(
        np.all(np.isin(big_array, small_array_fpe), axis=1)
    ).reshape(-1)

    print(f"No Floating Point Error: {inds_no_fpe}")
    print(f"With Floating Point Error: {inds_with_fpe}")

    print(f"Are 5.0 and 5.0+1e-9 close?: {np.isclose(5.0, 5.0 + 1e-9)}")

Output:
No Floating Point Error: [1 3]
With Floating Point Error: []
Are 5.0 and 5.0+1e-9 close?: True

How can I make my above solution work (on data sets with floating point error) by incorporating np.isclose? Alternative solutions are welcome.
NOTE: Since small_array is a subset of big_array, using np.isclose directly doesn't work because the shapes won't broadcast:
np.isclose(big_array, small_array_fpe)

yields
ValueError: operands could not be broadcast together with shapes (4,3) (2,3)

Update
Currently, the only working solution I have is
inds_with_fpe = [
    ndx
    for ndx, barr in enumerate(big_array)
    for sarr in small_array_fpe
    if np.all(np.isclose(sarr, barr))
]

A: I'm not going to give any code, but I've dealt with problems similar to this on a large scale. I suspect that to get decent performance with either of these approaches you'll need to implement the core in C (you might get away with using numba).
If both your arrays are huge there are a few approaches that can work.
Primarily these boil down to building a structure that can be used to find the nearest neighbor of a point from one of the arrays, and then querying it for each point in the other data set.
To do this I've previously used a Kd Tree approach, and a grid based approach.
The basis of the grid based approach is

*

*find the 3D extents of your first array.

*split this region into LNM bins.

*For each input point in the second array, find its bin. Any point that matches it will be in that bin.

The edge cases you need to handle are

*

*if the point falls on the edge of a bin, or close enough to the boundary of a bin that points considered equal to it might fall in the other bin - then you need to search more than one bin for its "equal".

*if the point falls outside all the bins, but close to the edge, points "equal" to it might fall in a nearby bin.

The downsides are that this is bad for data that is not uniformly distributed.
The upside is that it is relatively simple. Expected run time for uniform data is n1 * n2 / (L*N*M) (compared to n1*n2). Typically you select L,N,M such that this becomes O(n log(n)). You also get some further uplift from sorting the second array to improve reuse of the bins. It is also relatively easy to parallelize (both the binning and searching)
The K-d Tree approach is similar. IIRC it gives O(n log(n)) behavior, but it is trickier to implement, and the building of the data structure is tricky to parallelize). It tends to not be as cache friendly which can mean that although its asymptotic run-time is better than the grid based approach it can runs slower in practice. However it does give better guarantees for non-uniformly distributed data.

A: As @Michael Anderson already mentioned this can be implemented using a kd-tree. In comparsion to your answer this solution is using an absolute error. If this is acceptable or not depends on the problem.
Example
import numpy as np
from scipy import spatial

def find_nearest(big_array,small_array,tolerance):
    tree_big=spatial.cKDTree(big_array)
    tree_small=spatial.cKDTree(small_array)
    return tree_small.query_ball_tree(tree_big,r=tolerance)

Timings
big_array=np.random.rand(100_000,3)
small_array=np.random.rand(1_000,3)
big_array[1000:2000]=small_array

%timeit find_nearest(big_array,small_array,1e-9) #find all pairs within a distance of 1e-9
#55.7 ms ± 830 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

#A. Hendry
%timeit np.argwhere(np.isclose(small_array, big_array[:, None, :]).all(-1).any(-1)).reshape(-1)
#3.24 s ± 19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Credit to @AndrasDeak for this answer
The following code snippet
inds_with_fpe = np.argwhere(
    np.isclose(small_array_fpe, big_array[:, None, :]).all(-1).any(-1)
).reshape(-1)

will make the code work. The corresponding output is now:
No Floating Point Error: [1 3]
With Floating Point Error: [1, 3]
Are 5.0 and 5.0+1e-9 close?: True

None in the above creates a new axis (same as np.newaxis). This changes the shape of the big_array array to (4, 1, 3), which adheres to broadcasting rules and permits np.isclose to run. That is, big_array is now a set of 4 1 x 3 points, and since one of the axes in big_array is 1, small_array_fpe can be broadcast to 2 1 x 3 arrays (i.e. shape (2, 1, 3)) and the elements can be compared element-wise.
The result is a (4, 2, 3) boolean array; every element of big_array is compared element-wise to every element of small_array_fpe and the components where they are close (within a specific tolerance) is returned. Since all is called as an object method rather than a numpy function, the first argument to the function is actually the axis rather than the input array. Hence, -1 in the above functions means "the last axis of the array".
We first return the indeces of the (4, 2, 3) array that are all True (i.e. all (x, y, z) components are equal), which yields a 4 x 2 array. Where any of these are True is the corresponding index in big_array where the points are equal, yielding a 4 x 1 array.
argwhere returns indices grouped by element, so its shape is normally (number  nonzero items, num dims of input array), hence we flatten it into a 1d array with reshape(-1).
Unfortunately, this requires a quadratic amount memory w.r.t. the number of points in each array, since we must run through every element of big_array and check it against every element of small_array_fpe. For example, to search for 10,000 points in a set of another 10,000 points, for 32-bit floating point data, requires
Memory = 10000 * 10000 * 4 * 8 = 32 GiB RAM!

If anyone can devise a solution with a faster run time and reasonable amount of memory, that would be fantastic!
FYI:
from timeit import timeit

import numpy as np

big_array = np.array(
    [
        [1.0, 2.0, 1.2],
        [5.0, 3.0, 0.12],
        [-1.0, 14.0, 0.0],
        [-9.0, 0.0, 13.0],
    ],
    dtype=float,
)

small_array = np.array(
    [
        [5.0 + 1e-9, 3.0 + 1e-9, 0.12 + 1e-9],
        [10.0, 2.0, 5.8],
        [-9.0 + 1e-9, 0.0 + 1e-9, 13.0 + 1e-9],
    ],
    dtype=float,
)

def approach01():
    return [
        ndx
        for ndx, barr in enumerate(big_array)
        for sarr in small_array
        if np.all(np.isclose(sarr, barr))
    ]

def approach02():
    return np.argwhere(
        np.isclose(small_array, big_array[:, None, :]).all(-1).any(-1)
    ).reshape(-1)

if __name__ == "__main__":
    time01 = timeit(
        "approach01()",
        number=10000,
        setup="import numpy as np; from __main__ import approach01",
    )
    time02 = timeit(
        "approach02()",
        number=10000,
        setup="import numpy as np; from __main__ import approach02",
    )

    print(f"Approach 1 (List Comprehension): {time01}")
    print(f"Approach 2 (Vectorized): {time02}")

Output:
Approach 1 (List Comprehension): 8.1180582
Approach 2 (Vectorized): 0.9656997


text:
Q: Create basic php page not working I'm trying to create new page in PHP(new_page.php), successful created page will be insert into database (create_page.php), but now it is not working, not sure which steps i am missing, any helps are appreciate. Below is my code & screenshots:
Mysql table:
http://i60.tinypic.com/2h3aofr.png
new_page.php
http://i60.tinypic.com/21dmop2.png
<?php $host = "localhost";
$name = "root";
$password = "";
$db = "test_son";
$connection = mysqli_connect($host, $name, $password, $db);

//Check if connect to MySQL works

if (mysqli_connect_errno()){

    die("Connection to MySql error " . mysqli_connect_errno());
}?>

<?php
function find_all_pages(){
    global $connection;
    $query  =  "select * from pages ";
    $query .= "order by position asc";
    $page_set = mysqli_query($connection, $query);
    confirm_query($page_set);
    return $page_set;
}?>

Create Page

        <form action="create_page.php" method="post">

Subject Id:
                <input type="number" name="subject_id" value="" />

Book name:
                <input type="text" name="book_name" value="" />

Position:
                <select name="position">

                    <?php

                    $page_set = find_all_pages();
                    $page_count = mysqli_num_rows($page_set);
                    for ($count=1; $count <= $page_count; $count++){
                    echo "<option value=\"1\">{$count}</option>";}
                    ?>

                </select>

visible
                <input type="radio" name="visible" value="0" /> No
                <input type="radio" name="visible" value="0" /> Yes

            <input type="submit" name ="submit" value="Create Page" />
        </form>

create_page.php
<?php
if (isset($_POST["submit"])){
    //Process the form
    $subject_id = $_POST["subject_id"];
    $book_name = $_POST["book_name"];
    $position = $_POST["position"];
    $visible = $_POST["visible"];

    $book_name = mysqli_real_escape_string($connection, $book_name);
    $subject_id = mysqli_real_escape_string($connection, $subject_id);

    //Perform database query
    $query  = "insert into pages (";
    $query .= " subject_id, 'book_name', position, visible";
    $query .= " ) values ( ";
    $query .= "$subject_id, '$book_name', $position, $visible ";
    $query .= ")";

    $result = mysqli_query($connection, $query);

    if ($result){
            //Success will redirect to manage content page
            $_SESSION["message"] = "page was created. ";
            redirect("manage_content.php");
        } else {
            //Failure will redirect to new subject page
            //$_SESSION["message"] = "subject was not created. Please check following possible errors:
 "
                    //. " menu name is not blank
 visible is not blank";

            //redirect("new_page.php");
            echo "fail " . mysqli_error($connection) ;
        }
}

?>
When i submitted the create page button, error appears:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''book_name', position, visible ) values ( 121, 'how to win influence 1234', 1, 0'

A: There are security vulnerabilities in the way you are creating that query. But to specifically respond to your issue, get rid of the '  around 'book_name'.

A: You shouldn't have a ' character in the list of column_names .... column names are not string literals, they're column names. If they absolutely have to be quoted (e.g. if you have a column name that is a MySQL reserved word, then you use backticks(`) not quotes (')
$query  = "insert into pages (";
$query .= " subject_id, book_name, position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";

Now please learn about prepared statements and bind variables


text:
Q: JBoss8: Error UT005023 - Exception handling request to URL I am getting the below error on JBoss 8 server.
17:36:07,482 ERROR [io.undertow.request] (default task-22) UT005023: Exception handling request to /user/XMLPreviewer: org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/sun/org/apache/xml/internal/serialize/XMLSerializer

I have got the following dependencies in my pom:
    <dependency>
        <groupId>javax.xml</groupId>
        <artifactId>jaxp-api</artifactId>
        <version>1.4.2</version>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>1.4.01</version>
            <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>xml-apis</groupId>
        <artifactId>xml-apis</artifactId>
        <version>1.4.01</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.parsers</groupId>
        <artifactId>jaxp-api</artifactId>
        <version>1.4.5</version>
    </dependency>

A: You are asking for trouble including any of those jars in your application.
The APIs and implementation provided by those jars exist in the JDK (as far back as Java 5) and you will find life far simpler if you make use of those instead of adding additional (possibly obsolete) versions to your application.
Furthermore, Java EE may specify further extensions to the standard (JDK provided) XML APIs (JAXB 2.2 for example) and therefore provide this extended implementation to your application transparently.
Therefore, rather than the set of dependencies you have above, if you add the following instead:
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

The <scope>provided</scope> element is important because this jar does not need to be deployed with your application. The classes it contains are provided by your Java EE 7 server implementation.
If you add this dependency then you can also discard other dependencies such as the servlet-api, jsp-api, ejb-api, etc as these are all included in the javaee-api dependency.


text:
Q: How to only replace all hyphens after 2nd instance In a string like this: Last-Name — lives on a road, in south-shore.
I am trying to replace all instances of "," & "-" in to " " with only skipping the 2nd instance of "-". I then want to replace the "-" with a ",".
I have currently tried to us this:
var all = node.InnerText.Replace(","," ");
var hyph = all.Replace("—",",").Replace("-",",");

Which works... except it is replacing everything and I am needing the 2nd instance of "—" to remain while all other instances of ",", "—" & "-"'s are changed to " ". So it looks like this when it is done: (Last, Name , lives on a road in south, shore.).
When I need it to look like: (Last Name , lives on a road in south shore).
Doing some looking around, it seems that IndexOf() is the way to go but I am unsure of how to setup my query. Would I be on the right track using something like this? Or is there a better way to go about this? To be honest I am not entirely sure and I am still learning C# so sorry if this is poorly worded or way off mark.
int position = dash.IndexOf(find);
if (position > 1)
{
return dash;
}
return dash.Substring(1, position) + replace + dash.Substring(postion + find.Length);

In every case it will be:
last name — some text here
or
last name — some-sort of text
or
last-name — more text, here
or
last name — more-text here
Where it just needs to be:
last name, some text here.
Thank you for any help!

A: Do this with regex, look up for search operator and set it to search for everything after the first. Sorry answering this on the phone so I can't look it up at the moment.

A: Here you go
int firstHyph = all.IndexOf('-'); // find the first hyphen
int secondHyph = all.IndexOf('-', firstHyph + 1); // find the second hyphen
var sb = new StringBuilder(all);
sb[secondHyph] = '#'; // replace the second hyphen with some improbable character
// finally, replace all hyphen and whatever you need and change that
// "second hyphen" (now sharp) to whatever you want
var result = sb.ToString().Replace("-", " ").Replace("#", ",");

A: A simple and, exclusive solution
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

public class Test
{
    public static void Main()
    {
        string all = Convert.ToString("In every case it will be last name — some text here OR last name — some-sort of text OR last-name — more text, here OR last name — more-text here").Replace(",", " ");
        int hyph1 = all.IndexOf('—');
        int hyph2 = hyph1 + all.Substring(++hyph1).IndexOf('—');
        string partial = all.Substring(0, ++hyph2).Replace("—", " ");
        string res = String.Concat(partial, "—", all.Substring(++hyph2).Replace("—", " ").Replace("-", ","));
        Console.Write(res.ToString());
    }
}

See on the Fiddle:
http://ideone.com/wWCGeA


text:
Q: How do I take the variance of a subset of a vector? I am trying to use dplyr to create summary statistics over different groups of the data.
Let's say for group 1:
variable1 <- c(4,51,100,200,10)
And I want code something along these lines:
library(dplyr)

summaryVars <- df %>%
  group_by(group) %>%
  summarise_all(funs(mean, var, limited_var = var(if variable1 > 50))

How can I return limited_var = var(c(51,100,200))

A: One way to go is to use mutate instead of summarise, and use slice at the end, i.e.
library(dplyr)

#Creating a toy data set
df <- data.frame(variable1 = c(4, 51, 100, 200, 10), iris, stringsAsFactors = FALSE) %>%
    group_by(Species) %>%
    filter(row_number() == 1:5) %>%
    ungroup()

str(df)
#Classes 'tbl_df', 'tbl' and 'data.frame':  15 obs. of  6 variables:
 #$ variable1   : num  4 51 100 200 10 4 51 100 200 10 ...
 #$ Sepal.Length: num  5.1 4.9 4.7 4.6 5 7 6.4 6.9 5.5 6.5 ...
 #$ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.2 3.2 3.1 2.3 2.8 ...
 #$ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 4.7 4.5 4.9 4 4.6 ...
 #$ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 1.4 1.5 1.5 1.3 1.5 ...
 #$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 2 2 2 2 2 ...

df %>%
 group_by(Species) %>%
 mutate(limited_var = var(variable1[variable1 > 50])) %>%
 mutate_at(vars(-limited_var), funs(mean, var)) %>%
 slice(1L) %>%
 ungroup()

A: Here is all you need to answer my question:
limited_var = var(variable1[variable1 > 50])

use that within dplyr to calculate the variance for a subset of the group.


text:
Q: Can I program a Raspberry Pi with Python over SSH? So, I know Python, and I've been thinking of getting a Raspberry Pi, as I heard that you can program it with Python. The thing is, I don't have an extra HDMI monitor at hand, but only a Windows 10 laptop (besides, what use would an R-Pi be if you want to use it in a project, when it has to be plugged in to a monitor, mouse etc.?), so I found an alternative called SSH.  After watching a few tutorials, I'm positive that I'll be able to set up an R-Pi wirelessly with ease.  However, it still hasn't become clear to me, how I would be able to program an R-Pi with Python over SSH.
My initial goal with the R-Pi is to program it with Python, to do things like from saying "hello world", to controlling the GPIO ports, all without external hardware (except that laptop), but I haven't found anything on the internet that suits my needs.  Now, my question is, how do I do such, and to what extent will I be able to control my Pi with Python through another computer?
Thank you in advance for the help!

A: When you connect over ssh to a raspberry pi you are greeted with a terminal.
In that terminal you can use a command line editor like nano or vim to make and edit files. You can also use the command line to execute them.
In this little session I connect to a raspberry pi and then make a python program and execute it.
trirpi@mycomputer:~$ ssh pi@192.168.1.3
pi@192.168.1.3's password:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Dec 26 17:41:02 2016 from 192.168.1.83

pi@raspberrypi:~ $ ls
projects
pi@raspberrypi:~ $ cd projects/
pi@raspberrypi:~/projects $ vim aprogram.py
pi@raspberrypi:~/projects $ python aprogram.py

You should learn how to use the command line so you can use commands like cd.
You could also setup a vnc server (I think the new raspbian image has one installed by default). That way you can also see gui's and not only a terminal.


text:
Q: RT5572 shown in lsusb but not iwconfig I've searched google and I can't find a solution to this problem :[
I'm running Debian. Simply did a minimal netinst with no desktop environment:
~#: uname -r
3.2.0-4-686-pae

I have this product which uses the Ralink 5572 chipset. According to here it should be supported by the rt2800usb kernel module.
When I plug the stick in I see it come up in dmesg like so:
usb 1-2: new high-speed USB device number 5 using ehci-pci
usb 1-2: New USB device found, idVendor=2001, idProduct=3c1a
usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-2: Product: 11n Adapter
usb 1-2: Manufacturer: Ralink
usb 1-2: SerialNumber: 1.0

It is also seen by lsusb.
And that's it. rt2800usb is not loaded (I have already run apt-get install firmware-ralink) On the wiki page I linked there appears to be extra stuff from dmesg. When I check iwconfig I don't see an interface for the device. I have also tried modprobe rt2800usb and the module loads no problem, but the interface still does not exist.
I can't find any errors anywhere so I can't figure out what is wrong. Any ideas what I can do?

A: The problem is that your kernel doesn't have a driver for this device.
The device's model and category are recognized because these are standard USB features. Seeing them correctly identified in the output of lsusb doesn't imply that you have a driver that would do anything useful with the device (and contrariwise you might have a working driver and yet not see the model identification in lsusb if lsusb was working on an old database of model names).
The rt2800usb driver, like any other USB driver, registers a list of USB devices (model and manufacturer identifiers) that it can handle. Your particular model was added in kernel 3.9.
It's possible that merely declaring the extra model will make it work. It's also possible that this model requires a workaround in the code somewhere but there doesn't appear to be any specific treatment of that particular model in the current version, so you might have a chance.
You can force the driver to believe that it can handle your device. Once the module is loaded, register a dynamic USB device ID:
echo 0x2001 0x3c1a >/sys/bus/usb/drivers/rt2800usb/new_id

To arrange for the module to be loaded automatically, you can declare an alias for it. I think that you'd still need to register the device ID. You should be able to do that with an install directive in /etc/modprobe.d. Create a file /etc/modprobe.d/rt2800usb-local.conf containing
alias usb:v2001p3c1Ad*dc*dsc*dp*ic*isc*ip*in* rt2800usb
install rt2800usb /sbin/modprobe --ignore-install rt2800usb && echo 0x2001 0x3c1a >/sys/bus/usb/drivers/rt2800usb/new_id


text:
Q: Detect if (Android) phone encryption is enabled I want to store data securely in a user friendly way.
As default the data is encrypted and needs a pass phrase to be unlocked. However, if the phone is encrypted and needs a pass phrase to be unlocked this seems redundant and I would like to give the option to turn of application encryption thus avoiding typing in a (new) pass phrase when starting the application.
However - is it possible to detect if phone encryption is enabled? If so, how?

A: Use getStorageEncryptionStatus() on DevicePolicyManager to find out the encryption status of the device.
Source


text:
Q: How to enforce max active run = 1 for a group of DAGs in Airflow? I have a group of DAGs and I only want one of them to run at any given time.
ExternalTaskSensor will not work if I trigger a backfill job for one of them for a very old date.
I am aware of pool and priority weights method.
Another approach could be to make a custom operator and check all the dag runs of all the dags in the group.
Is there any other method to achieve this?

A: Airflow doesn't support this feature, even if you use pools, you need to use the same pool for all the tasks from all the dags in the group, and set the pool slots to 1, which break the parallelism.
You can achieve this by merging the dags in one dag and adding a branch operator which processes a param from dag_run conf to know which dag should it runs:
import pendulum

from airflow.operators.empty import EmptyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.models.param import Param
from airflow.models import DAG
from airflow.decorators import task

default_args = {}

def dag_1(main_dag: DAG):
    dag_id = "dag_1"
    start_task = EmptyOperator(
        task_id=dag_id,
        dag=main_dag
    )
    task_1 = EmptyOperator(
        task_id=f"{dag_id}.task1",
        dag=main_dag
    )
    task_2 = EmptyOperator(
        task_id=f"{dag_id}.task2",
        dag=main_dag
    )
    start_task >> task_1 >> task_2
    return start_task

def dag_2(main_dag: DAG):
    dag_id = "dag_2"
    start_task = EmptyOperator(
        task_id=dag_id,
        dag=main_dag
    )
    task_1 = EmptyOperator(
        task_id=f"{dag_id}.task1",
        dag=main_dag
    )
    task_2 = EmptyOperator(
        task_id=f"{dag_id}.task2",
        dag=main_dag
    )
    task_3 = EmptyOperator(
        task_id=f"{dag_id}.task3",
        dag=main_dag
    )
    start_task >> [task_1, task_2] >> task_3
    return start_task

with DAG(
    dag_id='multiple_dags',
    default_args=default_args,
    start_date=pendulum.datetime(2023, 1, 1),
    schedule=None,
    max_active_runs=1,
    params={
        "dag_id": Param(default="dag_1", enum=["dag_1", "dag_2"])
    }
) as dag:
    @task.branch(task_id="start_task")
    def branch(**context):
        return context["params"]["dag_id"]

    branch() >> [
        dag_1(dag),
        dag_2(dag)
    ]

for param dag_1:

for param dag_2:

Then if you want to run these dags on different schedules, you can create N new dags contains one task from TriggerDagRunOperator to trigger the main dag and pass the dag id as param:
from airflow.operators.trigger_dagrun import TriggerDagRunOperator

def create_trigger_dag(dag_id, schedule):
    with DAG(
        dag_id=dag_id,
        start_date=pendulum.datetime(2023, 1, 1),
        schedule=schedule,
        catchup=False
    ) as dag:
        TriggerDagRunOperator(
            task_id="trigger_dag",
            trigger_dag_id="multiple_dags",
            conf={
                "dag_id": dag_id
            }
        )
    return dag

trigger_dag_1 = create_trigger_dag(dag_id="dag_1", schedule="*/1 * * * *")

trigger_dag_2 = create_trigger_dag(dag_id="dag_2", schedule="*/2 * * * *")

And here is the result, 2 runs from dag_1 for each run from dag_2:


text:
Q: Knockout issue displaying content based on dropdown value I just created a jsfiddle so that u can do quick edits
JSFIDDLE Link to Code

As you can see the Array selectedChoice works fine in the dropdown and displays content based on the dropdown selected value.
However, when I try to use a CountryModel with properties id and name it is trowing errors in Internet Explorer but not in Firefox. however, is odd that the default behavior is not to hide the content
This content appear when US is selected

I suspect this code

I also tried this

This content appear when Russia is selected

Two issues:

Typescript code
class CountryModel {
    id: number;
    name: string;

}

compiles to
var CountryModel = (function () {
    function CountryModel() {
    }
    return CountryModel;
})();

Typescript Code
///
///
///
class ViewModel {
    constructor()
    {
        //initialize the data for the model now this has two purposes. Consider separating the model from its data generation.
        var x = new CountryModel();
        x.id = 1;
        x.name = "Russia";
        var y = new CountryModel();
        y.id = 2;
        y.name = "US";
        this.countries.push(x);
        this.countries.push(y);
    }

    availableDrugs = ['A', 'B', 'others'];
    firstName: KnockoutObservable<string>  = ko.observable();
    isVisible: KnockoutObservable<boolean> = ko.observable(true);
    selectedChoice = ko.observable();
    selectedChoiceWithModel = ko.observable();
    countries: KnockoutObservableArray<CountryModel> = ko.observableArray([]);
    sendMe = function () {

        alert(ko.toJSON({ selectedCountryId: this.selectedChoice() }));
    };
}

$(() => {
    ko.applyBindings(new ViewModel(), document.getElementById("model"));
});

Compiles to
/// <reference path="CountryModel.ts" />
/// <reference path="../Scripts/typings/knockout/knockout.d.ts" />
/// <reference path="../Scripts/typings/jquery/jquery.d.ts" />
var ViewModel = (function () {
    function ViewModel() {
        this.availableDrugs = ['A', 'B', 'others'];
        this.firstName = ko.observable();
        this.isVisible = ko.observable(true);
        this.selectedChoice = ko.observable();
        this.selectedChoiceWithModel = ko.observable();
        this.countries = ko.observableArray([]);
        this.sendMe = function () {
            alert(ko.toJSON({ selectedCountryId: this.selectedChoice() }));
        };
        //initialize the data for the model now this has two purposes. Consider separating the model from its data generation.
        var x = new CountryModel();
        x.id = 1;
        x.name = "Russia";
        var y = new CountryModel();
        y.id = 2;
        y.name = "US";
        this.countries.push(x);
        this.countries.push(y);
    }
    return ViewModel;
})();

$(function () {
    ko.applyBindings(new ViewModel(), document.getElementById("model"));
});

Html code

@section scripts
{

}

First name:

First name: <input data-bind="value: firstName" />

   <input type="checkbox" data-bind="checked: isVisible"/>

Hide this content.

    <select data-bind="options: availableDrugs, value: selectedChoice, optionsCaption: 'choose..'"></select>
      <input type="text" data-bind="value: firstName, visible: selectedChoice() === 'others', hasfocus: selectedChoice() === 'others'" />

 This content appear when a is selected

This content appear when B is selected

      <select data-bind="options: countries, optionsText: 'name', value: selectedChoiceWithModel, optionsCaption: 'Choose...'"></select>

This content appear when US is selected

A: I suspect your binding is breaking in ie and not in other better browsers because of a case error that ie can't handle.
The hasFocus binding is camelCase so try converting all your hasfocus bindings to hasFocus.
Edit
Alright, your problem was more than one -
http://jsfiddle.net/BJhQz/14/
You need to make sure that selectedChoiceWithModel is defined before you try to bind to properties on it.  I added a containerless binding to your view to keep from trying to see the name of it if it was not yet selected.
Next, I made a few updates to your view model to make it easier to understand for me.  I am not saying they are required, but without them your view model was suffering from my inability to read it.
StackOverflow.com wants some code so here it is -

This content appear when Russia is selected

A: First of all I really appreciate everyone's help. You did help me identify some of the issues with the code. I have completed the code and here is the result for future people that will probably undergo the same pain as me. i do want to point out that selectedModelWirhChoice().name() was the wrong approach. Instead the key was to put optionsValue: 'name' so that selectedChoiceWithModel() would bind to the property name. Of course one could have also chosen to do the following
 optionsValue: 'id' to bind to the id number.
JsFiddle Code for your convenience
I have included the complete JSFiddle for your convenience but unfortunately I it will show the compiled JavaScript instead of the clean Typescript code. In any case the typescript code is below...

First name:

First name: <input data-bind="value: firstName" />

   <input type="checkbox" data-bind="checked: isVisible"/>

Hide this content.

    <select data-bind="options: availableDrugs, value: selectedChoice, optionsCaption: 'choose..'"></select>
      <input type="text" data-bind="value: firstName, visible: selectedChoice() === 'others', hasFocus: selectedChoice() === 'others'" />

 This content appear when a is selected

This content appear when B is selected

      <select data-bind="options: countries, optionsText: 'name', optionsValue: 'name', value: selectedChoiceWithModel, optionsCaption: 'Choose...'"></select>

        .

     Content is displayed when Russia is selected
         Content is displayed when US is selected

Keep in mind i used typescript to generate the javascript

class CountryModel {

    public id: number;
    public name: string;

}

/// <reference path="CountryModel.ts" />
/// <reference path="../Scripts/typings/knockout/knockout.d.ts" />
/// <reference path="../Scripts/typings/jquery/jquery.d.ts" />

class ViewModel {
    constructor()
    {
        //initialize the data for the model now this has two purposes. Consider separating the model from its data generation.
        var x = new CountryModel();
        x.id = 1;
        x.name = "Russia";
        var y = new CountryModel();
        y.id = 2;
        y.name = "US";
        this.countries.push(x);
        this.countries.push(y);

    }

    availableDrugs = ['A', 'B', 'others'];
    firstName: KnockoutObservable<string>  = ko.observable();
    isVisible: KnockoutObservable<boolean> = ko.observable(true);
    selectedChoice = ko.observable();
    selectedChoiceWithModel = ko.observable();
    countries: KnockoutObservableArray<CountryModel> = ko.observableArray([]);
    sendMe = function () {

        alert(ko.toJSON({ selectedCountryId: this.selectedChoice() }));
    };
}

$(() => {
    ko.applyBindings(new ViewModel(), document.getElementById("model"));
});


text:
Q: The code cannot be executed in the Firefox browser How can I do it in the Firefox browser?
Look
<script type="text/javascript">
    var adfly_id = 16627167;
    var popunder_frequency_delay = 0;
    var adfly_protocol = 'https';
</script>

<script src="https://cdn.adf.ly/js/display.js"></script>


text:
Q: Javascript ES6: How to retrieve calling subclass from a static method defined in superclass New to JavaScript.
Seeking some guidance on how to access the calling class name from a static method defined in the superclass using ES6 classes.  I've spent an hour searching, but have not been able to come up with a solution.
A code snippet may help clarify what I am seeking
class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return '....help here ...' }
}

class SubClass extends SuperClass { }

let sc = new SubClass()

console.log(sc.callingInstanceType)     // correctly prints 'SubClass'
console.log(SubClass.callingClassType)  // hoping to print 'SubClass'

As illustrated above, I can easily get the subclass name from a instance.  Not quite sure how to access from a static method.
Ideas for the implementation of static get callingClassType() welcomed.

A: callingClassType is a function (well, a getter in this case, same thing). The value of this inside a function depends on how it is called. If you call a function with foo.bar(), then this inside bar will refer to foo.
Thus if you "call" the function with SubClass.callingClassType, this will refer to SubClass. SubClass is itself a (constructor) function thus you can get its name via the name property.
So your method definition should be
static get callingClassType() { return this.name; }

class SuperClass {
  get callingInstanceType() {
    return this.constructor.name
  }
  static get callingClassType() {
    return this.name
  }
}

class SubClass extends SuperClass {}

let sc = new SubClass()

console.log(sc.callingInstanceType)
console.log(SubClass.callingClassType)

Have a look at the MDN documentation to learn more about this.

A: Use SuperClass.prototype.constructor.name:

class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return SuperClass.prototype.constructor.name; }
}

class SubClass extends SuperClass {}
class SubClass2 extends SuperClass {
     static get callingClassType() { return SubClass2.prototype.constructor.name; }
}

console.log(SuperClass.callingClassType); // 'SuperClass'
console.log(SubClass.callingClassType); // 'SuperClass'
console.log(SubClass2.callingClassType); // 'SubClass2'

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static#Examples:
class Triple {
  static triple(n) {
    if (n === undefined) {
      n = 1;
    }
    return n * 3;
  }
}

class BiggerTriple extends Triple {
  static triple(n) {
    return super.triple(n) * super.triple(n);
  }
}

console.log(Triple.triple());        // 3
console.log(Triple.triple(6));       // 18

var tp = new Triple();

console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)

console.log(tp.triple());
// 'tp.triple is not a function'.


text:
Q: Can I refer to a node using a short name in DOT I'm trying to respresent a binary tree with GraphViz using DOT, can I have a longer text string as a node's text but them just refer to it using a shortname when linking it?
I'm working with GraphViz through Pandoc and Pandoc-plot.
I've tried setting and node's ID, name, label and refering to it but it just doesn't work. In my document it just got the codeblock instead a rendered graph, I've tested it with a simple graph and it renders fine.
I've tried a graph like this in the GraphViz online editor and the node's with the long names don't get connected in the right way.
graph {
   "Adam \n 01/01"[id="adam"]
   "Bella \n01/02"[id="bella"]
   "Eloise \n01/05"

   adam -- bella
   bella -- eloise
}

A: Looks like you mix up node names and node labels (by default the node name is equal to the node label, so in your case the node name is "Adam \n 01/01" and also the label is "Adam \n 01/01" so you have to refer to it like:
"Adam \n 01/01" -- "Bella \n01/02"

but this is quite cumbersome and error prone so looks like you are looking for (as indicated bu "short names" request):

graph {
   adam [label="Adam \n 01/01"]
   bella [label="Bella \n01/02"]
   eloise [label ="Eloise \n01/05"]

   adam -- bella
   bella -- eloise
}


text:
Q: What is the passphrase used for in ssh key generation? I was setting up ssh for github and I found it interesting that in addition to a public and private key, a "passphrase" is also needed.
The public/private key pair is generated automatically and the passphrase is asked for after the generation.
Here is the github documentation..  What is the purpose of this "passphrase".
Does it effect the public and private key generation?

A: The passphrase is used to lock access to the private SSH key. The reason you use keys is to have something more secure than passwords, but a private keyfile without protection will grant access to all your systems to anyone who accesses your computer. So, the passphrase is there to add an extra security layer.

A: It does not effect the public/private key generation.  It is simply used as an added precaution so that someone who gains access to your PC or similar does not have complete access to all your files.
They will still need a passphrase which is paired with the private key to identify you.
This passphrase can be saved so that you only have to use it once.


text:
Q: killing form and the dot product When going from talking about roots as functionals to talking about roots as vectors in a Euclidian space (root system), does the killing form become the dot product? Are the killing form and dot product equivalent? Humphreys just went straight from the killing form to the dot product. Because the killing of two roots such that one is not a negative of the other is 0, but the dot product is less than zero, if they are simple roots.
Thanks

A: The killing form restricted to the Cartan subalgebra is an inner product, thus there is an isometry between the Cartan subalgebra with the killing form and $\mathbb{R}^k$ with the dot product given by choosing an orthonormal (w.r.t. the killing form) basis. This is the equivilance I think you're talking about.
What you're thinking of, is $ < e_\alpha, e_\beta >_K = 0 $ if $\alpha$ and $\beta$ are not scalar multiples. These $e$s are not the roots but act on the Cartan subalgebra via the roots.


text:
Q: Find a regex character class with a regex I need to find a regex character class (that is, everything between square brackets) with a regex. So I've come up with the following regex:

(?<!\\)\[(?:\^\])?(?:[^]\\]+|\\.)*\]

And that regex works perfectly fine when I test it in Notepad++ - both in the search window (Ctrl-F) and in the RegEx Helper plugin - but I get an error when I try to use it in PHP code.

$string = '[^abcd\]efgh]';

$pattern = '/
(?<!\\) \[              # an opening square bracket not preceded by a backslash
  (?:\^\])?             # circumflex and closing bracket 0 or 1 times
(?:
  [^]\\]+               # not a closing bracket, nor a backslash 1-n times
 |                      # or
   \\.                  # any escaped character (including an escaped closing bracket)
)*                      # 0-n times
\]                      # closing bracket
/x';

preg_match_all($pattern, $string, $matches);

print_r($matches);

Output:

Warning: preg_match_all(): Compilation failed: missing terminating ]
  for character class at offset 33 in
  C:...\test.php on line 21

Where am I wrong?

A: A literal backslash needs to be expressed in a PHP regex by four backslashes. Therefore, try
$pattern = '/(?<!\\\\)\[(?:\^\])?(?:[^]\\\\]+|\\\\.)*\]/'


text:
Q: Reloading View on dismissViewController (Modal) I am trying to reload a graph with datapoints after one has been deleted from a tableview. I call the
[self dismissViewControllerAnimated:YES completion:nil];

to get the modal off of the page, but then the viewWillAppear method of the root viewcontroller does not get called.
Any thoughts?

A: You don't have to pass nil to the completion: argument.  You can instead pass it a block of code to execute.
[self dismissViewControllerAnimated:YES completion:^{
        // code to execute upon completion
    }];

As a note, you really shouldn't be calling viewWillAppear:.  Instead, you should put your logic for reloading your graph in its own method.  In viewWillAppear:, call that method, and then in the completion block, also call that method.  We shouldn't need to re-execute EVERYTHING in viewWillAppear:, as most of your view controller's view is already set up (it wasn't deallocated).  All we need to do is reload one part of the screen.

A: Try putting your code to refresh the graph in the viewDidAppear method.


text:
Q: Dynamic Link Library function export First the main.h file -
main.h
#ifndef __MAIN_H__
#define __MAIN_H__

#include <iostream>

#ifndef _BUILD_DLL
#define XXX_API __declspec(dllexport)
#else
#define XXX_API __declspec(dllimport)
#endif

#include "device.h"

// Core functions
namespace xxx
{
    XXX_API void createDevice(int w, int h);
}

#endif // __MAIN_H__

main.cpp
#define _BUILD_DLL

namespace xxx
{

XXX_API void createDevice(int w, int h)
{
    Device dev;
    dev.createDevice(w, h);
}

}

device.h
#ifndef __DEVICE_H__
#define __DEVICE_H__

namespace xxx
{

class Device
{
public:
    Device();
    virtual ~Device();

    XXX_API void createDevice(int width, int height);

}; // end of class

} // end of namespace

#endif

device.cpp
#include "main.h"

namespace xxx
{

   Device::Device()
   {
   }

   Device::~Device()
   {
   }

   XXX_API void Device::createDevice(int width, int height)
   {
    std::cout << "Width: " << width << std::endl;
    std::cout << "height: " << height << std::endl;
   }

} // end of namespace

This are the files that create the dll and library.
And here is the test.cpp that creates the application which calls that lib functions-
#include "main.h"

int main()
{
    xxx::createDevice(800, 600);

    std::cout << "Press the ENTER key to exit.";
    std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);

    return 0;
}

As you can see I am calling createDevice(int, int) to create the device. What I want to know is how do I export the dll calls so that I can get a pointer to that device to call its member function from test.cpp. like this -
#include "main.h"

int main()
{
    xxx::Device* dev = createDevice(800, 600);

    std::cout << "Press the ENTER key to exit.";
    std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);

    return 0;
}

Thanks in advance

A: Change createDevice to this
XXX_API Device* createDevice(int w, int h)
{
    Device* dev = new Device();
    dev->createDevice(w, h);
    return dev;
}

Presumably you should to add a destroyDevice function to free the memory.