text:
Q: VS2008 c++/cli project adds unnecessary office.dll to output folder I have created a project (that behaves differently on 2 different computers, although all files are the same.
The project compiles to a managed DLL.  It is part of a solution (let's say 'solution A') that has 4 projects. This project references another project of solution A and various managed DLLs of another solution B.
On computer 1, where I did the development, it compiles as expected and it's working fine.
On computer 2, where I am mainly using the files, it compiles and it's working fine, too. But during compilation, there are 2 files added to the output folder although they are not referenced anywhere:
1>Kopieren von "c:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Office.dll" in das Zielverzeichnis...
1>Kopieren von "c:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Outlook.dll" in das Zielverzeichnis...

I am not using those files nor referencing them or functions of them at any place in my code. Why are they copied?
It doesn't hurt though, but I would like to know if there's something going wrong.

A: The 2nd comment of Hans Passant to the original post is the answer.
On computer 1, both files were registered in the GAC.
On computer 2, they weren't, so they were copied to the output folder instead.
Now I gotta find out why they are needed at all...


text:
Q: Broke Python Whilst Trying to Upgrade 3.8 to 3.9 Here is what happened; I tried to upgrade python3.8 to 3.9; my goal was to Install python3.9 and then force my system to start using 3.9 instead of the current 3.8.
Then I found thsHow to Upgrade to Python3.9
Ignorantly without reading the comments, I jumped into my terminal and started executing the install and update-alternatives commands; at the end of the article; I discovered that I wrote a small python program and discovered that I could not run it.
That was when I decided to go through the comments, and discovered that some dependencies were missing; having tried to install dist-utils for 3.9; my system did not allow any install, kept saying it's available or something so I ignored and decided to quickly go back to my 3.8 having read some articles here warning against messing with default python installations.
Initially, my fear was that I have broken the default python installation; even though I never attempted removing it, so I decided to switch back to the old 3.8 I had working well.
I did was simply following the same article which gave room for switching between the python versions and switched back to 3.8; now it appears I'm fine.
My question is how to setup the installed 3.9 so that I can have it function properly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ionic adding android.permission.GET_ACCOUNTS permission in app I am having <uses-permission android:name="android.permission.GET_ACCOUNTS" /> in manifest but I don't need, also as android uses groups of permissions instead of single permission when asking the user to grant them which is in Contacts group. More info about it. this is all I found out after search.
I want to remove this permission because this is the reason why I see contact permission in the app info screen.
I am having only this in my config.xml
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="19" />
    <preference name="android-targetSdkVersion" value="28" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <preference name="loadUrlTimeoutValue" value="300000" />
    <preference name="KeyboardDisplayRequiresUserAction" value="false" />
    <preference name="orientation" value="portrait" />
    <preference name="WKPort" value="8080" />

and in package.json has these plugins listed (does any of plugin automatically generate certain permission requirements?)
"cordova": {
    "plugins": {
      "cordova-plugin-globalization": {},
      "cordova-plugin-google-analytics": {
        "GMS_VERSION": "11.0.1"
      },
      "cordova-plugin-app-version": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "To locate you"
      },
      "cordova-plugin-statusbar": {},
      "cordova-plugin-file-transfer": {},
      "cordova-plugin-telerik-imagepicker": {
        "PHOTO_LIBRARY_USAGE_DESCRIPTION": "your usage message"
      },
      "cordova-plugin-advanced-http": {},
      "cordova-plugin-filepath": {},
      "cordova-plugin-file": {},
      "cordova-plugin-android-permissions": {},
      "cordova-plugin-filechooser": {},
      "cordova-plugin-filepicker": {},
      "cordova-sqlite-storage": {},
      "cordova-plugin-ionic-keyboard": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+"
      },
      "cordova-plugin-inappbrowser": {},
      "cordova-plugin-facebook4": {
        "APP_ID": "845225319173258",
        "APP_NAME": "Fixi",
        "FACEBOOK_HYBRID_APP_EVENTS": "false",
        "FACEBOOK_ANDROID_SDK_VERSION": "4.40.0"
      },
      "cordova-plugin-ms-azure-mobile-apps": {},
      "phonegap-plugin-push": {},
      "cordova-plugin-request-location-accuracy": {},
      "cordova-plugin-camera": {},
      "cordova.plugins.diagnostic": {},
      "cordova-plugin-screen-orientation": {},
      "cordova-plugin-googleplus": {
        "REVERSED_CLIENT_ID": "com.googleusercontent.apps.210603718696-n7l7im3akied7en16i7uueajrdlfen1h"
      }
    }

can anyone please help me out with this? Thanks in advance. :)


text:
Q: Get the index of the nth occurrence of an element in a Rust Vector I would like a function to get the index of the nth occurrence of an element. It would have a function signature like so:
fn get_index(vec, occurence, value)
For example, to get the index of the second occurence of the element 1 in a given vector:
let v: Vec<u8> = vec![3, 2, 1, 4, 2, 1];

assert_eq!(get_index(v, 2, 1), 5)

A: Your function might look something like:
fn get_index(v: Vec<u8>, occurrence: usize, value: u8) -> Option<usize> {
    v.iter()
        .enumerate()
        .filter(|(_, &v)| v == value)
        .map(|(i, _)| i)
        .nth(occurrence - 1)
}

Explaining this process:

*

*We take an iterator of our Vector v.

*We enumerate this iterator, transforming it into [(0, 3), (1, 2), (2, 1), ...]. This way, we can preserve the index of the item after filtering.

*We filter our enumeration based on whether the value (the right hand item in the tuple) is equal to the element we're looking for.

*We map and remove the value part as it is no longer relevant (but keeping the index) .

*We take the occurrencenth item, which is an Option that may contain the index (because it may not exist).

#[test]
fn given() {
    assert_eq!(get_index(vec![3, 2, 1, 4, 2, 1], 2, 1), Some(5));
}

Note that the function should return an Option (https://doc.rust-lang.org/std/option/), because we can't be certain that v will contain as many occurrences of the value as you have specified.


text:
Q: Retrieve CustomObject Definition without its Declarative information With the help of Metadata API we can fetch CustomObject definition easily. But somehow we need only CustomObject details not its custom fields, ListView etc.
I looked in available metadata type but unable to find anything which can help in achieving this.
Is there any method by which we can retrieve CustomObject details only. We only want to deploy custom object not its fields, Web links etc.
Any help will be appreciated.

A: According to the documentation, you can include specific fields you want to retrieve but it does not appear that you can exclude fields from being retrieved with the custom object.
However, an easy way to accomplish this, and to me even easier than trying to tinker with the api calls. Is to do some xml parsing in the language of your choice, and just pull the custom field nodes out of each of the custom object definitions.
Using that method, you can sidestep dealing with the api and just deal directly with the files, and even if the api changes, you know that your script will still remove fields.
--KC


text:
Q: MongoDB read documents within transaction Suppose I do the following list of operations in MongoDB

*

*Start a session

*Start a transaction for that session

*run an insert command with a new document

*run a find command on the collection of the inserted document

*Commit the transaction

*End the session

I understand that outside of the transaction the insert done in the third step will not be visible until the transaction is committed, but what about within the transaction, will the find run in the fourth step see this new document or will it not?

A: Yes, a transactional find sees a document inserted in a previous transactional insert. You could assume the Read your own writes property.

Every time a transaction is started a new snapshot is created. Outside the transaction, the snapshot is obviously invisible: this is accomplished by using (and abusing if your transaction involves many updates) the WiredTiger cache. This cache is structured as a tree, similar to the following one1:

where each transactional operation is represented as a new update block that could in turn be chained to another update block.
Outside operations only see non-transactional tree entries, while transactional operations see all the entries added before the snapshot is taken + the update blocks for the given transaction.
I am aware that it is a very brief explanation on how MongoDB manages transaction atomicity, but if you are interested in understanding more on this, then I suggest you to read a report I have written. in the same repository you can find some scenarios for the most typical doubts.

1: image taken from Aly Cabral's presentation about How and when to use Multi-document transactions


text:
Q: Why does Messaging.renderEmailTemplate() return a "Field Custom_Field__c does not exist" even when the field does exists? When running the code below anonymously I get a (paraphrased) error:

"Field Custom_Field__c does not exist"

Code:
Id bankId = 'a1e630000000oOG';
Id contactId = '00363000009GnPE';

//verify field exists
Submission__c sub = [SELECT Id, Bank__c FROM Submission__c WHERE Id=:bankId];

//verify record exists and bank field is populated
System.assert(String.valueOf(sub.Bank__c).length()>0);

//verify record exists
System.assert([Select id from contact WHERE id=:contactId].size()==1);

String unrendered = 'Dear {!Bank__c},\n Hope you\'re doing well!';

List<Messaging.RenderEmailTemplateBodyResult> renderResults = Messaging.renderEmailTemplate(contactId, bankId, new List<String>{unrendered});

System.debug(renderResults);

I've made sure the whatId record exists, the field being merged is populated, and the whoId record exists (as can be seen from the assert statements).
But I get an error:

getFieldName=Bank__c;
getMessage=Field Bank__c does not exist. Check spelling.;
getOffset=7;
getStatusCode=EMAIL_TEMPLATE_MERGEFIELD_ERROR;

Here's the full user debug:
13:32:16:146 USER_DEBUG [17]|DEBUG|(Messaging.RenderEmailTemplateBodyResult[getErrors=(Messaging.RenderEmailTemplateError[getFieldName=Bank__c;getMessage=Field Bank__c does not exist. Check spelling.;getOffset=7;getStatusCode=EMAIL_TEMPLATE_MERGEFIELD_ERROR;]);getMergedBody=null;getSuccess=false;])

As seen in the debug log the attribute getMergedBody is null. I'm trying to merge text on the fly so users can send emails with their choice of fields to merge. Why am I getting this error? What does it actually mean since the field does indeed exist?
Thank you!
Edit:
The field is accessible to the running user as checked on the FLS level.
Edit 2:
This question has already been answered. To reproduce the issue in any org use this code:
Opportunity opp = [SELECT Id, StageName FROM Opportunity LIMIT 1];
Contact con = [Select id from contact LIMIT 1];

Id oppId = opp.Id;

Id contactId = con.Id;

//verify record exists and bank field is populated
System.assert(String.valueOf(opp.StageName).length()>0);

//as per the answer, {!StageName} needs to be changed to {!Opportunity.StageName}
String unrendered = 'Dear {!StageName},\n Hope you\'re doing well!';
List<Messaging.RenderEmailTemplateBodyResult> renderResults = Messaging.renderEmailTemplate(contactId, oppId, new List<String>{unrendered});
System.debug(renderResults);

A: I think I found the issue, based on your assert I assume you are trying to get the bank__c info related to Submission__c in the unrendered string. Change 'Dear {!Bank__c}...' to 'Dear {!Submission__c.bank__c}...'


text:
Q: UIScrollView - tell the difference between setContentOffset and manual scrolling I have a scrollview, which automatically advances every 3 seconds to the next "page" (page control also used). However, once the user touches the scrollview, I want to stop the auto-advancing.
I have subclassed the scrollview. I can detect touchesBegan in the subclass, but touchesMoved is not called, so I can't tell if the user has manually swiped the scrollview. I can't use scrollviewDidScroll, because that gets called when I set the contentOffset when the auto-advance timer fires.
So what are my other options for detecting touches? Why isn't touchesMoved called on the scrollview subclass?

A: Thank you for the suggestions. They helped me stumble upon this easy solution:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.scrollTimer invalidate];
}

A: You may want to look into the following delegate method:
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView

Per Apple:

The scroll view calls this method at the end of its implementations of the UIScrollView and setContentOffset:animated: and scrollRectToVisible:animated: methods, but only if animations are requested.

So that delegate method is only called when programatic scrolling occurs.  You could set up your autoscroll call in that method, only calling it if some BOOL is false.  Setting that BOOL to true in your touch event.
Or something completely different =]
It is a useful delegate method though.
~ Good luck

A: The scrollview probably nominates a subview to receive touch input — UIKit objects are very fussy about this sort of thing and generally can't even handle forwarded events.
What you probably want to do is to key-value observe either tracking or dragging (and it sounds like you want the latter). If the relevant property changes to true then you know the user has initiated scrolling.


text:
Q: Proving the distance of a code is at least 3 I have an exercise that says, "Let $A$ be a matrix, and let $C$ be the code consisting of all solutions to $Ax = 0$. If $A$ has neither a column of zeros nor two equal columns, prove that the distance of $C$ is at least $3$. (Hint: If $v$ has weight $1$ or weight $2$, look at how $Av$ can be written in terms of the columns  of $A$.)"

Finston, David R.. Abstract Algebra (Springer Undergraduate Texts in Mathematics and Technology) (p. 27). Springer International Publishing. Kindle Edition.

This is under a topic of binary code, so everything is in regards to Z2
I have no idea how to start it or what I am trying to get to. I'm also terrible at proving things. Any ideas?

A: The minimum distance of any code $C \subseteq \Bbb Z_2^n$ is $$\min \{d_H(u,v): u,v \in C , u \neq v\}$$ but because the code $C$ is a linear subspace we can also see it as
$$\min \{\|v\|_H: v \in C, v \neq 0\}$$
where $\|v\|= d_H(v,0)$ the number of $1$'s in the codeword: if $u$, $v$ realise the minimum, $u-v$ realises the minimal norm and is also in $C$ (of course in this field $u-v=u+v$ anyway) and the converse is true because $0 \in C$.
And a vector $(c_1,c_2,\ldots,c_n)$ is in $C$, the null space of $A$ iff $\sum_{i \in J} A_i = 0$ where $A_i$ is the $i$-th column of $A$, and $J=\{i: c_i=1\}$.
This is just by how matrix multiplication over $\Bbb Z_2$ works.
So if we have a vector of minimal Hamming-norm $d$, it has exactly $d$ ones, and so there are $d$ many columns of $A$ that sum to $0$. And if we have $d$ many columns that sum to $0$, the corresponding vector that has $1$ at those indices and $0$ elsewhere lies in the null space of $A$ and so in $C$ and the minimum distance (norm) is $\le d$. These observations establish you claim: if the minimum dustance is $3$ all columns are non-zero and no pair of them can sum to $0$, e.g. be equal, and conversely.


text:
Q: returning an 'arrow key' from a function back to main() So I want a function to return the char representing an arrow key to use it further in the main, and here's my try:
#include <conio.h>
#include <iostream>
using namespace std;

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77

char func()
{
    char c;
        c=_getch();
        switch((c=_getch())) {
        case KEY_UP:
            return c;
        case KEY_DOWN:
            return c;
        case KEY_LEFT:
            return c;
        case KEY_RIGHT:
            return c;
        default:
            break;
        }
        return 0;
}
int main()
{
    cout<<func();
}

But it doesn't work , it just prints the character with the 'actual' ASCII value (like 'M' if I pressed the right arrow key) , So i want to know how to solve this problem . Also why is it that the same ASCII value is used for a character as well as the arrow key? What does it mean?
Another question is that modern IDE's don't use getch() or _getch() functions , so what is the alternate of that?


text:
Q: generate unique string of length n without prefilled dictionary I have an application that is kind of like a URL shortener and need to generate unique URL whenever a user requests.
For this I need a function to map an index/number to a unique string of length n with two requirements:

*

*Two different numbers can not generate same string.
In other words as long as i,j<K: f(i) != f(j).   K is the number of possible strings = 26^n.  (26 is number of characters in English)

*Two strings generated by number i and i+1 don't look similar most of the times. For example they are not abcdef1 and abcdef2. (So that users can not predict the pattern and the next IDs)

This is my current code in Python:
chars = "abcdefghijklmnopqrstuvwxyz"

for item in itertools.product(chars, repeat=n):
    print("".join(item))

# For n = 7 generates:
# aaaaaaa
# aaaaaab
# aaaaaac
# ...

The problem with this code is there is no index that I can use to generate unique strings on demand by tracking that index. For example generate 1 million unique strings today and 2 million tomorrow without looping through or collision with the first 1 million.
The other problem with this code is that the strings that are created after each other look very similar and I need them to look random.
One option is to populate a table/dictionary with millions of strings, shuffle them and keep track of index to that table but it takes a lot of memory.
An option is also to check the database of existing IDs after generating a random string to make sure it doesn't exist but the problem is as I get closer to the K (26^n) the chance of collision increases and it wouldn't be efficient to make a lot of check_if_exist queries against the database.
Also if n was long enough I could use UUID with small chance of collision but in my case n is 7.

A: I'm going to outline a solution for you that is going to resist casual inspection even by a knowledgeable person, though it probably IS NOT cryptographically secure.
First, your strings and numbers are in a one-to-one map.  Here is some simple code for that.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
len_of_codes = 7
char_to_pos = {}
for i in range(len(alphabet)):
    char_to_pos[alphabet[i]] = i

def number_to_string(n):
    chars = []
    for _ in range(len_of_codes):
        chars.append(alphabet[n % len(alphabet)])
        n = n // len(alphabet)
    return "".join(reversed(chars))

def string_to_number(s):
    n = 0
    for c in s:
        n = len(alphabet) * n + char_to_pos[c]
    return n

So now your problem is how to take an ascending stream of numbers and get an apparently random stream of numbers out of it instead.  (Because you know how to turn those into strings.)  Well, there are lots of tricks for primes, so let's find a decent sized prime that fits in the range that you want.
def is_prime (n):
    for i in range(2, n):
        if 0 == n%i:
            return False
        elif n < i*i:
            return True
    if n == 2:
        return True
    else:
        return False

def last_prime_before (n):
    for m in range(n-1, 1, -1):
        if is_prime(m):
            return m

print(last_prime_before(len(alphabet)**len_of_codes)

With this we find that we can use the prime 8031810103.  That's how many numbers we'll be able to handle.
Now there is an easy way to scramble them.  Which is to use the fact that multiplication modulo a prime scrambles the numbers in the range 1..(p-1).
def scramble1 (p, k, n):
    return (n*k) % p

Picking a random number to scramble by, int(random.random() * 26**7) happened to give me 3661807866, we get a sequence we can calculate with:
for i in range(1, 5):
    print(number_to_string(scramble1(8031810103, 3661807866, i)))

Which gives us
lwfdjoc
xskgtce
jopkctb
vkunmhd

This looks random to casual inspection.  But will be reversible for any knowledgeable someone who puts modest effort in.  They just have to guess the prime and algorithm that we used, look at 2 consecutive values to get the hidden parameter, then look at a couple of more to verify it.
Before addressing that, let's figure out how to take a string and get the number back.  Thanks to Fermat's little theorem we know for p prime and 1 <= k < p that (k * k^(p-2)) % p == 1.
def n_pow_m_mod_k (n, m, k):
    answer = 1
    while 0 < m:
        if 1 == m % 2:
            answer = (answer * n) % k
        m = m // 2
        n = (n * n) % k
    return answer

print(n_pow_m_mod_k(3661807866, 8031810103-2, 8031810103))

This gives us 3319920713.  Armed with that we can calculate scramble1(8031810103, 3319920713, string_to_number("vkunmhd")) to find out that vkunmhd came from 4.
Now let's make it harder.  Let's generate several keys to be scrambling with:
import random
p = 26**7
for i in range(5):
    p = last_prime_before(p)
    print((p, int(random.random() * p)))

When I ran this I happened to get:
(8031810103, 3661807866)
(8031810097, 3163265427)
(8031810091, 7069619503)
(8031809963, 6528177934)
(8031809917, 991731572)

Now let's scramble through several layers, working from smallest prime to largest (this requires reversing the sequence):
def encode (n):
    for p, k in [
            (8031809917, 991731572)
          , (8031809963, 6528177934)
          , (8031810091, 7069619503)
          , (8031810097, 3163265427)
          , (8031810103, 3661807866)
        ]:
        n = scramble1(p, k, n)
    return number_to_string(n)

This will give a sequence:
ehidzxf
shsifyl
gicmmcm
ofaroeg

And to reverse it just use the same trick that reversed the first scramble (reversing the primes so I am unscrambling in the order that I started with):
def decode (s):
    n = string_to_number(s)
    for p, k in [
            (8031810103, 3319920713)
          , (8031810097, 4707272543)
          , (8031810091, 5077139687)
          , (8031809963, 192273749)
          , (8031809917, 5986071506)
        ]:
        n = scramble1(p, k, n)

    return n

TO BE CLEAR I do NOT promise that this is cryptographically secure.  I'm not a cryptographer, and I'm aware enough of my limitations that I know not to trust it.
But I do promise that you'll have a sequence of over 8 billion strings that you are able to encode/decode with no obvious patterns.
Now take this code, scramble the alphabet, regenerate the magic numbers that I used, and choose a different number of layers to go through.  I promise you that I personally have absolutely no idea how someone would even approach the problem of figuring out the algorithm.  (But then again I'm not a cryptographer.  Maybe they have some techniques to try.  I sure don't.)

A: How about :
from random import Random

n = 7

def f(i):
    myrandom = Random()
    myrandom.seed(i)
    alphabet = "123456789"
    return "".join([myrandom.choice(alphabet) for _ in range(7)])

# same entry, same output
assert f(0) == "7715987"
assert f(0) == "7715987"
assert f(0) == "7715987"

# different entry, different output
assert f(1) == "3252888"

(change the alphabet to match your need)
This "emulate" a UUID, since you said you could accept a small chance of collision. If you want to avoid collision, what you really need is a perfect hash function (https://en.wikipedia.org/wiki/Perfect_hash_function).

A: you can try something based on the sha1 hash
#!/usr/bin/python3

import hashlib

def generate_link(i):
    n = 7
    a = "abcdefghijklmnopqrstuvwxyz01234567890"
    return "".join(a[x%36] for x in hashlib.sha1(str(i).encode('ascii')).digest()[-n:])

A: This is a really simple example of what I outlined in this comment. It just offsets the number based on i. If you want "different" strings, don't use this, because if num is 0, then you will get abcdefg (with n = 7).
alphabet = "abcdefghijklmnopqrstuvwxyz"

# num is the num to convert, i is the "offset"
def num_to_char(num, i):
    return alphabet[(num + i) % 26]

# generate the link
def generate_link(num, n):
    return "".join([num_to_char(num, i) for i in range(n)])

generate_link(0, 7) # "abcdefg"
generate_link(0, 7) # still "abcdefg"
generate_link(0, 7) # again, "abcdefg"!

generate_link(1, 7) # now it's "bcdefgh"!

You would just need to change the num + i to some complicated and obscure math equation.


text:
Q: Git: What's the path separator used in the content of the .git\HEAD in Git repositories on Windows? The title says it all, but for example, if the HEAD of a Git repository points to ref/heads/master on any well-used Git implementation for Windows, which of the following is the content of the file .git/HEAD ... oops, .git\HEAD:

*

*ref: refs/heads/master, or

*ref: refs\heads\master ?

Either way, I need to calculate the absolute path <git project>\.git\refs\heads\master, but I don't have Windows environment and I can't get to know which form is used! Answer is greatly appreciated.
Background: I'm modifying a Haskell library implementing a macro that embeds the Git revision hashes of Haskell projects into their source codes right on compilation (very nice for implementing --version option!). When we compile the program invocating that macro, git is called; however even before that, when a build tool is checking whether recompilation is required, we cannot call git and all that's done is simple file update check! Therefore, at the time of each compilation, we must compute and save the path of reference file at which HEAD is pointing, so that the reference file would be checked for update next time. The problem is that I would like to make the library cross-platform but that I don't know how to compute the path of a reference file on Windows, for I don't know the original form.

A: HEAD uses a reference name and not a path separator.  Git always uses forward slashes in reference names, even on Windows.  Backslashes are never allowed in a reference name on any platform, ever.
Since Windows will also allow forward slash path separators (unless you're using UNC paths), it's usually safe to just use forward slashes everywhere unless you know you have special needs.


text:
Q: Add an object to a var div element So I am creating a "GoogleMap component" within a Single Page Application.
I have been given some patterns to follow that are inspired by an AS2 expert. He wants to have instances of GoogleMaps available to the SPA. Some of the goals of the pattern are, of course, encapsulation and reusability.
The pattern goes as follows:
GoogleMap = { instances: [] }; //static instance,wrapper class

GoogleMap.get = function () {
    var mapCanvas = document.createElement('div');

    if (this.instances.length > 0) {
        return this.instances.pop();
    }
    var map = new google.maps.Map(mapCanvas, mapOptions); //mapOptions are defined don't worry
     return mapCanvas;
}

GoogleMap.destroy = function (googleMap) {
    this.instances.push(googleMap);
}

Then in my HTML:
<script type="text/javascript">
    function start() {
        var mapDiv = GoogleMap.get();
        document.body.appendChild(mapDiv);
        //here lies my issue
        //mapDiv.setMapCenter({ lat: 90, long: 90 });
    }
    window.onload = start;
</script>

I want to be able to add an object to mapDiv which is only a html element right now.
I thought all vars in Javascript inherit from Object except null and undefined. So I thought I could do, in GoogleMap.get:
var mapCanvas = document.createElement('div');
mapCanvas.prototype.setMapCenter = function(lat,long){ //error no prototype!

    var location = new google.maps.LatLng(lat,long);
            this.instance.setCenter(location);

    return mapCanvas, which has a method that the caller can use to set lat and long, awesome! If only it worked the way my mind it thinking it would
}

But there is no prototype for the var mapCanvas which is just a <div>


text:
Q: Causality and Quantum Field Theory I have a problem with proof of causality in Peskin & Schroeder, An Introduction to QFT, page 28. To avoid confusion I use three vectors notation, rewriting the Eq. (2.53) for $y=0$ as follows:
$[\phi(x,t),\phi(0,0)]=\int \frac{d^3p}{(2\pi)^3}\frac{1}{2\sqrt{p^2+m^2}}\left(e^{-i\mathrm{p}.\mathrm{x}-it\sqrt{p^2+m^2}}-e^{i\mathrm{p}.\mathrm{x}+it\sqrt{p^2+m^2}}\right)$
The book goes on about how the integrand being Lorentz invariant makes this integral zero for the x out of the light cone. But I (not being a special relativity expert) want to see it more rigorously:
after changing variables $p\to-p$ in the first term, the equation simplifies to:
$[\phi(x,t),\phi(0,0)]=\int \frac{d^3p}{(2\pi)^3}\frac{-2i}{2\sqrt{p^2+m^2}}e^{i\mathrm{p}.\mathrm{x}}\sin\left(t\sqrt{p^2+m^2}\right)$
using spherical coordinates:
$[\phi(x,t),\phi(0,0)]=\int \frac{dpd\phi d\theta p^2\sin\theta}{(2\pi)^3}\frac{-i}{\sqrt{p^2+m^2}}e^{ipx\cos\theta}\sin\left(t\sqrt{p^2+m^2}\right)\\
[\phi(x,t),\phi(0,0)]=\int_0^{\infty}\frac{dpp}{(2\pi)^2}\frac{-2i}{x\sqrt{p^2+m^2}}\sin (px)\sin\left(t\sqrt{p^2+m^2}\right)$
again after another change of variables $u=\sqrt{p^2+m^2}$,
$[\phi(x,t),\phi(0,0)]=\frac{-2i}{x}\int_m^{\infty}\frac{du}{(2\pi)^2}\sin (x\sqrt{u^2-m^2})\sin\left(tu\right)$
I cannot see how this integral should be zero for $x>t$ !!! Can somebody please explain this to me?

A: I'll address your point about why the integral is Lorentz invariant, as from the comments to cduston's answer, I think this is your sticking point:
You can see the relation between a manifestly Lorentz invariant form like this $$\int d^4p \frac{e^{-ipx}}{(p^2-m^2)} \ \ \ (1) $$ and the not-so-obviously Lorentz invariant form $$ \int d^3p \frac{1}{E_{{\bf{p}}}}{e^{-ipx}} \ \ \ (2)$$ by using the identity $$\frac{1}{(p^2-m^2)}= \frac{1}{2E_{{\bf{p}}}}\{\frac{1}{(E_{{\bf{p}}}+p_0)}-\frac{1}{(E_{{\bf{p}}}-p_0)}\} $$  Here $E_{{\bf{p}}} = \sqrt{{\bf{p}}^2+m^2}$ is the on-shell time component of the momentum four vector, and $p_0$ is the "generic" time component - not necessarily on-shell.
If you substitute this in (1) and do the $p_0$ integral using the appropriate contour, you'll get (2).
What's actually going on is explained in the discussion near equation (2.40), you're doing a 4 momentum integral, but just restricting it to the mass shell using a delta function.  Restriction to a mass shell is a Lorentz invariant operation, so you're maintaining Lorentz invariance throughout (even though with the three momentum integral it doesn't look like it!).

A: In the text he says the two terms vanish under $(x-y)\rightarrow -(x-y)$. In other words, there is a Lorentz transformation which takes $(x-y)\rightarrow -(x-y)$ in the second term when the separation is spacelike ($(x-y)^2<0$ using the wrong sign...). Do that, and the commutator vanishes.


text:
Q: Localizing django datepicker I am using a jQuery UI datepicker with django. I managed to make the datepicker accept format of dd-mm-yyyy, but I'm not able to make the model accept it's data.
Any easy way to solve this?


text:
Q: Get text value of selected option in Jquery I have some custom Jquery which grabs the id's from a select list, and populates a secondary select list with those that are selected.
I have this working well, however I need the secondary select list needs to display the text value of the selected option.  Currently I just get the actual id.
Can anybody assist please?
JQUERY
$('#myselect').change(function() {
        var row = $(".chosen-select").val();
        $('#secondSelect').html('');
        jQuery.each(row, function(i, val) {
            $('#secondSelect').append('<option value=' + val + '>' + val) + '</option>';
        });
});

HTML
First select list
<select data-placeholder="Choose cars..." class="chosen-select" name="myselect[]" id="myselect" multiple>
<option value="1">Vauxhall</option>
<option value="2">Volvo</option>
etc...
</select>

Second select list
<select name="secondSelect" id="secondSelect">
    <option value="">Select Model</option>
    should be populated here..
</select>

A: What about this? fiddle
$('#myselect').change(function() {
        $('#secondSelect').html('');
        jQuery.each($("option:selected",this), function(i, val) {
            $('#secondSelect').append($(val).clone());
        });
});


text:
Q: Converting text file to all uppercase letters I have an assignment for class and I have to make a program that takes an existing file and converts all the letters to uppercase. Below is part of the code (specifically the loop):
 // Read lines from the file until no more are left.
  while (inputFile.hasNext())
  {
      // Read the next name.
     String friendName = inputFile.nextLine();

      // Need line to make all letters uppercase

  }

  System.out.print("Enter the saved file name: ");
  String filename2 = keyboard.nextLine();

When I run it now: I am able to open the first text file and a second txt file is created, but there is no letters in the new file.

A: You may try like this:
File file1 = new File("initial.txt");
File file2 = new File("final.txt");
char CharCounter = 0;
BufferedReader in = (new BufferedReader(newFileReader(file1)));
PrintWriter out = (new PrintWriter(new FileWriter(file2)));
int ch;
while ((ch = in.read()) != -1)
{
   if (Character.isLowerCase(ch))
   {
        ch=Character.toUpperCase(ch);// convert assign variable
   }
out.write(ch);
}
in.close();
out.close();

A: Try String upper = friendName.toUpperCase().
Now the upper String has all the character in the uppercase.Use it according to your need. Refer String API

A: Look at the String class documentation and try to find a method to change the string value to all uppercase.
Also you need to get the output file name above the while loop and then write to the output file inside the loop since for every iteration of the loop, the string value of the previous iteration is lost.

A: Use FileUtils readFileToString() and writeFileToString() to do the work simple,
String content = FileUtils.readFileToString(new File(FILE_PATH));
FileUtils.writeStringToFile(new File(FILE_PATH), content.toUpperCase());

A: friendName = friendName +System.lineSeparator()+friendName.toUpperCase();

//After the while loop finishes, write the contents of friendName in your output file.

A: Try This Demo Code:
       import java.io.*;
       import java.util.*;
       class m{

  public static void main (String[] args) {
     try
    {
     FileReader fr = new FileReader("file.java");
     BufferedReader br = new BufferedReader(fr);
     PrintWriter out = (new PrintWriter(new FileWriter("mahesh.java")));
     String s="";
   while((s = br.readLine()) != null)
   {
      out.write(s.toUpperCase()+"\n");
    }
  out.close();
  }
    catch(Exception e)
    {
     e.printStackTrace();
    }
   }

  }

A: package WT_LAB_THIRTEEN;
import java.io.*;

public class StringsToUpperCase {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(
                new FileReader(new File("C:\\Users\\Web Tech\\WT_LAB_THIRTEEN\\InputFile.txt")));
        PrintWriter pw = new PrintWriter(
                new FileWriter(new File("C:\\Users\\Web Tech\\WT_LAB_THIRTEEN\\OutputFile.txt")));
        int ch;
        while ((ch = br.read()) != -1) {
            if (Character.isLowerCase(ch)) {
                ch = Character.toUpperCase(ch);
            }
            /*the below part of the code can be used to convert UpperCase characters to lowerCase
            else if (Character.isUpperCase(ch)) {
                ch = Character.toLowerCase(ch);
            }*/
            pw.write(ch);
        }
        br.close();
        pw.close();
    }
}


text:
Q: Shrink UIButton When Highlighted I have a button which is built in with my own custom image.  I want to give feedback to the user that it has been clicked by shrinking it when it's highlighted.  As of now, I'm thinking of making a smaller scale of the  image to replace the original when the button is highlighted.  But I'm wondering if there's another solution to shrink the size of the button image?

A: Is it the image on the button?  If it is a sepperate image that u want to shrink when the button is pressed then u could do this
If the image is the button then it is impossible to do this without just changing images. or putting the image behind the button.
do this if u are going to put the image in the background
-(IBAction)Shrink:(id)sender{
     Image.frame = MakeCCGRectMake(position x, position y, size x, size y);

}

and change the sent events from touch up inside to touch down


text:
Q: Научить телеграм бота загружать документы на комп Доброго всем времени суток.
Я в разработке ботов начинающий, как и в программировании на Python. Столкнулся с проблемой использования библиотеки telepot.
Весь бот на нее завязан, все вроде работает, но функция загрузки файла ботом на компьютер не хочет никак встать. Перепробовал столько вариантов, что стыдно показывать.
Если кто-то реализовал эту функцию у бота, буду благодарен за любую помощь.
Python 3,9 32bit.
Пысы, пользовался и родными мануалами от telepot-a, но что-то так и не разобрался.

A: Можно использовать библиотеку requests
import requests

file_info = bot.get_file(message.document.file_id)
# Я использую библиотеку PyTelegramBotAPI, и там узнать file_id вот так
# в вашем случае вам нужно узнать как в библиотеке вашей узнать и заменить
file = requests.get(
        f'https://api.telegram.org/file/bot{API_TOKEN}/{file_info.file_path}')
open(message.document.file_name, 'wb').write(file.content)


text:
Q: Tinymce 4.0b1 is not loading I am using these lines to load tinymce4.0b1 but its not loaded.whats the problem?

<link rel="stylesheet" type="text/css" href="~/Scripts/tinymce/js/tinymce/skins/lightgray/skin.min.css"/>

And these are my HTML lines.

        <form method="post">
            <textarea name="content" style="width: 100%">salam</textarea>
        </form>

But the textarea doesnt change.

A: Not sure what the issue is here as your code is fine. Double check the paths to your JS and CSS files.
If you've checked that and you're still having issues, copy and paste the code below:

<title>TinyMCE Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

        <form method="post">
            <textarea name="content" style="width: 100%">salam</textarea>
        </form>

A: The scripts files should be loaded after bootstrap files and the media plugin should not be use before purchasing it.


text:
Q: When working with non-normally distributed time series data, how can I determine when metric is significantly (@ 95% CI) lower/higher than historical? I'm working with time series data that looks at a conversion rate day by day. I have the data going back a few years. I'd like to build in some logic/alert/etc. so that I know when the conversion rate for a specific day is meaningfully lower/higher than what we've seen historically. When I say "meaningfully", I'm referring to a 95% tolerance interval.
My data isn't normally distributed (I've run a QQ plot & Shapiro test), and this is where I get stumped.
I'd appreciate any help anyone can provide - my stats knowledge is a bit rusty as of late :)


text:
Q: Parse SEC EDGAR XML Form Data with child nodes using BeautifulSoup I am attempting to scrape individual fund holdings from the SEC's N-PORT-P/A form using beautiful soup and xml. A typical submission, outlined below and [linked here][1], looks like:
<edgarSubmission xmlns="http://www.sec.gov/edgar/nport" xmlns:com="http://www.sec.gov/edgar/common" xmlns:ncom="http://www.sec.gov/edgar/nportcommon" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<headerData>
<submissionType>NPORT-P/A</submissionType>
<isConfidential>false</isConfidential>
<accessionNumber>0001145549-23-004025</accessionNumber>
<filerInfo>
<filer>
<issuerCredentials>
<cik>0001618627</cik>
<ccc>XXXXXXXX</ccc>
</issuerCredentials>
</filer>
<seriesClassInfo>
<seriesId>S000048029</seriesId>
<classId>C000151492</classId>
</seriesClassInfo>
</filerInfo>
</headerData>
    <formData>
        <genInfo>
        ...
        </genInfo>
        <fundInfo>
        ...
        </fundInfo>
        <invstOrSecs>
            <invstOrSec>
                <name>ARROW BIDCO LLC</name>
                <lei>549300YHZN08M0H3O128</lei>
                <title>Arrow Bidco LLC</title>
                <cusip>042728AA3</cusip>
                <identifiers>
                    <isin value="US042728AA35"/>
                </identifiers>
                <balance>115000.000000000000</balance>
                <units>PA</units>
                <curCd>USD</curCd>
                <valUSD>114754.170000000000</valUSD>
                <pctVal>0.3967552449</pctVal>
                <payoffProfile>Long</payoffProfile>
                <assetCat>DBT</assetCat>
                <issuerCat>CORP</issuerCat>
                <invCountry>US</invCountry>
                <isRestrictedSec>N</isRestrictedSec>
                <fairValLevel>2</fairValLevel>
                <debtSec>
                    <maturityDt>2024-03-15</maturityDt>
                    <couponKind>Fixed</couponKind>
                    <annualizedRt>9.500000000000</annualizedRt>
                    <isDefault>N</isDefault>
                    <areIntrstPmntsInArrs>N</areIntrstPmntsInArrs>
                    <isPaidKind>N</isPaidKind>
                </debtSec>
                <securityLending>
                    <isCashCollateral>N</isCashCollateral>
                    <isNonCashCollateral>N</isNonCashCollateral>
                    <isLoanByFund>N</isLoanByFund>
                </securityLending>
            </invstOrSec>

With Arrow Bidco LLC being a bond within the portfolio, with some of its characteristics included within the filing (CUSIP, CIK, balance, maturity date, etc.). I am looking for the best way to iterate through each individual security (investOrSec) and collect the characteristics of each security in a dataframe.
The code I am currently using is:
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup

header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36", "X-Requested-With": "XMLHttpRequest"}

n_port_file = requests.get("https://www.sec.gov/Archives/edgar/data/1618627/000114554923004968/primary_doc.xml", headers=header, verify=False)
n_port_file_xml = n_port_file.content
soup = BeautifulSoup(n_port_file_xml,'xml')

names = soup.find_all('name')
lei = soup.find_all('lei')
title = soup.find_all('title')
cusip = soup.find_all('cusip')
....
maturityDt = soup.find_all('maturityDt')
couponKind = soup.find_all('couponKind')
annualizedRt = soup.find_all('annualizedRt')

Then iterating through each list to create a dataframe based on the values in each row.
fixed_income_data = []
for i in range(0,len(names)):
    rows = [names[i].get_text(),lei[i].get_text(),
        title[i].get_text(),cusip[i].get_text(),
        balance[i].get_text(),units[i].get_text(),
        pctVal[i].get_text(),payoffProfile[i].get_text(),
        assetCat[i].get_text(),issuerCat[i].get_text(),
        invCountry[i].get_text(),couponKind[i].get_text()
        ]
    fixed_income_data.append(rows)

fixed_income_df = pd.DataFrame(equity_data,columns = ['name',
                         'lei',
                         'title',
                         'cusip',
                         'balance',
                         'units',
                         'pctVal',
                         'payoffProfile',
                         'assetCat',
                         'issuerCat',
                         'invCountry'
                         'maturityDt',
                         'couponKind',
                         'annualizedRt'
                         ], dtype = float)

This works fine when all pieces of information are included, but often there is one variable that is not accounted for. A piece of the form might be blank, or an issuer category might not have been filled out incorrectly, leading to an IndexError. This portfolio has 127 securities that I was able to parse, but might be missing an annualized return for a single security, throwing off the ability to neatly create a dataframe.
Additionally, for portfolios that hold both fixed income and equity securities, the equity securities do not return information for the debtSecs child. Is there a way to iterate through this data while simultaneously cleaning it in the easiest way possible? Even adding "NaN" for the debtSec children that equity securities don't reference would be a valid response. Any help would be much appreciated!
[1]: https://www.sec.gov/Archives/edgar/data/1618627/000114554923004968/primary_doc.xml

A: Here is the best way, in my opinion, to handle the problem. Generally speaking, EDGAR filings are notoriously difficult to parse, so the following may or may not work on other filings, even from the same filer.
To make it easier on yourself, since this is an XML file, you should use an xml parser and xpath. Given that you're looking to create a dataframe, the most appropriate tool would be the pandas read_xml() method.
Because the XML is nested, you will need to create two different dataframes and concatenate them (maybe others will have a better idea on how to approach it). And, finally, although read_xml() can read directly from a url, in this case, EDGAR requires using a user-agent, meaning you also need to use the requests library as well.
So, all together:
#import required libraries
import pandas as pd
import requests

url = 'https://www.sec.gov/Archives/edgar/data/1618627/000114554923004968/primary_doc.xml'
#set headers with a user-agent
headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"}
req =  requests.get(url, headers=headers)

#define the columns you want to drop (based on the data in your question)
to_drop = ['identifiers', 'curCd','valUSD','isRestrictedSec','fairValLevel','debtSec','securityLending']

#the filing uses namespaces (too complicated to get into here), so you need to define that as well
namespaces = {"nport": "http://www.sec.gov/edgar/nport"}

#create the first df, for the securities which are debt instruments
invest = pd.read_xml(req.text,xpath="//nport:invstOrSec[.//nport:debtSec]",namespaces=namespaces).drop(to_drop, axis=1)

#crete the 2nd df, for the debt details:
debt = pd.read_xml(req.text,xpath="//nport:debtSec",namespaces=namespaces).iloc[:,0:3]

#finally, concatenate the two into one df:
pd.concat([invest, debt], axis=1)

This should output your 126 debt securities (pardon the formatting):
lei     title   cusip   balance     units   pctVal  payoffProfile   assetCat    issuerCat   invCountry  maturityDt  couponKind  annualizedRt
0   ARROW BIDCO LLC     549300YHZN08M0H3O128    Arrow Bidco LLC     042728AA3   115000.00   PA  0.396755    Long    DBT     CORP    US  2024-03-15  Fixed   9.50000
1   CD&R SMOKEY BUYER INC   NaN     CD&R Smokey Buyer Inc   12510CAA9   165000.00   PA  0.505585    Long    DBT     CORP    US  2025-07-15  Fixed   6.75000

You can then play with the final df, add or drop columns, etc


text:
Q: Characters allowed in php array keys? I have some php array keys that are populated with a lot of weird characters.
Is this allowed? Are there any constraints to what I cannot use?

A: According to the manual:

The key can either be an integer or a string. The value can be of any
  type.
Additionally the following key casts will occur:

*

*Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.

*Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.

*Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.

*Null will be cast to the empty string, i.e. the key null will actually be stored under "".

*Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

The manual again:

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

So in short, any string can be a key.  And a string can contain any binary data (up to 2GB).  Therefore, a key can be any binary data (since a string can be any binary data).
Some random (valid) abuse of array keys:
$w = array(chr(0) => 'null byte?', chr(rand(0, 255)) => 'random byte?');
var_dump($w);

A: PHP array keys can be integers or strings. PHP strings are byte arrays, meaning sequences of bytes. There are no other types of strings and PHP doesn't otherwise impose any special restrictions on array key strings. In other words: as long as it's a string, anything goes.

A: Anything you can stuff into a PHP string can be used as an array key. There's no limit on the characters allowed.
$a = array();

$x = 'long string of random garage';
echo $a[$x]; // this is ok

$x = array();
echo $a[$x]; // not ok

A: The key must be a string or an integer. There are some casts that take place, but I think the manual does a good job of explaining:

The key can either be an integer or a string. The value can be of any
  type.
Additionally the following key casts will occur:

*

*Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other
  hand "08" will not be cast, as it isn't a valid decimal integer.

*Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under
  8.

*Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.

*Null will be cast to the empty string, i.e. the key null will actually be stored under "".

*Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

A: I found this answer looking for more information on a problem I had.  I was using strings with UTF-8 characters in them, which would not work as keys to an array I had.
Something like
$str = "R&D - Solution";
$arr = array( "R&D - Solution" => "Research" );
echo $arr[$str];  // did not work

The (not big or clever) solution for me was to do this..
$str = md5("R&D - Solution");
$arr = array( md5("R&D - Solution") => "Research" );
echo $arr[$str];  // works!

A: If complex keys are causing an "undefined index" error, you may simply have a "trim" problem.
I was going nuts because a complex key was spitting out the "undefined index" error and I thought maybe it was a syntax violation. The array key causing the error was built from a field from a MySQL database query that I was converting into a key and using in a new array. The key looked like this: pl_1DNKoiJKwotCqAycickBVhTy and here's how the code was constructed.
//new array created from database query
$new_array[$dbquery['fieldname']] = {some value};

//key value found in field of second array
$keyval = $array_two['fieldname'];

//this produced the "undefined index" error
echo $new_array[$keyval];

when, in fact, the $keyval and $dbquery['fieldname'] appeared to be a perfect match (visually verified by echoing both to the browser). The mystery was solved by simply using trim in the second statement like this: $keyval = trim($array_two['fieldname']); Once 'trimmed', php no longer complained.
Hoping this saves some others from some frustrating moments...

A: I've personally not had any problems with unusual characters in array keys.  What is and isn't legal isn't well documented, other than to say that the key must be a scalar.  Your best bet is to just try it and see.

A: In addition to all the answers as they are true: You can use PSRs that they are some kind of rules between best programmers for having a nice and standard coding style.

A: In php array you cannot use key : 2.3 or decimal numbers

A: For this peace of code :
$a = (object) ['@km³' => 123];

This :
error_log($a->@km³);

Produce this error :
PHP Parse error: Syntax error, unexpected '@', expecting T_STRING or T_VARIABLE or '{' or '$' on line 1

But this is working :
error_log($a->{"@km³"});

(with {})

A: Encode the php page in ANSI "é" will be able for use (Cinéma wont show up as Cinéma).
In Notepad++ just use the menu Encode=>Convert ANSI and save


text:
Q: how lando reply relates to ackbar statement? Source

Though Admiral Ackbar wants to abandon the attack, Lando convinces him that they must give Han and his party more time on Endor.

how lando reply relates to ackbar statement?
The movie dialog:
Lando: That blast came from the death star! That thing's operational!
Ackbar: All craft prepare to retreat.
Lando: We won't get another chance at this, Admiral.
Ackbar: We have no choice General Calrissian.
        Our cruisers can't repel power of that magnitude.
Lando: Han will have that shield down; we've got to give him more time.

A: Ackbar wants to abandon the attack. He believes that "power of that magnitude" (that is, the power of the blast) is so great that their cruisers cannot repel it.
Lando then says that Han "will have that shield down".
It is not clear to me how "shield" relates to the "blast", and it seems at first like a nonsequitur. But I assume the power that could produce the blast is the same power that could establish the shield, and that therefore the shield was thought to be impenetrable, judging from the power of the blast.  Lando's remark is that Han will have figured out a way to disable the shield. He will "have it (the shield) down".  It won't matter how impenetrable the shield may be if it is not even operational.


text:
Q: Sequential boxes with 3 Random Box Shadow Colors Case:
I use Owl Carousel for the boxes with maximum 10 thumbnails (that will scroll manually across the browser with define width each panel). However, I've searched Google on "how create 3 random colors using jQuery" and seems some of the results are difficult for me to integrate.
Code Fig.1
BoxShadow = function() {
  var hfiColors = ['#00A9E0', '#E82425', '#EFB12A'];
  var colors = hfiColors.slice(0);

  $('.program-gallery .item').each(function(i){
    var i = i + 1;
    var color = Math.floor(Math.random() * colors.length);

    $(this).css('box-shadow', '0 0 0 5px' + colors[color]);
    colors = colors.slice(0,color-1).concat( colors.slice(color+1,colors.length-1) );
  });

  $.each(colors, function(i, v){
    $('.item' + (+i + 1)).html(colors[i]);
  });
}
$(document).ready(BoxShadow);

This is the code i have so far, and it generates random box-shadow to my thumbnails, but some box-shadows to my thumbnails are not displaying correctly. Honest to tell, I am confuse now on the code structure.
Code Fig.2

        Lorem ipsum dolor sit amet, consectetur adipisicing elit consequuntur.

        Suscipit blanditiis quos aspernatur minus optio beatae consectetur quidem accusantium rerum ab sed nisi.

        Culpa consequuntur necessitatibus laboriosam, quas quos odit non unde consequatur fugit rerum incidunt.

What To Achieve:
I would like to create a 3 random box-shadow colors (only) over to each (10 thumbs) of .item class.
Photo Fig.1

A: You can create a variable string containing alphabets from A through F and numbers 0 through 9, use String.prototype.concat() and Array.from() to concatenate random characters from string variable to set box-shadow of elements.

$(function() {
  var base = ['#00A9E0', '#E82425', '#EFB12A'];
  var shadow = "0 0 0 5px ";

  function randomColor() {
    return shadow + base[Math.floor(Math.random() * base.length)]
  }

  $(".item").each(function() {
    $(this).css("boxShadow", randomColor())
  })
})
.item {
  width: 50px;
  height: 50px;
  display: inline-block;
  margin: 8px;
}

1

2

3

4

5

6

7

8

9

10

A:

BoxShadow = function() {
  var hfiColors = ['#00A9E0', '#E82425', '#EFB12A'];
  var colors = hfiColors.slice(0);

  $('.program-gallery .item img').each(function(){
    var colorIndex = Math.floor(Math.random() * colors.length);
    $(this).css('box-shadow', '0 0 0 5px' + colors.splice(colorIndex, 1));
  });
}
$(document).ready(BoxShadow);
.item { width: 30%; display: inline-block; vertical-align:top; }
img { max-width: 100% }

        Lorem ipsum dolor sit amet, consectetur adipisicing elit consequuntur.

        Suscipit blanditiis quos aspernatur minus optio beatae consectetur quidem accusantium rerum ab sed nisi.

        Culpa consequuntur necessitatibus laboriosam, quas quos odit non unde consequatur fugit rerum incidunt.

Update your codes abit. And added some CSS for visuals.
$('.program-gallery .item img').each(function(){
// I targeted each image instead of `.item`

Instead of having to slice and concat your array to remove an item from it, just use splice:
$(this).css('box-shadow', '0 0 0 5px' + colors.splice(colorIndex, 1));


text:
Q: How to find the version of OpenFOAM installed on WSL-Ubuntu? I have installed the OpenFOAM package via
sudo apt install openfoam

on Ubuntu, inside the Windows WSL environment. But I have no idea what version/variant of the FLOSS is installed. I tried the
blockMesh -help

hoping it would give me some information about what I am dealing with but I got the error message:

--> FOAM FATAL ERROR :      Could not find mandatory etc entry (mode=ugo)       'controlDict'

A: You can call the shell function foamVersion (which should be available when you install OpenFOAM):
foamVersion # in my case, the output is: OpenFOAM-v2112

Or simply see the output of the environment variable:
echo $WM_PROJECT_VERSION # in my case, the output is v2112

A: Using the Ubuntu command
apt-cache show openfoam

I understood that I had installed the 1906.191111+dfsg1-2build1 version and the openfoam.com variant. But this is a Ubuntu-specific solution, not a general OpenFOAM solution that works on other operating systems.


text:
Q: Use node-wkhtmltopdf with HTML in memory I am trying to convert HTML into a PDF, but the HTML is generated dynamically and never actually served up.  I've been using node-html-pdf but it has some issues I've found difficult to overcome (known, long-standing bugs).
I thought I'd give wkhtmltopdf (via node-wkhtmltopdf) a try, but it expects a URL.
My current thought (which isn't great) is to expose the HTML via express since I'm already exposing a REST API with this server.  While doing this isn't rocket science, it seems pretty complicated to just hand something content from memory.
Does anyone have a good pattern for using wkhtmltopdf from node with HTML held in memory?

A: Apparently there are two npm packages for this.  If you google 'node wkhtmltopdf' you are likely to run into this one first: node-wkhtmltopdf
...but if you look further you'll find: wkhtmltopdf which is seems more actively maintained and has documentation explaining how to use it directly, as mentioned by @Ben Fortune in the comments above.
Using the correct package, it seems well explained how to use HTML directly.


text:
Q: What's the meaning of [=](...){...} in C++? What is the effect of this statement:
std::replace_if(ln.begin(),ln.end(),[=](int c){return c=='\n'||c==' ';},0);

Specifically, I'd like to know:
What's the meaning of
[=](int c){return c=='\n'||c==' ';}

Where's the grammar for this defined?

A:
[=](int c){return c=='\n'||c==' ';}

is a lambda expression that creates an unnamed function object. It is callable with one parameter and returns a boolean. The square brackets are the so-called "lambda introducer" which contains the so-called "capture-clause". The capture-clause tells the compiler how the lambda object captures surrounding local variables.

std::replace_if(ln.begin(),ln.end(),[=](int c){return c=='\n'||c==' ';},0);

replace_if takes two iterators for a sequence, a functor (more specifically: a predicate) and some other value. It iterates over the elements of the sequence called ln and replaces each element with 0 if the given predicate (the lambda expression) returns true for that element.
So, basically, this line of code will replace each space and line feed character in ln with a null terminator.

A: It's a lambda function. A function that has no name and is defined inline in the code. It's been added to C++ with the C++11 Standard. So, it's relatively new.
You can read about them here

A: It's a lambda. It replaces the integers c in the container ln with 0 if c == '\n' or c == ' '. Since the container seems to hold characters, you can basically say it replaces spaces and newlines with null-terminating characters.


text:
Q: matrix from C function to Python I'm working with python and ctypes. I have a C function convert a quaternion (similar to an imaginary number) to a matrix. I know, that send result variable in function like argument it's bad tone, so how can I return matrix to python code in type array c_float*16.
float* QuaternionToMatrix(Quaternion q)
{
    float matrix[16];

    matrix[ 0] = 1.0f - 2.0f * ( q.y * q.y + q.z * q.z );
    matrix[ 1] = 2.0f * (q.x * q.y + q.z * q.w);
    matrix[ 2] = 2.0f * (q.x * q.z - q.y * q.w);
    matrix[ 3] = 0.0f;

    matrix[ 4] = 2.0f * ( q.x * q.y - q.z * q.w );
    matrix[ 5] = 1.0f - 2.0f * ( q.x * q.x + q.z * q.z );
    matrix[ 6] = 2.0f * (q.z * q.y + q.x * q.w );
    matrix[ 7] = 0.0f;

    matrix[ 8] = 2.0f * ( q.x * q.z + q.y * q.w );
    matrix[ 9] = 2.0f * ( q.y * q.z - q.x * q.w );
    matrix[10] = 1.0f - 2.0f * ( q.x * q.x + q.y * q.y );
    matrix[11] = 0.0f;

    matrix[12] = 0;
    matrix[13] = 0;
    matrix[14] = 0;
    matrix[15] = 1.0f;

    float* a = matrix;

    return a;
}

A: You're returning a pointer to a local variable. This will cause memory corruption.  I'd recommend creating a struct enapsulating your matrix and returning that:
typedef struct matrix {
    float data[16];
} matrix;

matrix QuaternionToMatrix(Quaternion q) {
    ...
}

Because this will result in copying some amount of memory (c. 512 bytes), you would probably be better off passing the matrix as an out-parameter:
void QuaternionToMatrix(Quaternion q, matrix *matrix) {
    ...
}


text:
Q: Select last daily not null value with timezone I have a collection of data provided by many sensors and need to get the last value of the day per sensor at a specific timezone.
Every device is GEO-located so I need the day located accordingly.
Here's the involved table:
CREATE TABLE public.dt_weight(
  hive character(20) NOT NULL,
  hiveconnection integer,
  instant timestamp with time zone NOT NULL,
  weight integer,
  optweight integer,
  CONSTRAINT dt_weight_pkey PRIMARY KEY (hive, instant)
)

And the query:
SELECT w1.*
    FROM dt_weight w1
    JOIN (
        SELECT hive, DATE_TRUNC('day', instant AT TIME ZONE 'pst') AS moment,
            MAX(instant) AT TIME ZONE 'pst' AS last
        FROM dt_weight
        WHERE weight IS NOT NULL AND hive = '002C0055700833024E45'
        GROUP BY DATE_TRUNC('day', instant AT TIME ZONE 'pst'), hive
    ) w2
    on (w1.instant = w2.last AND w1.hive=w2.hive)
WHERE w1.hive = '002C0055700833024E45'
ORDER BY moment

and the result (hive, moment, last):
"002C0055700833024E45";932890;"2015-11-23 23:55:42+01";27800;
"002C0055700833024E45";933006;"2015-11-25 23:56:02+01";27770;
"002C0055700833024E45";933065;"2015-11-26 23:56:22+01";27610;

moment and last are returned as timestamp without timezone and many records are missing! Trying the subquery alone I get more values:
SELECT hive, DATE_TRUNC('day', instant AT TIME ZONE 'pst') AS moment,
    MAX(instant) AT TIME ZONE 'pst' AS last
FROM dt_weight
WHERE weight IS NOT NULL AND hive = '002C0055700833024E45'
GROUP BY DATE_TRUNC('day', instant AT TIME ZONE 'pst'), hive
ORDER BY last

"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:57:17"
"002C0055700833024E45";"2015-11-19 00:00:00";"2015-11-19 23:58:12"
"002C0055700833024E45";"2015-11-20 00:00:00";"2015-11-20 23:52:12"
"002C0055700833024E45";"2015-11-21 00:00:00";"2015-11-21 23:53:03"
"002C0055700833024E45";"2015-11-22 00:00:00";"2015-11-22 23:55:47"
"002C0055700833024E45";"2015-11-23 00:00:00";"2015-11-23 23:55:42"
"002C0055700833024E45";"2015-11-24 00:00:00";"2015-11-24 23:56:02"
"002C0055700833024E45";"2015-11-25 00:00:00";"2015-11-25 23:56:02"
"002C0055700833024E45";"2015-11-26 00:00:00";"2015-11-26 23:56:22"

Days 18 to 22 and 24 doesn't show up. Why?!? My client timezone is CEST. Need to mention that this query is meant as a piece of a bigger plan.
For completeness here's a slice of source data:
SELECT hive, DATE_TRUNC('day', instant AT TIME ZONE 'pst') AS moment, instant AT TIME ZONE 'pst', weight
FROM dt_weight
WHERE weight IS NOT NULL AND hive = '002C0055700833024E45'
ORDER BY instant

"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 03:04:57";3540
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 03:05:17";3540
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 06:47:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 06:57:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:07:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:17:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:27:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:37:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:47:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 07:57:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:07:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:17:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:27:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:37:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:47:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 08:57:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:07:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:17:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:27:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:37:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:47:27";0
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 09:57:27";27940
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:07:27";27940
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:17:27";27950
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:27:27";27960
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:37:27";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:47:27";27950
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 10:57:27";27950
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:07:27";27970
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:17:27";27960
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:27:27";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:37:27";27970
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:47:27";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 11:57:27";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:07:27";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:17:27";27970
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:27:27";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:37:27";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:47:27";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 12:57:27";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:07:27";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:17:27";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:27:27";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:37:27";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:47:27";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 13:57:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:07:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:17:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:27:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:37:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:47:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 14:57:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:07:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:17:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:27:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:37:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:47:23";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 15:57:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:07:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:17:23";27960
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:27:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:37:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:47:23";27970
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 16:57:23";27990
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:07:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:17:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:27:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:37:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:47:23";27970
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 17:57:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:07:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:17:23";28030
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:27:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:37:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:47:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 18:57:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:07:23";28040
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:17:23";28030
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:27:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:37:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:47:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 19:57:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:07:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:17:23";27980
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:27:23";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:37:23";28040
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:47:23";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 20:57:17";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:07:17";28050
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:17:17";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:27:17";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:37:17";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:47:17";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 21:57:17";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:07:17";28030
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:17:17";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:27:17";28030
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:37:17";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:47:17";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 22:57:17";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:07:17";28040
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:17:17";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:27:17";28000
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:37:17";28010
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:47:17";28020
"002C0055700833024E45";"2015-11-18 00:00:00";"2015-11-18 23:57:17";28010
"002C0055700833024E45";"2015-11-19 00:00:00";"2015-11-19 00:07:17";28030
"002C0055700833024E45";"2015-11-19 00:00:00";"2015-11-19 00:17:17";28010
"002C0055700833024E45";"2015-11-19 00:00:00";"2015-11-19 00:27:17";28010

A: Try this one:
SELECT
    DISTINCT ON (hive, moment)
    *, DATE_TRUNC('day', instant AT TIME ZONE 'pst') AS moment
FROM dt_weight
ORDER BY hive, moment DESC, instant DESC;

It uses DISTINCT ON to keep only the first row for each combination of hive and day. To make sure that the first row that we keep is also the latest one, we additionally sort in reverse chronological order.


text:
Q: BeautifulSoup: Duplicated Class parsing how to overcome I am finding some difficulties in parsing the HTML with "class" using BeautifulSoup. The idea is to get the price of an item on a website which has the following HTML exposure:
HTML structure
Therefore, I need the £920 as a text.
I have tried the following:
url = 'https://www.tiffany.co.uk/jewelry/necklaces-pendants/tiffany-t-t1-circle-pendant-69901190/'

#Open the url to monitor using a new user agent to avoid website blocks you
req = Request(
    url=url,
    headers={'User-Agent': 'Mozilla/5.0'}
)

#Read the HTML code of the url
webpage = urlopen(req, context=ctx).read()
soup = bs4.BeautifulSoup(webpage, "html.parser")

#Define the HTML element we need to screen and find prices
prices = soup.find("span", {"class": "product-description__addtobag_btn_text-static_price-wrapper_price"}).get_text()
print(prices)

And I am getting "[]" as an answer. I believe that since that the product-description__addtobag_btn_text-static_price-wrapper_price I am interested in a sub-part of the same product-description__addtobag_btn_text-static_price-wrapper_price BeautifulSoup takes the first that has no text. I am not sure how to overcome this.
Thank you!

A: The website you are trying to reach is using Javascript to load the page.
One way to grab the price is using the Selenium package:
Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.tiffany.co.uk/jewelry/necklaces-pendants/tiffany-t-t1-circle-pendant-69901190/")

# Wait for the element to be present and visible on the page
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CLASS_NAME, "product-description__addtobag_btn_text-static_price-wrapper_price"))
)

price = element.text
print(price)

Output:
£6,675

More info on the Selenium package can be found here.

A: Data are not loaded as html but as json in a script markup:
<script type="application/ld+json">
            {
                "@context": "http://schema.org",
                "@type": "Product",
                "description": "Tiffany T1 designs reinvent our iconic Tiffany T collection with bold profiles and powerful details. Precisely crafted in 18k yellow gold, this large circle pendant features a beveled edge that makes a striking statement. Wear it solo or layer with necklaces in different lengths for a distinctive look.",
                "name": "Tiffany T T1 Circle Pendant",
                "image": "//media.tiffany.com/is/image/Tiffany/EcomItemL2/tiffany-tt1-circle-pendant-69781926_1030892_ED.jpg?&op_usm=1.0,1.0,6.0&$cropN=0.1,0.1,0.8,0.8&defaultImage=NoImageAvailableInternal&",
                "url": "https://www.tiffany.co.uk/jewellery/necklaces%20&%20pendants/tiffany-t-t1-circle-pendant-69901190/",
                "sku": "69901190",
                "category": "Necklaces & Pendants",
                "material": ["Gold"],
                "color": [],
                "itemCondition": "New",
                "brand": "Tiffany & Co.",
                "offers":{
                    "@type": "Offer",
                    "priceCurrency": "GBP",
                    "price": "6675",
                    "url": "https://www.tiffany.co.uk/jewellery/necklaces%20&%20pendants/tiffany-t-t1-circle-pendant-69901190/"
                }
            }
        </script>

So, you can use:
import json

data = json.loads(soup.find_all('script', {'type': 'application/ld+json'})[-1].get_text())
price = int(data['offers']['price'])

Output:
>>> price
6675


text:
Q: Apply Low Pass Filter How to apply this Low Pass Filter Function in my code:
static final float alpha = 0.05f;
    public float[] lowPass(float[] output, float[] input)
    {
        output[0] = output[0] + alpha * (input[0] - output[0]);
        output[1] = output[1] + alpha * (input[1] - output[1]);
        output[2] = output[2] + alpha * (input[2] - output[2]);
        return output;
    }

Reading Accelerometer and detecting an accident
I Want mLastX, mLastY and mLastZ save  accelerometer readings after being filtered with low pass filter
public void onSensorChanged(int sensor, float[] values)
    {
        if (sensor != SensorManager.SENSOR_ACCELEROMETER) return;
        long now = System.currentTimeMillis();

        if ((now - mLastForce) > SHAKE_TIMEOUT) {
            mShakeCount = 0;
        }

        if ((now - mLastTime) > TIME_THRESHOLD) {
            long diff = now - mLastTime;
            float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
            if (speed > FORCE_THRESHOLD) {
                if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
                    mLastShake = now;
                    mShakeCount = 0;
                    if (mShakeListener != null) {
                        mShakeListener.onShake();
                    }
                }
                mLastForce = now;
            }
            mLastTime = now;
            mLastX = values[SensorManager.DATA_X];
            mLastY = values[SensorManager.DATA_Y];
            mLastZ = values[SensorManager.DATA_Z];

A: Call it with the first parameter initially being the array [mlastx, mlastY, mlastz] and the second parameter being the current values of the sensor.  After being called, the values of the first array will be changed and should become mlastX, mlastY, and mlastZ.  Its actually easier to code if you just keep them as an array rather than holding them in separate variables.
Now wether this will accomplish what you want is another question.  Your math as it is in that function has some odd things in it, and a few things just outright wrong.  For example, you're summing accelerations and dividing by time to get a "speed".  No, that gets you jerk.  Speed would require you to multiply by time.  And to get a true vector magnitude you should be adding the squares of the speed differences for each component, not the absolute values.  THe 10K multiplication makes no sense, just divide the threshold by 10K, as its unlikely to be used anywhere else.  This has a feeling of someone who tried to translate an algorithm they didn't really understand.


text:
Q: iOS 7. Keep UITableView section header from sticking on top I'm designing a menu with categories and subcategories: when the user clicks a category, it should unfold to show its subcategories in an accordion style.
My first approach (and the easiest, I guess), is setting a table section per category: section headers would contain the category, and the inner cells would be subcategories, but the default behavior of the section headers staying at the top doesn't fit too well with the design of my interface.
My questions:
- Is there any iOS7 feature to prevent this behavior so that section headers keep moving just as a normal cell?
- Am I missing some UITableView feature conceived for accordion styled menus?

I'm aware of this old thread.-
Change Default Scrolling Behavior of UITableView Section Header
which solution is based on using scrollViewDidScroll, just wondering if there's any new feature to perform the task in a 'less manually' way.

A: If you use UITableViewStyleGrouped then the section headers will scroll down with the cells.


text:
Q: Packing and unpacking a 32-bit number? I have a project I'm working on where the file format stores the locations of various parts of the file in offsets. So, for example, the file will hold information about 8 different layers. There will be an offset in bytes to the data for each layer.
I'm having trouble calculating what that offset is as the way it is stored is confusing to me. I do have enough documentation to do it by hand but I don't know how to do it in code.
The docs say:
A packed offset is 32bits. The unpacked offset is also a 32 bit number to be used as a byte count. An offset is packed in memory as two words, or 4 bytes.
So, for example,
byte0 = aaaaaaaa
byte1 = bbbbbbbb
byte3 = cccccccc
byte4 = ddddeeee
The hi nibble of the low byte is appended to byte 0 and byte 2 as follows:
dddd aaaaaaaa cccccccc
Four 0 are added to the lo part (enforcing 16 byte chunkiness)
dddd aaaaaaaa cccccccc 0000
For completeness we specify that the high 8 bits of a 32 bit offset are 0.
The final unpacked offset looks like this:
00000000 ddddaaaa aaaacccc cccc0000
I can follow those instructions manually and come up with the correct numnber, but I don't know how to code that. I was copying another person's code who was working with the same filetype and they used:
offset = (val1 << 12) + (val2 << 4) + (val3 <<4) + (val4 >> 4)
val1, val2, val3, and val4 are just the 4 individual bytes. This worked fine for smaller numbers, but as soon as they got over a certain value, it no longer worked.
Can anyone help in getting this to work in C#?

A: Judging by your description, it looks like you need the following
offset = val1 << 12 | val3 << 4 | (val4 & 0xF0) << 16;

In this case, val1 means aaaaaaaa, val3 means cccccccc and val4 means dddddddd. val2 appears to be ignored.


text:
Q: Unhandled exception: FormatException: My problem is I Work on flutter app with firebase i make all the steps to can use firebase and i had this exception when i run flutterfire configure command
⠼ Fetching available
Firebase projects...
Unhandled exception:
FormatException: Unexpected character (at character 1)

^
#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1250:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:915:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#4      JsonDecoder.convert (dart:convert/json.dart:612:36)
#5      runFirebaseCommand (package:flutterfire_cli/src/firebase.dart:95:25)
#6      getProjects (package:flutterfire_cli/src/firebase.dart:114:20)
#7      ConfigCommand._selectFirebaseProject (package:flutterfire_cli/src/commands/config.dart:278:24)
#8      ConfigCommand.run (package:flutterfire_cli/src/commands/config.dart:368:37)
#9      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
#10     main (file:///C:/Users/IT/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutterfire_cli-0.2.6/bin/flutterfire.dart:57:5)
⠦ Fetching available Firebase projects...
Unhandled exception:
FormatException: Unexpected character (at character 1)

^
#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1250:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:915:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#4      JsonDecoder.convert (dart:convert/json.dart:612:36)
#5      runFirebaseCommand (package:flutterfire_cli/src/firebase.dart:95:25)
#6      getProjects (package:flutterfire_cli/src/firebase.dart:114:20)
#7      ConfigCommand._selectFirebaseProject (package:flutterfire_cli/src/commands/config.dart:278:24)
#8      ConfigCommand.run (package:flutterfire_cli/src/commands/config.dart:368:37)
#9      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
#10     main (file:///C:/Users/IT/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutterfire_cli-0.2.6/bin/flutterfire.dart:57:5)

A: Probably you have to update the firebase CLI.
Open a terminal and put these commands:

*

*curl -sL firebase.tools | upgrade=true bash

*firebase login --reauth


text:
Q: psql and trigger behaviour I'm restoring a sql dump with a psql command:
psql -h 127.0.0.1 -p 5433 -U master -d dbname -f sqldump.sql

My database has several event triggers and just ordinary triggers on the tables.
Does psql turn them off during restoration(as far as I saw event triggers were turned off by psql)? I would like to know the exact commands psql does in order to achieve this.

A: psql will not disable event triggers. What makes you think so?
Event triggers by default are only triggered if the parameter session_replication_role is set to is set to local or origin, so you can prevent event triggers from firing by setting the parameter to replica (that won't work for event triggers that have ENABLE REPLICA or ENABLE ALWAYS).


text:
Q: How to fetch a oneToMany lazy relationship using hibernate and jpa PROBLEM: hibernate is ignoring JOIN FETCH I put in my query. My intention is to retrieve the product_item elements from a oneToMany relationship that has been set as lazy but this is not happening.
This is the query I am trying to run:
em.createQuery("SELECT DISTINCT e " +
            "FROM ereturn e, " +
            "user shipper " +
            "JOIN FETCH product_item pi on pi.ereturn.id = e.id " +
            "JOIN FETCH product_definition pd on pi.product.id = pd.id " +
            "WHERE " +
            "shipper.id = e.shipper.id " +
            "AND e.scanDateTime IS NOT NULL " +
            "AND e.status = 'RECEIVED'").getResultList()

this is the query execution plan:
Hibernate:
select
    distinct ereturn0_.id as id1_1_,
    ereturn0_.barcode as barcode2_1_,
    ereturn0_.carrier as carrier27_1_,
    ereturn0_.consignee as consign28_1_,
    ereturn0_.consigneeFirstName as consigne3_1_,
    ereturn0_.consigneeLastName as consigne4_1_,
    ereturn0_.creationtime as creation5_1_,
    ereturn0_.disabled as disabled6_1_,
    ereturn0_.dispatchedDate as dispatch7_1_,
    ereturn0_.failedReturnPOBoxPrivateBag as failedRe8_1_,
    ereturn0_.globalCondition as globalCo9_1_,
    ereturn0_.globalId as globalI10_1_,
    ereturn0_.groupName as groupNa11_1_,
    ereturn0_.invoice as invoice12_1_,
    ereturn0_.notes as notes13_1_,
    ereturn0_.pickupDateTime as pickupD14_1_,
    ereturn0_.pickupDateTimeOffset as pickupD15_1_,
    ereturn0_.pieces as pieces16_1_,
    ereturn0_.processedByShipper as process17_1_,
    ereturn0_.reasonToReturn as reasonT18_1_,
    ereturn0_.returnAction as returnA19_1_,
    ereturn0_.returnMethod as returnM20_1_,
    ereturn0_.returned as returne21_1_,
    ereturn0_.rma as rma22_1_,
    ereturn0_.scanDateTime as scanDat23_1_,
    ereturn0_.shipper as shipper29_1_,
    ereturn0_.status as status24_1_,
    ereturn0_.trackingNumber as trackin25_1_,
    ereturn0_.weight as weight26_1_
from
    ereturn ereturn0_ cross
join
    user user1_
inner join
    product_item productite2_
        on (
            productite2_.ereturn=ereturn0_.id
        )
inner join
    product_definition productdef3_
        on (
            productite2_.product=productdef3_.id
        )
where
    user1_.id=ereturn0_.shipper
    and (
        ereturn0_.scanDateTime is not null
    )
    and ereturn0_.status='RECEIVED'

The query gets executed but ereturn.productItems are not fetched hence json serialization complains.
And these are my classes:
public class Ereturn {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "shipper")
private User shipper = new User("", UserType.SHIPPER);
@ManyToOne
@JoinColumn(name = "consignee")
private User consignee;
@ManyToOne
@JoinColumn(name = "carrier")
private User carrier = new User("", UserType.CARRIER);
@JsonManagedReference(value="ereturn-parcel")
@OneToMany(mappedBy = "ereturn", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Parcel> parcels = new ArrayList<>();
@JsonManagedReference(value="ereturn-productItems")
@OneToMany(mappedBy = "ereturn", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProductItem> productItems = new ArrayList<>();
...
}

public class ProductItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name  = "product")
private ProductDefinition product;
@JsonBackReference(value="ereturn-productItems")
@ManyToOne
@JoinColumn(name = "ereturn")
private Ereturn ereturn;
...
}

public class ProductDefinition {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "shipper")
private User shipper;
@JsonIgnore
@OneToMany(mappedBy = "product", cascade = CascadeType.REFRESH)
private List<ProductItem> productItems = new ArrayList<>();
...
}

public class User implements SecurityContext {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
@OneToMany(mappedBy = "shipper", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductDefinition> productDefinitions = new HashSet<>();
@JsonIgnore
@OneToMany(mappedBy = "shipper", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<Ereturn> ereturns = new HashSet<>(); // Client process ereturn to finish it
@JsonIgnore
@OneToMany(mappedBy = "shipper", cascade = CascadeType.ALL)
private Set<Contract> contracts = new HashSet<>();
private Boolean disabled = Boolean.FALSE;
...
}

QUESTION 1: Why the query is not fetching elements from product_item table?
QUESTION 2: the query above returns as many elements as rows returned from the database instead of grouping by ereturn. Why is that?

A: I believe that JOIN FETCH with ON conditions not work to fetch entities on Hibernate. I not found this kind of use on Hibernate documentation or examples on the Internet.
To make the FETCH work, you need to use the relationship between the two entities and use the JOIN FETCH without the ON conditions, like:
SELECT e FROM eReturn e
JOIN FETCH e.productItens

And remember to not use the fetched alias to apply WHERE conditions.


text:
Q: After calling MoveWindow() with TRUE, the window client area is still invalid MSDN doc's for MoveWindow() says:
"If the bRepaint parameter is TRUE, the system sends the WM_PAINT message to the window procedure immediately after moving the window (that is, the MoveWindow function calls the UpdateWindow function)."
But when I call GetUpdateRect() after MoveWindow(), while processing the WM_LBUTTONDOWN message in the parent, I get a beep, which shows that the child is invalid. What is the explanation ???
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>

HINSTANCE   ghInstance;

LRESULT CALLBACK WindowProc (HWND hwnd, UINT message, UINT wParam, LONG lParam);
LRESULT CALLBACK ChildProc (HWND hwnd, UINT message, UINT wParam, LONG lParam);

int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
    HWND        hWnd;
    MSG     msg;
    WNDCLASSEX  wndclassx;

    ghInstance = hInstance;

    wndclassx.cbSize        = sizeof(WNDCLASSEX);
    wndclassx.style         = 0;
    wndclassx.lpfnWndProc   = WindowProc;
    wndclassx.cbClsExtra    = 0;
    wndclassx.cbWndExtra    = 0;
    wndclassx.hInstance     = hInstance;
    wndclassx.hIcon         = 0;
    wndclassx.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wndclassx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wndclassx.lpszMenuName  = NULL;
    wndclassx.lpszClassName = _T("ParentWindow");
    wndclassx.hIconSm       = NULL;

    if( !RegisterClassEx(&wndclassx) ) return 0;

    wndclassx.cbSize        = sizeof(WNDCLASSEX);
    wndclassx.style         = 0;
    wndclassx.lpfnWndProc   = ChildProc;
    wndclassx.cbClsExtra    = 0;
    wndclassx.cbWndExtra    = 0;
    wndclassx.hInstance     = hInstance;
    wndclassx.hIcon         = 0;
    wndclassx.hCursor       = 0;
    wndclassx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wndclassx.lpszMenuName  = NULL;
    wndclassx.lpszClassName = _T("ChildWindow");
    wndclassx.hIconSm       = NULL;

    if( !RegisterClassEx(&wndclassx) ) return 0;

    if( !(hWnd = CreateWindow(_T("ParentWindow"), _T("Parent Window"), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                              CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance,
                              NULL)) ) return 0;

    ShowWindow(hWnd, SW_SHOW);
    UpdateWindow(hWnd);

    while( GetMessage(&msg, NULL, 0, 0) )
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

LRESULT CALLBACK WindowProc (HWND hwnd, UINT message, UINT wParam, LONG lParam)
{
    HWND    hWnd;

    switch ( message )
    {
        case WM_CREATE:

        CreateWindow(_T("ChildWindow"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, 10, 10, 100, 100, hwnd, (HMENU)0,
                          ghInstance, NULL);
        break;

        case WM_LBUTTONDOWN:

        hWnd = GetWindow(hwnd, GW_CHILD);

        MoveWindow(hWnd, 10, 10, 200, 200, true);

        if( GetUpdateRect(hWnd, NULL, FALSE) ) MessageBeep(-1);
        break;

        case WM_DESTROY:
        PostQuitMessage(0);
        break;

        default:

        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

LRESULT CALLBACK ChildProc (HWND hwnd, UINT message, UINT wParam, LONG lParam)
{
    return DefWindowProc(hwnd, message, wParam, lParam);
}

A: I tried it myself and WM_PAINT is triggered before the if(GetUpdateRect()) is. Also, GetUpdateRect returns FALSE for me.
I'm running Visual Studio 2008 on XP.
I guess it could depend on what compiler you are using, what operating system that is used and whatnot. According to the code you passed everything is done in the same thread, but if it is a multithreaded program I think that this could inflict some issues as well.

A: The MSDN doc's is wrong. MoveWindow() with TRUE doesn't call UpdateWindow() as the documentation says. It just invalidates the window client area. If I call UpdateWindow() just after MoveWindow() the program runs as expected.


text:
Q: Problem in Group theory about normal subgroup Let $H$ be a normal subgroup of a group $G$ with index $n$. Prove that if $g \in G$ then $g^n\in H$. Find an example pointing that this can not occur if $H$ is not normal.

A: In general, for any group $G$ with $n=|G|$, $g^n=e$ where $e$ is the identity element.  So, if $H$ is a normal subgroup of $G$ with $[G:H]=n$, then $|G/H|=n$.
Let $g\in G$, then $H=eH=(gH)^n=g^nH$.  Hence, $g^n\in H$.


text:
Q: Azure Active Directory access error I am using Azure Active Directory B2C in an application. When I try to call the azure login page (which is a sign-in policy), I am prompted with the following error:

Sorry, but we're having trouble signing you in.
  We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, please try again.
  Correlation ID: 9e8de233-669b-4495-8678-236216359c58
  Timestamp: 2017-02-21 13:51:35Z
  AADB2C90068: The provided application with ID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' is not valid against this service. Please use an application created via the B2C portal and try again.

Any suggestions on how to fix this and allow user to authenticate into the application?

A: I believe the problem is that you have registered under the tab Applications in the non-B2C portal. Under the "Getting Started" or "Configure" tab you will find a link called "Manage B2C settings". Clicking this will take you to the new Azure portal but logged into the B2C directory instead. Go to "Applications" and register your application there.
Image


text: Q: Any other machine learning algorithms besides clustering for Customer Segmentation I've searched online materials for Customer Segmentation for a while. Most materials are related with K-means or some other clustering algorithms. Are there any other machine learning or statistical models that are widely used in industry for Customer Segmentation? Any tutorials or related links are helpful.


text:
Q: Is it possible to have multiple ActionBar CustomViews? I have a simple question.
Is the following scenario possible with the Android Actionbar:

*

*Actiobar Title

*CustomView1

*CustomView2

*Normal MenuItem

Graphical representation:

What I know is that it's possible to have a custom Actionbar View by using this method:
ActionBar.setCustomView(View v);

in addition to that, I know having a title and normal MenuItems in combination with a CustomView is supported as well.
But is it possible to have multiple custom Views (like in the picture above) in the ActionBar, and if yes, how?

A: Just create custom layout for your ActionBar menu items and find the menu items to which you want to provide custom layout in onCreateOptionsMenu and call setActionView(View view) on them.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    ...
    MenuItem item = menu.findItem(R.id.YOUR_MENU_ITEM_ID);
    item.setActionView(R.layout.YOUR_CUSTOM_LAYOUT);
    ...
}