text:
Q: masking hostname to IP address lookup in Linux/Bash/Perl Many of the servers in our environment have their loop-back line in /etc/hosts configured like so:
127.0.0.1        mydevserver.testdomain.com mydevserver localhost.localdomain localhost

Normally, this is not an issue.  However, we are now dealing with some external software from a vendor that calls gethostbyaddr and their installer is designed to fail if the result of hostname --ip-address is 127.0.0.1.  This of course causes it to fail on our systems because the servers hostname is in the loopback line of /etc/hosts.
My question is, if I wrap the installer in a bash or perl script, is there a way to "mask" or temporarily alter the results of hostname --ip-address without changing the /etc/hosts file?
(Clarification: They are calling the gethostbyaddr() function from within their compiled binary installer. The way to get a similar result from command line is hostname --ip-address)

A: One way might be to write your own gethostbyaddr() function, compile it into a library (say, libmyfunc.so), then preload it in a wrapper script so the vendor's installer uses it rather than the system gethostbyaddr() :
#!/bin/bash
export LD_PRELOAD=libmyfunc.so
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

/path/to/crappy_vendor_binary $@

A: Write your own implementation of hostname that does the expected thing, put it somewhere, unshift that directory before $PATH.

A: If the really call the hostname command, then nothing is easier than that: just replace it with your own version.

A: well if it's a plain BASH script, add this before the call of "hostname":
function hostname(){ echo -n; }


text:
Q: Thread safe usage of CallContext.LogicalSetData I am using CallContext.LogicalGetData in order to share information across asynchronous code.
I want to perform this kind of call in a 'thread-safe' fashion:
var val = CallContext.LogicalGetData(key);
if(val==null)
{
   CallContext.LogicalSetData(key, initialValue);
}
return val;

Any idea on how to do that ?

A: Use a lock:
private static readonly object _lock = new object();

public static object GetData(string key, object initialValue)
{
    lock(_lock)
    {
       object val = CallContext.LogicalGetData(key);
       if (val == null)
           CallContext.LogicalSetData(key, initialValue);
       return val;
    }
}

Note: The class or method do not have to be static. Just make sure that all the threads use the same lock when accesing the critical section.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to stop prettier from adding an extra tab for .then() {} statements after Promise.try? So, I was wondering if it is possible to stop prettier from adding an extra tab for .then() {} statements after Promise.try or just simple return PromiseFn() .then(() => {})..
Usually, I write promise chains, that look something like this:
import Promise from "Bluebird"

Promise.try() {
  // code..
})
.then(() => {
  // more core
})
.then(() => {
 // more code
})

How prettier makes it look like:
Promise.try() {
  // code..
})
  .then(() => {
    // more core
  })
  .then(() => {
   // more code
  })

So I was wondering, if it is possible to stop prettier from adding the extra, non-needed tab before all the .then() statements?

A: It seems Prettier is a very opinionated formatter...
But you may be able to flag to Prettier to ignore the next node
// prettier-ignore
Promise.try() {
  // code..
})
.then(() => {
  // more core
})
.then(() => {
 // more code
})

We dropped using Prettier in our project for this reason, it didn't allow for formatting how we wanted to. And TBH I'm not even sure the above will still work for what you want, but it seems the best option to try.


text:
Q: android firebase start listing data equal to entered letter There is a problem with the list inside the "if" it doesn't work I get an error this:java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
 private FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
private DocumentReference productSearchRef = rootRef.collection("products").document("qQIJ9oGjlwwqNObfVV6U");
private CollectionReference productsRef = rootRef.collection("products");

  MutableLiveData<List<String>> getProductNameListMutableLiveData() {
    MutableLiveData<List<String>> productNameListMutableLiveData = new MutableLiveData<>();
    productSearchRef.get().addOnCompleteListener(productNameListTask -> {
        if (productNameListTask.isSuccessful()) {
            DocumentSnapshot document = productNameListTask.getResult();

            if (document.exists()) {
                List<String> productNameList = (List<String>) document.get("name");

                productNameListMutableLiveData.setValue(productNameList);
            }
        } else {
            Log.d(Constants.TAG, productNameListTask.getException().getMessage());
        }
    });
    return productNameListMutableLiveData;
}![enter image description here](https://i.stack.imgur.com/8a5Tl.jpg)

A: You are getting the following error:

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List"

In the second if statement, because the type of the "name" field in the database is String and not a List, hence that error. There is no way in Java in which you can convert a String into a List. To solve this, you should get the value of the "name" field according to its data type. So please change the following line of code:
List<String> productNameList = (List<String>) document.get("name");

Into:
String productNameList = document.getString("name");

So something like this will do the trick:
private FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
private DocumentReference productSearchRef = rootRef.collection("products").document("qQIJ9oGjlwwqNObfVV6U");
private CollectionReference productsRef = rootRef.collection("products");

MutableLiveData<List<String>> getProductNameListMutableLiveData() {
MutableLiveData<List<String>> productNameListMutableLiveData = new MutableLiveData<>();
    productsRef.get().addOnCompleteListener(productNameListTask -> {
        if (productNameListTask.isSuccessful()) {
            DocumentSnapshot snapshot = productNameListTask.getResult();
             for (QueryDocumentSnapshot document : snapshot) {
                 if (document.exists()) {
                     String name = document.getString("name");
                     productNameList.add(name);
                 }
             }
             productNameListMutableLiveData.setValue(productNameList);
        } else {
            Log.d(Constants.TAG, productNameListTask.getException().getMessage());
        }
    });
    return productNameListMutableLiveData;


text:
Q: Print all the files which are at maximum depth in a directory Print all the files which are present in maximum depth
for example
abc/1/2/3/4/r.txt
abc/1/f1.txt
abc/11/22/44/66/77/f2.txt
abc/11/22/44/66/77/f4.txt
abc/11/22/44/66/77/f5.txt

so this would print
abc/11/22/44/66/77/f2.txt
abc/11/22/44/66/77/f4.txt
abc/11/22/44/66/77/f5.txt

I have written this command
$cat listoffiles.txt  | awk -F "/" ' { if ( NF > x ) { x = NF; y = $0 } }END{ print y }'

but this is printing only the first occurrence.

A: Keep buffering deepest files and discard them whenever the max depth changes. At the end, dump what's in the buffer.
awk -F'/+' 'NF>max{max=NF;delete buf} NF==max{buf[$0]} END{for(f in buf) print f}' file


text:
Q: How to capture regex first occurence and interpolate into string with postgreSQL I'm trying to concatenate the digits from a string that starts with 'CityName' into a separate string. I have the concatenation part. My issue is being able to access the matches from the regex
I have a regex in rails that looks like /CityName\s*(\d+)/i. I'm super new to regex and it's hard for me to wrap my head around the docs. But I'm assuming that this regex will find any digits after the CityName case intensively. And then it's interpolated if it matches an attribute on my model.
regex = /CityName\s*(\d+)/i
if line_1 =~ regex
  "C#{$1}"
  ...
end

But further along in the execution, it's slowing down because I have to iterate over a lot of records. I have a query in psql that will do that calculations that I need, however I'm having a hard time implementing this regex replacement. My attempts so far look like:
CASE
    when addr.line_1 ~* 'CityName\s*(\d+)' then 'C' || regex_matches('CityName\s*(\d+)')[0]
...

I'm having a hard time finding a solution to grab the first occurrence of the regex match. Thanks for any tips :D
EDIT: I am trying to grab the digits after 'CityName' from a string if that string contains 'CityName'
Ultimately I need assistance with the regex and how to contactenate the digits with 'C'

A: Your question is a bit unclear. Are you trying to add the digits to your selection or to filter records based on them?
If you just want to select them:
Address.select(%q{(regexp_matches(addr.line_1, 'CityName\s*(\d+)'))[1] as digits})
  .map(&:digits)

If you want to filter based on then:
Address.where(%q{addr.line_1 ~ 'CityName\s*(\d+)'}).map &:email
  .map(&:line_1)

Also a few notes:

*

*Selecting digits case intensively does not really make sense. Digits
does not have case.

*PostgreSQL arrays start from 1 instead of 0.

A: Got it! Was able to finally start to figure out the regex.
WHEN addr.line_1 ~* '(?i)CityName\s*(\d+)' THEN 'C' || (SELECT (regexp_matches(addr.line_1, '(?i)CityName\s*(\d+)'))[1])
The (?i) allowed for case insensitive matching for CityName and then the concatenation worked. Thank you @ti6on for pointing out the index difference with postgres :D

A: It seems you need a subquery or a WITH query:
SELECT tbl1.col1, sum(...), min(...) FROM (SELECT ..., CASE ...yourregex stuff... END col1 FROM ...) tbl1 GROUP BY 1;
WITH tbl1 AS (SELECT ..., CASE ...yourregex stuff... END col1 FROM ...) SELECT t.col1, sum(...) FROM tbl1 t GROUP BY 1;
If you need them regulary, you can also create views from the query or create a temp table, then you can use it in queries later.


text:
Q: Read error: Failure in SSL library, usually a protocol error I am trying to access an secure url by using a DefaultHttpClient.
I am creating BKS file using portecel tool.
The jks file created using the same is working fine in java program but the bks is throwing the following exception:
java.io.IOException: Read error: Failure in SSL library, usually a protocol error
I am able to open the bks file in a keystore explorer and see the details.
The same is working fine in Android 2.3 but not in 2.2
let me know if anybody has faced such problem and solved it.

A: I encountered the same problem in one of my applications. After googling a bit I found a bugreport from k9mail which refers to this bugreport on Android 2.2 and some more posts all indicating this is a framework bug in 2.2.
I found several sources like this one mentioning that importing the certificates server-side has to be done in some specific order, in order for Android to accept it. Since I have no control over the server I didn't pursue this option and I have no clue if it actually works; however, it might be interesting for you to investigate further.

A: Check whether the server want client authentication.

A: I had this problem with Retrofit Library. I solved this change, "https://10.0.3.2:4567" to "http://10.0.3.2:4567" in my URL connection.


text:
Q: RSS feed not generating for custom post type after wordpress 3.8.1 update Rss feeds seem to be generating for the category and home pages but not for the custom post type  page.I have used custom post type and not the default post.I am getting the feeds for custom post type in  wordpress 3.6 version but not for 3.8.1.It seems the version is a problem but i tried generating feeds for the default post using version 3.8.1 and it showed the posts.The problem seems to be with the version as well as the custom post type.Please help.

A: Did you add the following function in your functions.php (replace the elements in the array with the     slug of your custom post type
/*---------------------------------------------------------------------------------------*/
/*  Add the management of custom type (Etudes et Standard) in the rss                    */
/*   source : http://www.seomix.fr/custom-post-type-wordpress-rss/                       */
/*---------------------------------------------------------------------------------------*/

    function myfeed_request($qv) {
        if (isset($qv['feed']) && !isset($qv['post_type']))
            $qv['post_type'] = array('etudes', 'standard');
        return $qv;
    }
    add_filter('request', 'myfeed_request');


text:
Q: Loss function and batch size in Keras For classification task there are several loss-function we can use.
If I simply use something like
model.compile{ loss=keras.losses.categorical_crossentropy, ....

Does this mean loss is normalized in batch size? like
loss = 1/m * sum_i sum_c [ y_i^c * ln(y^_i)^c ]

wehre m is batch size, and
i  is an index of a sample
c  is class
or the loss is summed up in the batch size?
loss = sum_i  sum_c  [ y_i^c * ln(y^_i)^c ]

A: What I can find from the keras API docs is that the default reduction for batch optimization is set to AUTO which defaults "for almost all cases" to SUM_OVER_BATCH_SIZE. This will mean the loss is the scalar sum divided by number of elements in batch.

*

*Link for tf.keras.losses

*Link for tf.keras.losses.Reduction


text:
Q: Solve $x+y=84, \; \operatorname{lcm}(x,y) = \big( \gcd(x,y) \big)^2$ I am interested in solving the system of equations
$$
(S) \; \left\{
\begin{array}{l}
x + y = 84 \\
\operatorname{lcm}(x,y) = \big( \gcd(x,y) \big)^2
\end{array}
\right.
$$
where $(x,y) \in \mathbb{N}^{\ast}$.

If $d = \gcd(x,y)$, then $d \mid 84$. Therefore:
$$ d \in \lbrace 1, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84 \rbrace. $$
Therefore, for each possible value $d$, we have to solve the system:
$$
(S) \; \left\{
\begin{array}{l}
x + y = 84 \\
\operatorname{lcm}(x,y) = d^2
\end{array}
\right.
$$
However, I'm not sure how to solve such a system given $x+y$ and $\operatorname{lcm}(x,y)$.

A: As @Alexander pointed out in the comments, $\operatorname{lcm}(x, y) = d^2 \iff xy = \operatorname{lcm}(x, y) \operatorname{gcd}(x, y) = d^2d = d^3$, so $ y = \frac{d^3} x \implies x^2-84x+d^3=0 $ and it's easy to carry on from here.
Hope it helps.


text:
Q: How to fix "undefined reference to to `SSLv3_client_method`" during cURL custom installation I work on a project which use cURL a lot. Recently we add a new feature to allow perform SFTP calls within our API.
SFTP is disabled by default in cURL so I tried to search how to enable it. I found that answer which helped me but during the build process I got an error about SSLv3_client_method reference.
I ran :
sudo apt-get install build-essential debhelper libssh2-1-dev
sudo apt-get source libcurl3
sudo apt-get build-dep libcurl3

cd curl-*/debian

vim rules #Append "--with-libssh2"

cd ..
sudo dpkg-buildpackage
cd ..

sudo dpkg -i curl_xxxxx.deb
sudo dpkg -i libcurl3_xxxx.deb
sudo dpkg -i libcurl3-gnutls_xxxx.deb

After the update my "rules" file contains :
cd debian/build && dh_auto_configure ${CONFIGURE_ARGS}          \
    --with-ca-path=/etc/ssl/certs --with-libssh2
cd debian/build-gnutls &&  dh_auto_configure ${CONFIGURE_ARGS}  \
    --with-ca-bundle=/etc/ssl/certs/ca-certificates.crt     \
    --without-ssl --with-gnutls --with-libssh2
cd debian/build-nss && dh_auto_configure ${CONFIGURE_ARGS}      \
    --with-ca-bundle=/etc/ssl/certs/ca-certificates.crt     \
    --without-ssl --with-nss --with-libssh2

Then I got the error :
../lib/.libs/libcurl.so: undefined reference to `SSLv3_client_method'
collect2: error: ld returned 1 exit status
make[4]: *** [curl] Error 1
make[4]: Leaving directory `/home/bee4/curl-7.35.0/debian/build/src'
make[3]: *** [all] Error 2
make[3]: Leaving directory `/home/bee4/curl-7.35.0/debian/build/src'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/bee4/curl-7.35.0/debian/build'
dh_auto_build: make -j1 returned exit code 2
make[1]: *** [override_dh_auto_build] Error 2
make[1]: Leaving directory `/home/bee4/curl-7.35.0'
make: *** [build] Error 2
dpkg-buildpackage: error: debian/rules build gave error exit status 2

I use Ubuntu 14.04 on an OVH server. Maybe I'm doing something wrong ? Also is it the right way to enable SFTP support through the cURL PHP extension (first build the right cURL version then install the PHP extension).

A: I finally get this error out !
For that I needed to build a libssh2 version and build a curl version which used that.
Maybe it is a problem with the bundled curl 7.35.0 in Ubuntu 14.04 (because I used a 7.46.0 during the correction).
So I downloaded a libssh2 source package then I build it :
./configure
make
make install

And I built my curl instance to use this libssh2 :
./configure --with-libssh2=/usr/local --disable-shared
make
make install

With that I have an operational instance of curl 7.46 (the lastest stable) which is also able to use the SFTP & SCP protocols.
I needed to use the --disable-shared flag to force a new compilation of different libs. Without that, the SFTP / SCP are not enabled... Maybe someone can give me some details here...
No more errors about the missing SSLv3_client_method, everything is ok !


text:
Q: Very slow wifi connection Ubuntu 15.04 I recently bought a laptop and installed new Ubuntu on it, dual booting with Windows 8. In windows I have a very decent wifi connection and signal is always high. However on Ubuntu at the same Location in my house I only get 1 or 2 bars. I tried to post it's number but it seems I don't have no wireless extensions in iwconfig
eth0      no wireless extensions.

wlan0     IEEE 802.11abg  ESSID:"amiraratoud"
          Mode:Managed  Frequency:2.412 GHz  Access Point: 94:FB:B3:F9:94:2D
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on

lo        no wireless extensions.

and lspci results:
00:00.0 Host bridge: Intel Corporation Broadwell-U Host Bridge -OPI (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Broadwell-U Integrated Graphics (rev 09)
00:03.0 Audio device: Intel Corporation Broadwell-U Audio Controller (rev 09)
00:04.0 Signal processing controller: Intel Corporation Broadwell-U Camarillo Device (rev 09)
00:14.0 USB controller: Intel Corporation Wildcat Point-LP USB xHCI Controller (rev 03)
00:16.0 Communication controller: Intel Corporation Wildcat Point-LP MEI Controller #1 (rev 03)
00:1b.0 Audio device: Intel Corporation Wildcat Point-LP High Definition Audio Controller (rev 03)
00:1c.0 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #1 (rev e3)
00:1c.1 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #2 (rev e3)
00:1c.2 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #3 (rev e3)
00:1c.3 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #4 (rev e3)
00:1c.4 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #5 (rev e3)
00:1f.0 ISA bridge: Intel Corporation Wildcat Point-LP LPC Controller (rev 03)
00:1f.2 SATA controller: Intel Corporation Wildcat Point-LP SATA Controller [AHCI Mode] (rev 03)
00:1f.3 SMBus: Intel Corporation Wildcat Point-LP SMBus Controller (rev 03)
08:00.0 Network controller: Broadcom Corporation BCM43142 802.11b/g/n (rev 01)
09:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101E/RTL8102E PCI Express Fast Ethernet controller (rev 0a)
0a:00.0 3D controller: NVIDIA Corporation Device 1347 (rev a2)

and lshw -class network results:
  *-network
       description: Wireless interface
       product: BCM43142 802.11b/g/n
       vendor: Broadcom Corporation
       physical id: 0
       bus info: pci@0000:08:00.0
       logical name: wlan0
       version: 01
       serial: d8:5d:e2:b8:12:0f
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=wl0 driverversion=6.30.223.248 (r487574) ip=*.*.*.* latency=0 multicast=yes wireless=IEEE 802.11abg
       resources: irq:18 memory:c6100000-c6107fff
  *-network
       description: Ethernet interface
       product: RTL8101E/RTL8102E PCI Express Fast Ethernet controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:09:00.0
       logical name: eth0
       version: 0a
       serial: 94:57:a5:d6:b7:0f
       size: 10Mbit/s
       capacity: 100Mbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl8107e-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=MII speed=10Mbit/s
       resources: irq:49 ioport:4000(size=256) memory:c6004000-c6004fff memory:c6000000-c6003fff


text:
Q: stuck on basic regular expression Task: To find all the numbers in a text file and compute the sum of it.
Link to file(if required) : http://python-data.dr-chuck.net/regex_sum_42.txt
name = raw_input("Enter your file: ")
if len(name) < 1: name = "sample.txt"

try:
    open(name)
except:
    print "Please enter a valid file name."
    exit()

import re
lst = list()
for line in name:
    line = line.strip()  #strip() instead of rstrip() as there were space before line as well
    stuff = re.findall("[0-9]+", line)
    print stuff               # i tried to trace back and realize it prints empty list so problem should be here
    stuff = int(stuff[0])     # i think this is wrong as well
    lst.append(stuff)
    sum(lst)

print sum(lst)

Can someone tell me where did I go wrong ? sorry for any formatting errors and thanks for the help
I have also tried:
\s[0-9]+\s
.[0-9]+.

A: You need to change your code to:
lst = []
with open(name) as f:
    for line in f:
        stuff = [lst.append(int(x)) for x in re.findall("[0-9]+", line.strip())]
print sum(lst)

See the IDEONE demo
The problem was that you tried to parse an empty string in the first place. When parsing to int and appending to the list (declared with lst = []) inside comprehension, you avoid messing with empty output and the list you get is flattened automatically.
Also, you need to actually read the file in. "The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files." (source)


text:
Q: Setting different strings within a title for multiple graphs in Python I want to have a title such as "Japan IP firms patent filings: mean=834.41, standard deviation=534.56 with the bolded string changing for the different figures.
The mean and standard deviation are already changing using this code:
title = "Japan IP firms patent filings: mu =%.2f, std = %.2f"%(mu,std)

But I want to string together/concatenate the list 'name' below to the above title for every normal distribution figure:
names=[Japan, UK, USA, Uruguay, Brazil,Mexico,Costa Rica]

This is the code in the for loop i have so far
for item in totalIPs:

    mu=statistics.mean(item)
    std=statistics.stdev(item)

    xmin, xmax = plt.xlim()
    x=np.linspace(xmin, xmax, 100)

    fitted_pdf=ss.norm.pdf(x,mu, std)

    plt.figure()

    plt.xlabel('Distribution of patents by IP firms',fontsize=12)

    plt.ylabel('Frequency of firms of each patents',fontsize=12)

    plt.hist(x, bins=10,normed=True, alpha=0.6, edgecolor='black', color = 'g')

    plt.plot(x, fitted_pdf, 'K', linewidth=2)
        title = "Japan IP firms patent filings: mu =%.2f, std = %.2f"%(mu,std)
    plt.title(title)

I think I have to use the matplotlib.Axes method set_title to do this but I am not sure how to combine it with the code i have already for the 'title'

A: Using zip you can iterate over your names at the same time as totalIPs, and then you can use string formatting to include that name in your title string:
names = ['Japan', 'UK', 'USA', 'Uruguay', 'Brazil', 'Mexico', 'Costa Rica']

for item, name in zip(totalIPs, names):

    mu=statistics.mean(item)
    std=statistics.stdev(item)

    xmin, xmax = plt.xlim()
    x=np.linspace(xmin, xmax, 100)

    fitted_pdf=ss.norm.pdf(x,mu, std)

    plt.figure()

    plt.xlabel('Distribution of patents by IP firms',fontsize=12)

    plt.ylabel('Frequency of firms of each patents',fontsize=12)

    plt.hist(x, bins=10,normed=True, alpha=0.6, edgecolor='black', color = 'g')

    plt.plot(x, fitted_pdf, 'K', linewidth=2)

    title = "{} IP firms patent filings: mu ={:.2f}, std = {:.2f}".format(name, mu, std)
    plt.title(title)


text:
Q: JPA, inheritance and instanceof I use JPA inheritance with JOIN strategy (JPA2/Hibernate). I have an abstract general Event entity with shared fields (date, time, place etc), and its children, let's say OutdoorEvent, ClassicalMusicEvent etc. with specific fields for each type. I make a search over all Event's, getting a List<Event> which I display. The processing for each event type is different though, so I need to figure out the type of event for each Event object. Now here's the problem. I came up with two solutions. First, the instanceof keyword:
if (event instanceof OutdoorEvent) {
   ...
} else if (event instanceof OtherKindOfEvent) {
   ...
} etc.

Second, I add a transient enum field to the Event entity and set this field in every children type's constructor. Then I could do:
if (event.getType() == EventType.OutdoorEvent) {
   ...
} else if (event.getType() == EventType.OtherKindOfEvent) {
   ...
} etc.

Which solution is better, or more OOP? Is there any other solution to this?

A: This is a good question because the optimal OOP solution would be to use polymorphism.  On your abstract Event class add an abstract 'process' method and then in your subclasses implement the required processing.  Then you can just call process() and don't care what the type of subclass it is.
However, you probably want to keep your Event (i.e. data) classes decoupled from the logic so somewhere you're probably going to end up doing instanceof or something like your enum.
I have no preference which, it is possible that one is faster than the other and I would probably go with the enum rather than instanceof for speed (keen to hear if anyone has insight on that).
If you do go with the enum In your example with the events, you should use a switch instead of if..else.

A: The most OOP approach would be to use the visitor pattern.
Put the display handling logic in a Visitor:
public VisitorImpl implements Visitor {
    public void handleOutdoorEvent(OutdoorEvent event) { .. }
    public void handleOtherKindOfEvent(OtherKindOfEvent event) { .. }
}

And then on each subclass have:
public void handleDisplay(Visitor visitor) {
     visitor.visit(this);
}

Then instead of the multiple if-checks you just do:
Visitor visitor = new VisitorImpl(..);
for (..) {
   entity.visit(visitor);
}

Apart from that, instanceof looks cleaner.

A: If you deal with Hibernate then you should prepare yourself for cases with Hibernate Proxies (see e.g. Casting Hibernate Proxies to Subclasses): in your example variable event might be a dynamically created instance of HibernateProxy, and event instanceof OtherKindOfEvent will not work in this case.
So you will either need to de-proxy (using Hibernate utilities and loosing JPA abstraction), or use approach like you've mentioned. So my personal preference is the second option (or anything similar to it).

A: Simple strategy pattern:
Map<Class<?>,Handler> handlers = new ArrayList();
handlers.add(SomeClass1.class, new Handler1());
handlers.add(SomeClass2.class, new Handler2());
handlers.add(SomeClass3.class, new Handler3());

....

for(Entity e : entities){
   handlers.get(e.getClass()).execute(e);
}


text:
Q: Debug statement truncated in Raw Log It seems like something was implemented last spring that truncates long debug statements in the developer console. All the solutions say to view the raw log. I opened the raw log from both the developer console and also from the debug logs page but both are also truncated. If anyone knows how to fix this it would be much appreciated.

A: Certain types of debug statements are "always" truncated (assuming they reach some arbitrary length), notably Map, List, and Set values that are debugged directly to the log.
For example:
System.debug([SELECT Name FROM Account LIMIT 50000]);

Also, if you reach the maximum log size (20MB), then there will definitely be truncation. If you need to see the entire value, consider using a Check Point instead. Also, see this trailhead on how to use Check Points.
Serializing the object (JSON.serialize(someValue)) can also allow much larger values to be printed out, although not all objects can be serialized this way.


text:
Q: Retrieving the documents connected this vertex I would like to retrieve all documents connected to the vertex.
First all my idea was to find a vertex by using the information stored in it. I was able to do it with a full text query:
FOR doc IN spec
FILTER doc.serial_no == '"12345abc"'
RETURN doc

RESULT:
[
  {
    "_key": "3834670",
    "_id": "spec/3834670",
    "_rev": "_WP3-fvW---",
    "type": "spec-type-545",
    "name": "spec-name-957",
    "serial_no": ""12345abc""
  }
]

Now I would like to find all documents attached to this vertex. How can I do that?

A: Assuming you save connections from your vertex to its attached documents in edge collections you can use a traversal.
A traversal starts at one specific document (startVertex) and follows all edges connected to this document. For all documents (vertices) that are targeted by these edges it will again follow all edges connected to them and so on.
In your case the startVertex is 'spec/3834670'. IN [min[..max]] defines the depth of the traversal, not specifying this option will use the default depth of 1. edgeCollection1, ..., edgeCollectionN is a list of all edge collections in use.
FOR v IN [min[..max]] ANY 'spec/3834670'
  edgeCollection1, ..., edgeCollectionN
  RETURN v._key

This is documented in the AQL Manual.


text:
Q: ArcGIS API for Python geometric filter of feature layer producing Runtime Error: 'geometry parameter invalid' I am trying to select a handful of features from an Enterprise Portal feature layer using the ArcGIS API for Python. Specifically I am trying to do a spatial selection, where the selected features are within a certain bounding box.
My code is based on the code snippets in the API reference documentation pages for the arcgis.features FeatureLayer query() function, the arcgis.geometry.filters module, and the arcgis.geometry Geometry and Polygon sections. Code is as follows (with exact names simplified for privacy reasons):
# Import Statements
from arcgis.gis import GIS
from arcgis.geometry import Geometry
from arcgis.geometry.filters import *
import arcpy

# Instantiate Connection to Portal
gis = GIS("portal_url", username="my_username")

# Get item from portal and set spatial reference
portalItem = gis.content.get('itemID')
portalLayer = portalItem.layers[0]
spatialReference = arcpy.SpatialReference(4326)

# Create a filter feature Geometry object
AOI = Geometry({
  "rings" : [[-108.46, 35.12],[-108.48, 35.12],[-108.48, 35.18],[-108.46, 35.18],
              [-108.46, 35.12]],
  "spatialReference" : {"wkid" : 4326} })

# construct a geometry filter using the filter geometry
AOI_geom_filter = intersects(AOI, spatialReference)

# query a feature layer for features that meet filter criteria
subset = portallLayer.query(geometry_filter=AOI_geom_filter, outfields='OBJECTID, LAT, LON')

This results in an error:
Unable to complete operation.
'geometry' parameter is invalid.
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-71-bb0dabd89dd0> in <module>
      9
     10 # query a feature layer for features that meet filter criteria
---> 11 NMparcels = parcelLayer.query(geometry_filter=AOI_geom_filter, outfields='OBJECTID, LAT, LON')

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\features\layer.py in query(self, where, out_fields, time_filter, geometry_filter, return_geometry, return_count_only, return_ids_only, return_distinct_values, return_extent_only, group_by_fields_for_statistics, statistic_filter, result_offset, result_record_count, object_ids, distance, units, max_allowable_offset, out_sr, geometry_precision, gdb_version, order_by_fields, out_statistics, return_z, return_m, multipatch_option, quantization_parameters, return_centroid, return_all_records, result_type, historic_moment, sql_format, return_true_curves, return_exceeded_limit_features, as_df, **kwargs)
    698
    699         params['returnCountOnly'] = True
--> 700         record_count = self._query(url, params, raw=as_raw)
    701         if 'maxRecordCount' in self.properties:
    702             max_records = self.properties['maxRecordCount']

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\features\layer.py in _query(self, url, params, raw)
   1397         """ returns results of query """
   1398         result = self._con.post(path=url,
-> 1399                                 postdata=params, token=self._token)
   1400         if 'error' in result:
   1401             raise ValueError(result)

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\_impl\connection.py in post(self, path, postdata, files, ssl, compress, is_retry, use_ordered_dict, add_token, verify_cert, token, try_json, out_folder, file_name, force_bytes, add_headers)
   1175                                          verify_cert=verify_cert, is_retry=True)
   1176
-> 1177                 self._handle_json_error(resp_json['error'], errorcode)
   1178                 return None
   1179

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\_impl\connection.py in _handle_json_error(self, error, errorcode)
   1196
   1197         errormessage = errormessage + "\n(Error Code: " + str(errorcode) +")"
-> 1198         raise RuntimeError(errormessage)
   1199
   1200 class _StrictURLopener(request.FancyURLopener):

RuntimeError: Unable to complete operation.
'geometry' parameter is invalid.
(Error Code: 400)

I've done the following testing to try to figure out why this is erroring (given that I'm following the example in the documentation very closely):

*

*Checked the geometry of the AOI object (polygon type, correct coordinates), including checking that the coordinates are listed in the correct format and order when creating the AOI object.

*Visualized portalLayer in a map - it appears as it should, and covers the AOI

*Ran a non-geometric query (where='OBJECTID<10') on portalLayer (worked as expected)

*Look at the result of AOI_geom_filter - it's a dictionary that seems reasonable, although the documentation pages linked above don't actually say what intersects() should output.

Can anyone see what's missing and leading to the error?
I'm working on the ArcGIS Jupyter Notebook environment (ArcGIS 10.7.1) on Windows 10. I did note that running arcgis.__version__ said I have Version 1.6.1 instead of Version 1.8.2 which is what the documentation webpages are for.

A: Found the solution a couple days later. In the line where I created the AOI Geometry item I was missing a set of brackets (added below). This meant that the array used to create the geometry was short a dimension. It was still recognizable as a polygon when I checked the type of the geometry, but the geometry filter and query had problems with it. The extra set of brackets makes more sense when one remembers that the Geometry item could have multiple polygons in one item.
AOI = Geometry({
  "rings" : [[[-108.46, 35.12],[-108.48, 35.12],[-108.48, 35.18],[-108.46, 35.18],
              [-108.46, 35.12]]],
  "spatialReference" : {"wkid" : 4326} })


text:
Q: How do I implement Map.getOrCreate? (object caching pattern) Often I find myself following this cache some object in a map pattern:
myMap = new Map<string, MyThing>;
getThing(key: string): MyThing {
  let thing = this.myMap.get(key);
  if (thing !== undefined) return thing;

  thing = new MyThing();
  this.myMap.set(key, thing);
  return thing;
}

I want to generalize this to something like:
getOrCreate(this.myMap, key, MyThing);

or
this.myMap.getOrCreate(key, MyThing);

Initial implementation idea:
export function getOrCreate<K, V>(map: Map<K, V>, key: K, objConstructor: () => V) {
  let v = map.get(key);
  if (v !== undefined) return v;

  v = objConstructor();
  map.set(key, v);
  return v;
}

*

*Am I re-inventing the wheel? Does TypeScript or the ES6 library already have something like this? (I don't see a method for this in Map)

*Also, I want to be able to pass a general function or an object constructor.
How do I determine if I need to execute new objConstructor() or just objConstructor()?
What would the objConstructor type be if the function supports both?
() => V | Constructor???() => V
Or should I pass in MyThing.constructor as an argument; will calling that be equivalent to new MyThing()?
Or maybe just if (objConstructor.constructor) new objConstructor();?

*Is it good practice to modify Map by defining Map.prototype.getOrCreate?

*If I were to modify Map.prototype, does that affect maps created with the native {} instead of new Map() or is that a different kind of Map?

EDIT: Issues with passing a constructor with a generic signature.
getOrCreate(myMap, key, AsyncSubject);

Argument of type 'typeof AsyncSubject' is not assignable to parameter of type '() => AsyncSubject'.

You can't do AsyncSubject<MyThing>, that's a syntax error.
AsyncSubject as any works, but is there a way to fix the getOrCreate signature and maintain type-checking?
This implementation passes type-checking:
export function getOrCreate<K, V>(map: Map<K, V>, key: K, constructor: ( () => V ) | Object) {
  let v = map.get(key);
  if (v !== undefined) return v;

  if (constructor instanceof Object) v = new (<any>constructor)();
  else v = constructor();
  map.set(key, v);
  return v;
}

Is using Object as a type like this good practice?
Of course () => new AsyncSubject<MyThing>() works, but this is verbose.
TypeScript 2.0.3


text:
Q: Spring Boot to access OAuth2 protected resources without using HttpSecurity? I would like to create a simple console spring boot application which should read an URL from terminal then print its data then again read another URL and print its data and so on till pressing CTRL + C. The grant type to be used should be client credentials; the client credentials should be the same for every URL and should be conveyed to the application at startup using the spring boot Externalized Configuration capabilities. After 1th URL read the access token used in the process should be reused for the subsequent URLs; when expired/invalidated the access token should be transparently renewed/re-generated (using the refresh token if provided by the authorisation server in the 1th place or again the client credentials grant type).
The 6.6 OAuth 2.0 Client with e.g. 12.5 WebClient for Servlet Environments seems to fit the need but require to configure HttpSecurity (see 6.6 OAuth 2.0 Client) which I don't need because I'm not creating a web application but kind of a curl utility.
How would one benefit the features provided by those without having to configure HttpSecurity?

A: you can consider postman is a console application without http security config. I think you need to create your own login to store the token and then put it into the header for each restful call.


text:
Q: Git status is not working correctly I don't think that my git status command is working correctly in this terminal session:
prompt> git add .

prompt> git status
On branch feature-api_sync
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   api_sync/README.md
    modified:   storm_tier/README.md

prompt> git commit -m "updated instructions"
[feature-api_sync 4c55c55] updated instructions
 2 files changed, 6 insertions(+), 2 deletions(-)

prompt> git status
On branch feature-api_sync
nothing to commit, working directory clean # <== HOW DO I SEE THAT I MADE 1 COMMIT???

But how do I see this:
prompt> git status
On branch master
Your branch is ahead of 'origin/master' by 14 commits.
  (use "git push" to publish your local commits)

nothing to commit, working directory clean

A: It's working completely correctly.  Do git log to see what happened in the past.

A: If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream-to=origin/<branch> feature-model_in_ruby


text:
Q: Python xPath looping for TR table rows but object empty Hi we are running this code and it is driving my crazy

*

*we capture a data table in table this works

*then grab all th and it's text in sizes this works

*then we want to grab all underlying rows in TR; and after loop over columns in rows : does not work! the color_rows object is always empty .. but when testing with xpath in the browser it does! work ... why? how?

My question is: how can I grab the tbody/tr's?
Expected flow

*

*loop over TR's

*Access, TR 1 by 1, get 1st TD

*Get all TD's data that have class form-control
 table = response.xpath('//div[@class="content"]//table[contains(@class,"table")]')
 sizes = table.xpath('./thead//th/text()').getall()[1:] #works!
 color_rows = table.xpath('./tbody/tr') #does not work! object empty
 for color_row in color_rows:
     color = color_row.xpath('/td[1]/b/text()').get().strip()
     print(color)
     stocks = color_row.xpath('/td/div[input[@class="form-control"]]/div//text()').getall()
     for size, stock in zip(sizes, stocks)

Our html data looks like this

            Colore
                S
                M
                L

                White
                <input type="hidden" name="data" value="3230/201">

                Avail:

                    <input name="cell" type="text" class="form-control">

179

                    <input name="cell" type="text" class="form-control">

360

etc etc

A: Apparently tbody tags are often omitted in HTML but aded by the browser.
In this case there was no (real) body tag making the xpath object miss!
And hence the troubles with xpath (if you really think the tbody tag is there)
Why do browsers insert tbody element into table elements?


text:
Q: Isses: Setting size of images I'm trying to set the size of images in the CSS file.
I set class for both images and try to change size in CSS.
But it's not letting me change size.
Code:

.social-icon{
  display: flex;
  justify-content: center;
}

.instagram .facebook{
  width:8%;
  length:8%;
  margin:5px 10px;
  min-width:5px;
}

A: I believe there is no CSS property called length, setting width and max-width is sufficient in this case to make the pictures smaller.
The main issue is that you were missing a comma between your two classes .facebook and .instagram, so effectively the browser is looking for .facebook element inside of .instagram.

.social-icon {
  display: flex;
  justify-content: center;
}

.instagram, .facebook {
  width:8%;
  margin:5px 10px;
  min-width:5px;
}


text:
Q: Using Solve to solve the equation $x^{1/3}=-1$ I am curious why this command returned no answers:
Solve[x^(1/3) == -1, x]

Gives this output:
(* {} *)

I was able to get around the problem with this:
Solve[Surd[x, 3] == -1, x]

Which returns:
(* {{x -> -1}} *)

But I still wonder why Solve[x^(1/3) == -1, x] does not return an answer.

A: I think the negative result of Solve and Reduce is correct, because the fractional power in question requires choosing a branch of the inverse function to $z\mapsto z^3$. The default in Mathematica is to put this cut along the negative real axis. This comes from the fact that the Arg function has that same cut, and that fractional powers 1/n of x are obtained from Abs[x]^(1/n) Exp[I Arg[x]/n].
Here is a plot of real and imaginary parts for the image of the standard cube root:
plot[f_] :=
 Module[{fn = f /. z -> x + I y},
  Show[ContourPlot[Im[fn], {x, -3, 3}, {y, -3, 3},
    ContourShading -> Automatic, ExclusionsStyle -> Red],
   ContourPlot[Re[fn], {x, -3, 3}, {y, -3, 3},
    ContourShading -> False, ContourStyle -> Blue,
    ExclusionsStyle -> Red], FrameLabel -> {"Re(z)", "Im(z)"},
   Background -> Lighter[Orange], PlotRangePadding -> 0,
   PlotLabel ->
    Framed[Grid[{{Style["-", Bold, Blue],
        "Real part"}, {Style["-", Bold, Gray], "Imaginary part"}},
      Alignment -> Left], FrameStyle -> None, Background -> White,
     RoundingRadius -> 5], ImageSize -> 300]]

plot[z^(1/3)]

The red line is the branch cut. The image does not contain the real number $-1$, as you can see by hovering over the contour lines for the real part.
This code is from another answer here.
Now we can also illustrate how a different branch can be chosen such that it contains the desired result:
arg[z_, σ_: - Pi] :=
  Arg[z Exp[-I (σ + Pi)]] + σ + Pi;

plot[Abs[z]^(1/3) Exp[I arg[z, 3 Pi/2]/3]]

The explanation for the arg function is in the above link. This image has $-1$ in it, as you can verify by hovering over it. In fact, you get
With[{z = -1}, Abs[z]^(1/3) Exp[I arg[z, 3 Pi/2]/3]]

(* ==> -1 *)

The above discussion is for inverse functions defined in the complex plane, whereas the new function Surd is defined only on the real axis. Solve works with Surd because effectively the branch cut is now moved off the real axis, similar to what I showed in the last plot. This is what is meant in the help docs for Surd when it says "on the negative axis, Surd is different from the principal root returned by Power."


text:
Q: Should branching of functions be tested if not part of the contract? Let's assume I have a method that performs an internal operation just the first time it gets called, e.g.:
class Foo {
  constructor() {
    this._unlocked = false;
    this._data = null;
  }
  bar() {
    if (!this._unlocked) {
      this._unlock();
    }
    ...
    return true;
  }
  _unlock() {
    performSomeUnlockOperation();
    this._unlocked = true;
  }
}

The contract of the bar method does not expose its internals, so it is enough to unit test it once per case, e.g.:
const foo = new Foo();
expect(foo.bar()).toReturn(true);

This way, the coverage tools would tell me that I skipped the if branch.
Is this a bad design smell?
From one side, it violates the single responsibility principle - bar is now doing two things, unlocking and its own stuff. Should I then wrap this object in a further external object that controls the unlock state? The point is that I do not want to expose the _unlock() call for external consumers all the time.
TL;DR what is the tradeoff between testability and API complexity in this case?
EDIT: the unlock operation is to request focus before reproducing audio via Web Audio API - i.e. to play a short 0 amplitude sample before playing the actual sound.

A: Tests should be useful. Coverage alone doesn't make a test useful or not, but incomplete coverage can hint at useful tests.
Viewed from the outside, that unlock mechanism may or may not matter – it depends. It would be perfectly fine if the "contract" for this class describes that the object has locked and unlocked states, if that is relevant. It's also perfectly fine if this is hidden from outside view. Then, the bar() operation would be expected to always succeed and sort out this unlocking internally.
But from the perspective of a developer working on this class, we might very well like white-box tests that explicitly cover this branch. The unlocked state that may be hidden from the outside is now very relevant. Tests that verify that the bar() operation works in all states of the objects could be useful.
Such developer tests tend to require a very testable design or deeper access into the internals, but this looks like JavaScript. Setting foo._unlocked = true from the outside is fairly fragile, but that might be a good tradeof if this test is valuable.
A more general pattern is to design APIs in two layers:
first a layer that contains the core logic and is easy to test,
and above that a thin layer that wraps this logic in a public API.
Here, your lower layer might implement a generic initialize-once object, so that the main object doesn't even need any branches.

A: If it is valid to test that a function works when it is called once, it is also valid to test that it works when it is called twice. And if you know that the internal behaviour on the second call is different, then it is common sense that there are bugs that only show up on the second call, or only on the first call. So it's absolutely fine to test it twice.
What if you don't? First, if the code of the function is changed, and bugs are introduced only on the codepath for the second call, your unit test wouldn't find it. Second, if your actual code calls the function twice and fails, you'll rely on the unit test and think the function is always correct, making it so much harder to find a bug.

A: How to test private members
Every private member that is useful, is used in some way by a public behavior of that class. To put it another way: if a private member's existence/value has zero impact on a class' public behavior in any way, then it can be safely removed.
Therefore, by fully testing your class' public behavior, you will invariably always be testing all useful private members. Since all other (and thus untested) private members can and should be safely removed, this means all your (remaining) private members will have been tested.
In your case:

*

*performSomeUnlockOperation could cause a change in state somewhere external to the class. That behavior can be tested, by mocking the object whose state gets altered and seeing if it was altered in the expected way.

*performSomeUnlockOperation could be changing the internal state of the class, which in turn causes its public behavior to change. That behavior (of performSomeUnlockOperation) can be tested by confirming that your class has the correct altered public behavior after having called performSomeUnlockOperation.

If performSomeUnlockOperation does not change any state external to the class, and only changes state internally in a way that does not change the public behavior of that class, then we can refer back to my initial point and conclude that performSomeUnlockOperation is useless and can be safely removed.

Should we test private branching logic?
No, not explicitly. We test public behavior. Private logic branching may be part of the implementation required to achieve the desired public behavior, but we do not test the implementation, we test the public behavior.
Take this simple example:
public class Calculator
{
    public int Add(int a, int b)
    {
        if(a < b)
            return a + b;
        else
            return (2*a + 2*b) / 2;
    }
}

Clearly, I've added a private logical branch that isn't necessary (the first option would work in all cases). The second option actually yields the same result, it just calculated it using a slightly different method.
The point I'm trying to get across here is that this class would pass any test that a more straightforward return a + b; implementation would also pass. The manner of implementation is irrelevant as far as the test is concerned. What matter is the public behavior, i.e. if the number that gets returned is actually the sum of the numbers that were given.

As a smaller aside, the SRP consideration is completely separate from this question, and there's not enough information in the question to answer that as well. There is not enough information here for me to conclude whether the unlocking functionality is a discrete responsibility or not.
And it doesn't really matter to the main question. If not part of the class itself, it's still a dependency that gets injected. The way of testing it will change, but what doesn't change is that your tests don't explicitly test private branching logic.


text:
Q: What happens after a method is called in Java This looks like a silly question but I found it is hard to get it right. I have asked different people but couldn't get an ideal answer.
I want to know what happens after we call a normal method in Java (Provided in a single threaded environment).
My understanding is that:

*

*All current stack variables are poped-up and stored somewhere (where?)

*The current method call halts

*The arguments of the newly called method are pushed to the stack

*The method code runs

*After the method finished running, the stack is again emptied and the old stack contents is again restored. (What happened if the function returns a value?).

*Code continues with the calling method.

This is a very incomplete and possibly wrong answer. Can someone provide a more detailed description?
Many thanks.

A: No, that's actually fairly accurate:
1) current stack variables remain on the stack
2) The current method pauses
3) The arguments of the newly called method are pushed to the stack
4) The method code runs
5) After the method finished running, we pop the stack.  The called method's stack variables are no longer valid - they no longer "exist" at this point.
6) We pass the return value (if any) to the caller
7) Code continues with the calling method.  All it's stack variables remain intact.
==============================
ADDENDUM:
@Kevin -

*

*Conceptually, I think you got it just about right.  I clarified a few points, I hope that helps.

*David Wallace's link is very good if you want to go in depth on how the JVM implements "method calling".

*Here is a good overview on how "a stack" works.  Any stack, calling any subroutine - not just Java:  http://en.wikipedia.org/wiki/Call_stack

*Finally, Marko Topolnik is correct.  "The reality" is almost always complex enough that it doesn't lend itself to a simple, one-size-fits all answer.  But I definitely think your understanding is good.  At least at the 10,000 foot level.
IMHO...

A: For the interpreter, assuming an instance method, and taking some minor liberties:

*

*The object pointer is used to reference the object, and from there the Class object.

*The method pointer is located in the Class object.  (The lookup to convert method name to method index was largely done when the class was loaded, so this is basically just an array index operation.)

*Generally some sort of a "mark" is pushed onto the JVM stack.  This would contain the caller's instruction pointer, and a pointer to the base of his stack.  (Lots of different implementations here.)

*The method's definition is consulted to see how many local vars are needed.  That many blank elements are pushed onto the stack.

*The object ("this") pointer is stored in local var 0, and any parms are stored in 1,2,3... as appropriate.

*Control is transferred to the called method.

On return, the stack is popped down to the point where the call started, any return value is pushed onto the stack, and control is transferred back to the caller.
Compiled code is conceptually similar, only it uses the "C" stack, and interpreted code in a JITC environment will make use of both the JVM stack and the "C" stack.


text:
Q: How does the desktop application of Google Drive work? I've seen all the demo videos on how google drive works but some things still don't make sense:

*

*I downloaded the app and the folder appears on my computer. Does it sync everything automatically or only things I drag in it? (So if I want to sync my whole 1GB Documents Folder, I drag (move, make shortcut, copy?) that folder in there? If I move it, the folder is no longer in my main directory, which I don't think is how it's supposed to work.

*If I add something to my Google Drive, it's downloaded onto my computer as well. So my 1GB folder is duplicated twice, one on my computer, one in the drives folder. (Isn't it supposed to be stored on Google's servers?)

*What's the point of the downloaded Google Drive app as compared to just using the web interface? The differences I see are: "Easier to drag and drop", "Duplicate data". Are these the only ones or do they serve different functions?
I'm still sort of confused, any explanations would be helpful, thanks

A: *

*Google Drive syncs automatically. Shortcuts won't do. If you add shortcut in your Drive folder, only the shortcut is synchronized, not the actually file. See this post to
know how you can make Google Drive your default documents folder.  However, you can use NTFS junctions to sync folders and files from outside your main google drive folder.

*The whole purpose of Drive is to provide users easy access to their files, wherever they are. That's why it syncs files to your computer. If you want something only online, use the selective sync feature. Right-click on tray icon > Preferences. In the dialog that opens, under Sync options, uncheck those folders which you don't want synced on your computer.

*As I said earlier, Google Drive makes your data accessible everywhere, always. Suppose you have some important file online and you don't have internet. What would you do? With Google Drive you would have the file on your computer as well. And if you make some changes in it, you won't have to manually upload the file once internet comes back. It's done automatically. Moreover, if you use Drive on your phone or on a different computer, you automatically have the updated file. This was one example, once you start using it regularly, you will find more uses.
Note If you want to check and make sure Google Drive is syncing (on Windows 7) look in the right corner of your tool bar. There should be a little yellow, green and blue triangle lighted up.


text:
Q: Flutter Firestore FieldValue.delete() crashes my app I am trying to delete a certain field from firestore when my user swipes 'delete' on my app. However, whenever I do this I either get the Errors:
Future<void> deleteItem(
  String location,
  String sellerName,
  String uid,
  String itemName,
) async {
   if (laCityList.contains(location)) {
      var data = {};
      data[uid] = {itemName: FieldValue.delete()};
      print('THis is in data: ${data}');
      await dbReference.collection('Items LA').document(location).updateData(data);
  }
}

Error:

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'

or If I do:
Future<void> deleteItem(
  String location,
  String sellerName,
  String uid,
  String itemName,
) async {
  if (laCityList.contains(location)) {
    Map<String, dynamic> data = {};
    data[uid] = {itemName: FieldValue.delete()};
    print('THis is in data: ${data}');
    await dbReference
        .collection('Items LA')
        .document(location)
        .updateData(data);
  }
}

Error:

Lost Connection to Device

My firestore is structured as:
Items -> City -> {UserId: {ItemName : {ItemInformation}}

I am wondering what I am doing wrong and would love to have your help
Thanks


text:
Q: creating an object from an alphabetically sorted array where keys are the first letters and values are the strings I've been trying to get an object output from an alphabetically sorted array.
For example, if I have arr = ['anger', 'apple', 'bowl', 'cat']
then I want my object to be like obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}
So far I have this, but it's not working properly.
const p4 = function (arr) {
  let val = {};
  const sortArr = arr.sort();
  for (let i = 0; i < sortArr.length; i++) {
    for (let j = i; j < sortArr.length; j++) {
      if (sortArr[i].charAt(0) == sortArr[j].charAt(0)) {
          val.sortArr[j].charAt(0) =sortArr[j] ;
      }
    }

    return val;
  }
};

A: You can use reduce:

let arr = ['anger', 'apple', 'bowl', 'cat']

const result = arr.reduce((a, b) => {
  let c = b.charAt(0);
  if (a[c]) {
    a[c].push(b)
  } else {
    a[c] = [b];
  }
  return a;
}, {})

console.log(result)

A: In the code:
let val = {};
  const sortArr = arr.sort();

sort sorts in place and returns the sorted array, so sortArr and arr both reference the same (sorted) array. You could just do:
  arr.sort()

and use arr in the following instead of sortArr.
  for (let i = 0; i < sortArr.length; i++) {
    for (let j = i; j < sortArr.length; j++) {

There is no need to process the array twice. All you need to do is:

*

*Iterate over each value in the array

*Get the first letter of the value

*If the val object doesn't have a property with that name, create it and assign an array to the value

*Push the string into the val[char] array

E.g.

function arrToObj(arr) {
  arr.sort();
  let result = {};
  for (let i=0, c; i<arr.length; i++) {
    c = arr[i].substr(0,1);
    if (!result[c]) {
      result[c] = [];
    }
    result[c].push(arr[i]);
  }
  return result;
}

let arr = ['anger', 'apple', 'bowl', 'cat']

console.log(arrToObj(arr));

You can also do the same thing with reduce:

let arr = ['anger', 'apple', 'bowl', 'cat']

let obj = arr.sort().reduce((acc, v) => {
  let c = v.substr(0,1);
  if (!acc[c]) acc[c] = [];
  acc[c].push(v);
  return acc;
}, {});

console.log(obj);


text:
Q: How can i print the screenshot of a page to a bluetooth printer Am currently using srehanuddin Cordova-Plugin-Bluetooth-Printer. I first take the screenshot of the page, save its URI in base64 try to print that data bUT THE PRINTER(Jingpu Bluetooth printer) seems not to interprete the data, because it prints some stuff that cannot be read. How can i take the screen and then print it?
Here is my code,
 printScreenShot() {
let alert = this.alertCtrl.create();
alert.setTitle('Print');
alert.addInput({
  type: 'radio',
  label: 'Bluetooth',
  value: 'bt'
});
alert.addInput({
  type: 'radio',
  label: 'Other',
  value: 'other'
});

alert.addButton('Cancel');
alert.addButton({
  text: 'OK',
  handler: data => {
    console.log(data);
    if (data == 'bt') {
      this.printVisible = false;
      this.backVisible = false;
      this.screenshot.URI(80).then(res => {
        console.log(res);
        console.log(res.URI);
        this.printBluetooth(res.URI);
      }, err => {
        this.printVisible = true;
        this.backVisible = true;
      });
    } else {
      this.backVisible = false;
      this.printVisible = false;
      this.screenshot.URI(80).then(res => {
        this.printOther(res.URI);
      }, err => {
        this.printVisible = true;
        this.backVisible = true;
      });
    }
  }
});
alert.present();

}
 printBluetooth(URI) {
BTPrinter.list(data => {
  console.log(data);
  if (data) {
    let alert = this.alertCtrl.create();
    alert.setTitle('Paired Devices');
    for (let device of data) {
      alert.addInput({
        type: 'radio',
        label: device,
        value: device
      });
    }

    alert.addButton('Cancel');
    alert.addButton({
      text: 'OK',
      handler: data => {
        this.printBt(URI, data);
      }
    });
    alert.present();
  } else {
    this.global.toast('Error occured', 'toast-error');
    this.backVisible = true;
    this.printVisible = true;
  }
})

}
printBt(URI, mac) {
console.log(mac);
let loader_send_1 = this.global.presentLoader('Sending ...');
loader_send_1.present();
BTPrinter.connect(function (mac) {
  console.log(mac);
  BTPrinter.print(function (data) {
    console.log("Success");
    console.log(data)
  }, function (err) {
    console.log("Error");
    console.log(err)
  }, URI)

}, function (err) {
  this.global.toast(err, 'toast-error');
  console.log(err)
}, mac);

}
<button (click)="printScreenShot()" ion-fab>


text:
Q: GMail API Grant Permissions Before UserRecoverableAuthUIException I've followed the quickstart example from Google to setup the GMail API: https://developers.google.com/gmail/api/quickstart/android
My app successfully requests the GET_ACCOUNTS permission and allows the user to select his/her gmail account. The selected account is saved in SharedPreferences for later access.
Through an IntentService, my app sends an email. I have followed the instructions located here: https://developers.google.com/gmail/api/guides/sending and included the activation.jar, additional.jar, and mail.jar libraries as needed. When I send the email with the below code, I get a UserRecoverableAuthUIException:
message = service.users().messages().send(userId, message).execute();

When I catch the exception, get the intent stored with the exception, and start the intent as a new activity, I am shown a dialog giving me the chance to allow my app to send email with my GMail account:

After pressing 'Allow' on this dialog, my app sends emails without any further issues. My app also appears on my Google account's permissions page online saying it has permission to send email.
Is there a way to manually trigger this dialog when I first acquire the user's account name rather than waiting for the exception to occur?
UPDATE
I have been able to extract the action and data stored in the intent if that helps any:

*

*action: com.google.android.gms.ui.UNPACKING_REDIRECT

*data: intent://com.google.android.gms.auth.uiflows.common/KEY

where KEY is a series of characters, probably linked to my account or are a token.
EDIT:
The following is the code to create the Credentials object and starting the account picker activity which I'm using:
private GoogleAccountCredential mCredential;
private static final String[] SCOPES = { GmailScopes.GMAIL_COMPOSE };

Inside constructor:
mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

Where I get the account:
private void chooseGMailAccount() {
        String accountName = this.getSharedPreferences(getString(R.string.shared_pref_main),
                Context.MODE_PRIVATE)
                .getString(getString(R.string.srd_pref_gmail_account), null);
        if (accountName != null) {
            mCredential.setSelectedAccountName(accountName);
            configureGMailAPI();
        } else {
            startActivityForResult(
                    mCredential.newChooseAccountIntent(),
                    REQUEST_ACCOUNT_PICKER);
        }
    }

A: You could try to add a few permissions to your manifest
<uses-permission android:name="com.google.android.gm.permission.WRITE_GMAIL" />
<uses-permission android:name="com.google.android.gm.permission.AUTO_SEND" />

And it should still need oAuth for user authentication but will allow the intent automatically these permissions ...
Haven't tested it but it might work

A: Try to send a mail while registration i.e after user choose account. At this point it will catch exception, once u get this exception show this pop up. After this user is good to go. I guess there is no direct way to trigger this pop up. As per developers.google.com/drive/android/auth. Authorization happens in response to receiving an error when sending a request. Your app must be prepared to catch the UserRecoverableAuthIOException. This means the user needs to authorize the app. Until your app is authorized by user, your app can't do anything.

A: To request the "managing drafts and sending emails" permission when the user is choosing an account, include GmailScopes.GMAIL_COMPOSE in the scopes when building GoogleAccountCredential.
   import com.google.api.services.gmail.GmailScopes;

   String[] SCOPES = { GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_LABELS };
   int REQUEST_ACCOUNT_PICKER = 1001;

   GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());

   startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);

See the Gmail API Javadoc for a list of scopes.


text:
Q: Finding a value of a function continuous at an other point
Let $f : \mathbb{R}\to\mathbb{R}$ be a function which is continuous at $0$ and $f(0) = 1$.
  Also assume that $f$ satisfies the following relation for all $x$:
  $$f(x) − f\left(\frac x2\right) = \frac{3x^2}4+x$$
  Find $f(3)$.

(I'm unable to even start.. any hint is appreciated)

A: $f(x)-f(x/2)=3x^2/4 +x$
$f(x/2)-f(x/4)=3x^2/16 +x/2$
$f(x/4)-f(x/8)=3x^2/64 +x/4$
$\cdot$
$\cdot$
$\cdot$
$f(x/2^n)-f(x/2^{(n+1)})=3x^2/2^{(2n+2)} +x/2^n$
Now as $n \rightarrow \infty$ , we get,
$f(x) - f(0) = \frac{3x^{2}(1+1/4+...)}{4} + x(1+1/2+1/4+....)$
$f(x)-1=x^2 +2x$
$f(x)= (x+1)^2$
$f(3)=16$


text:
Q: getting an undefined variable error in firebug Well, I am running the following function in my code and wondering why getting an error in Firebug which is as follows:
function TestSurvey(UniqueID, PhontTypes) {

            if(typeof(PhontTypes) != "undefined")
                PhontTypes = "4";

            if (PhontTypes.match("5"))
            {
                window.location = some url location here...
            }
            else
            {
                window.location = some url location here...
            }

    }

The error I am getting in firebug is as follows:
TypeError: PhontTypes is undefined

if (PhontTypes.match("5"))

A: The typeof condition seems to be inverted. It's currently limiting PhontTypes to be only undefined or "4" -- nothing else.
To have it replace undefined with a "default" value of "4", it should check for equality (== or ===) instead:
// if currently `undefined`, set default
if(typeof PhontTypes == "undefined")
    PhontTypes = "4";

Or, since the next line expects String.prototype.match() to be available, you might replace all values that aren't Strings:
if (typeof PhontTypes != "string")
    PhontTypes = "4";


text:
Q: What does this mean in lme4: function 'dataptr' not provided by package 'Rcpp' I'm  trying to do LMM using lme4, and this message pops up:
Error in initializePtr() :
  function 'dataptr' not provided by package 'Rcpp'
What should I do?

A: After a while, I got it.
1) Reinstall the latest version of Rcpp is the solution.
2) If you are not using lme4, but you also have this problem ("function 'dataptr' not provided by package 'Rcpp'") in combination with dyn.load(), it might be worth noting do not forget to include

library(Rcpp)

or

require(Rcpp)

on your code before

dyn.load("your_shared_lib.so")

Source:
building_shared_libs_with_Rcpp


text:
Q: Обновление данных на форме WinAPI Как можно обновлять текст в Edit Control прямо из потока?
У меня не получается, можете подсказать в чем проблема?
Запуск потока:
        case IDC_START:
        {
            hThread = CreateThread(NULL, 0, Add, (void*)0, 0, &ID_THREAD1);

            WaitForSingleObject(hThread, INFINITE);
            MessageBox(hwnd,"","",MB_OK);
            CloseHandle(hThread);

            return FALSE;
        }break;

И функция которая в потоке изменит Edit Control
DWORD WINAPI Add(LPVOID p)
{
    PostMessage(hLog, WM_SETTEXT, 0, (LPARAM)"asdsadsadadasdasd");
    return 0;
}

Много чего перепробовал, но не помогло.
P.S да, знаю, что PostMessage это асинхронный способ поставить сообщение в очередь для его исполнения без задержек, но я не так что-то понимаю, ведь по аналогии с SendMessage должно работать...
Спасибо!

A: Сообщение WM_SETTEXT должно отправляться синхронно.

If you send a message in the range below WM_USER to the asynchronous
  message functions (PostMessage, SendNotifyMessage, and
  SendMessageCallback), its message parameters cannot include pointers.
  Otherwise, the operation will fail. The functions will return before
  the receiving thread has had a chance to process the message and the
  sender will free the memory before it is used.

Вообще не вижу смысла использовать WM_SETTEXT, если есть SetWindowText()
Но если очень хочется асинхронности, то:
#define WM_MY_COOL_MESSAGE WM_USER + 123

case WM_MY_COOL_MESSAGE:
   char* msg = (char*)lParam;
   SetWindowTextA(hLog, msg);
   free(msg);

DWORD WINAPI Add(LPVOID p)
{
    PostMessage(hwnd, WM_MY_COOL_MESSAGE, 0, (LPARAM)strdup("asdsadsadadasdasd"));
    return 0;
}


text:
Q: How to apply a schema from an existing DataFrame to another DataFrame with missing columns in PySpark I have a JSON file with various levels of nested struct/array columns in one DataFrame, df_1. I have a smaller DataFrame, df_2, with less columns, but the column names match with some column names in df_1, and none of the nested structure.
I want to apply the schema from df_1 to df_2 in a way that the two share the same schema, taking the existing columns in df_2 where possible, and creating the columns/nested structure that exist in df_1 but not df_2.
df_1
root
 |-- association_info: struct (nullable = true)
 |    |-- ancestry: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- doi: string (nullable = true)
 |    |-- gwas_catalog_id: string (nullable = true)
 |    |-- neg_log_pval: double (nullable = true)
 |    |-- study_id: string (nullable = true)
 |    |-- pubmed_id: string (nullable = true)
 |    |-- url: string (nullable = true)
 |-- gold_standard_info: struct (nullable = true)
 |    |-- evidence: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- class: string (nullable = true)
 |    |    |    |-- confidence: string (nullable = true)
 |    |    |    |-- curated_by: string (nullable = true)
 |    |    |    |-- description: string (nullable = true)
 |    |    |    |-- pubmed_id: string (nullable = true)
 |    |    |    |-- source: string (nullable = true)
 |    |-- gene_id: string (nullable = true)
 |    |-- highest_confidence: string (nullable = true)

df_2
root
 |-- study_id: string (nullable = true)
 |-- description: string (nullable = true)
 |-- gene_id: string (nullable = true)

The expected output would be to have the same schema as df_1, and for any columns that don't exist in df_2 to just fill with null.
I have tried completely flattening the structure of df_1 to join the two DataFrames, but then I'm unsure how to change it back into the original schema. All solutions I've attempted so far have been in PySpark. It would be preferable to use PySpark for performance considerations, but if a solution requires converted to a Pandas DataFrame that's also feasible.

A: df1.select('association_info.study_id',
           'gold_standard_info.evidence.element.description',
          'gold_standard_info.gene_id')

The above code will reach into the df1 and provide you requisite fields in df2. The schema will remain same.
Could you try the same.


text:
Q: Output of the table in div class
$resultSet = mysql_query("SELECT * FROM news ORDER BY id DESC LIMIT 7");
$product_count = mysql_num_rows($resultSet);
   if($product_count >0){

    while( mysql_fetch_array($resultSet)){
        $id= $row["id"];
        $cat= $row["categories"];
        $title= $row["title"];
        $image= $row["image"];
        $txt= $row["txt"];
        $res= $row["resource"];

        }
   }
     else
        { echo'site is under maintaince ';}

       echo "

        '$cat'

'$title'

$txt

By ' $res'  |  '$date'  |  15 comments

";
   ?>

The code is not showing the output results of the table. Can you tell me what I am doing wrong? I want to show the output in the div class. My paging is working correctly, but it is not showing the output correctly. Can you guide me? I will really be grateful.

A: while( mysql_fetch_array($resultSet)){
        $id= $row["id"];
        $cat= $row["categories"];
        $title= $row["title"];
        $image= $row["image"];
        $txt= $row["txt"];
        $res= $row["resource"];

        }
   }

Where is $row in the lopp? However, to populate all the results, you need the printing inside the loop, otherwise you won't get them iterated


text:
Q: Monitoring SLA/SLO/SLI using Prometheus I have done much research about monitoring SLI metrics with Prometheus. I have found only how to monitor a cluster using Kubernetes. I'm hoping to find a response here for  simple monitoring.
I also want to know which is better for that using the R.E.D(rate,error,duration) method or the U.S.E(utilization,saturation,errors) method?
If possible give some examples(like : 1-clamp_max(sum(rate(wmi_cpu_interrupts_total[2m])),1))
For the 4 most standard metrics: CPU/DISKs/Networking/Memory


text:
Q: ReferenceError uppy is not defined Error image
I implement shrine gem with cropperjs and uppy in rails,
I refer to Usage of shrine Image Cropping and Example code
Then I implemented  code, seemingly code is correct,
But I got some errors Module not found: Error: Can't resolve 'cropbox' 2
  and above errors,
I searched similar issues and tried some solutions still I can't use shrine gem,
Would you like to help me?
application.js:
//= require popper
//= require bootstrap-sprockets
//= require_tree .

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

function fileUpload(fileInput) {
 var formGroup = fileInput.parentNode
 var hiddenInput = document.querySelector('.upload-data')
 var imagePreview = document.querySelector('.image-preview img')

formGroup.removeChild(fileInput)

 var uppy = Uppy.Core({
    autoProceed: true,
    restrictions: {
     allowedFileTypes: fileInput.accept.split(','),
    }
   })
  .use(Uppy.FileInput, {
    target: formGroup,
    locale: { strings: { chooseFiles: 'Choose file' } },
   })
  .use(Uppy.Informer, {
    target: formGroup,
   })
  .use(Uppy.ProgressBar, {
    target: imagePreview.parentNode,
  })
  .use(Uppy.ThumbnailGenerator, {
    thumbnailWidth: 600,
  })
  .use(Uppy.XHRUpload, {
    endpoint: '/upload',
  })

uppy.on('upload-success', function (file, response) {
  imagePreview.src = response.uploadURL

  var uploadedFileData = JSON.stringify(response.body['data'])

  hiddenInput.value = uploadedFileData

  var copper = new Cropper(imagePreview, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    crop: function (event) {
    data = JSON.parse(hiddenInput.value)
    data['metadata']['crop'] = event.detail
    hiddenInput.value = JSON.stringify(data)
     }
    })
  })
}

 document.querySelectorAll('input[type="file"]').forEach(function (fileInput) {
  fileUpload(fileInput)
})

cropbox.js:
import 'cropperjs/dist/cropper.css';

import Cropper from 'cropperjs'

function cropbox(image, url, { onCrop }) {
 image.src = url

   new Cropper(image, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    zoomable: false,
    crop: event => onCrop(event.detail)
  })
}

export default cropbox

fileUpload.js:
import cropbox from 'cropbox'

  uppy.on('upload-success', (file, response) => {
   // retrieve uploaded file data
    const uploadedFileData = response.body['data']

    // set hidden field value to the uploaded file data so that it's submitted
    // with the form as the attachment
    hiddenInput.value = JSON.stringify(uploadedFileData)

    cropbox(imagePreview, response.uploadURL, {
      onCrop(detail) {
        let fileData = JSON.parse(hiddenInput.value)
        fileData['metadata']['crop'] = detail
        hiddenInput.value = JSON.stringify(fileData)
      }
    })
  })

form.html.erb:
<%= form_with model: @blog_form , url: user_blogs_path ,local: true do |f| %>

  <%  f.label :title %>
  <%= f.text_field :title %>

<%  f.label :content %>
<%= f.text_area :content %>

<%  f.label :user_id %>
<%= f.hidden_field :user_id, value: current_user.id %>

<%= f.fields_for  :photos, Photo.new do |photos_fileds|  %>

<%= photos_fileds.label :image , class: "form-control" %>
<%= photos_fileds.hidden_field :image,  class: "upload-data", value:
photos_fileds.object.cached_image_data %>
<%= photos_fileds.file_field  :image , class: "form-control  ", id: "select-files"%>

<img id="image" src="<%= photos_fileds.object.image_url(:medium) %>" height="300" class="rounded"  >

<% end %>

  <%= f.submit "create", class: "btn btn-primary" %>
 <% end %>

application.html.erb:
  <!DOCTYPE html>

    <title>Prottype2</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

   <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= javascript_pack_tag 'application' %>
   <%= javascript_pack_tag 'cropbox' %>
   <%= javascript_pack_tag 'fileUpload'%>

   <link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css" rel="stylesheet" />
   <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" rel="stylesheet"
 />

<%= notice %>

<%= alert %>

   <%= yield %>

I moved code position
application.html.erb:

<link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css"
rel="stylesheet" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"
rel="stylesheet" />

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track':
 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track':
'reload' %>
<%= javascript_pack_tag 'application' %>
<%= javascript_pack_tag 'app' %>
<%= javascript_pack_tag 'cropbox' %>
<%= javascript_pack_tag 'fileUpload'%>

And also I moved file input application.js to app.js

A: I solved this error, I refered to Shrine example in Rails
I just forgot the details of code in fileUpload.js


text:
Q: What's the doorbell in InfiniBand? I am reading a document ablut InfiniBand, which is called 《InfiniBand™ Host Channel Adapter Verb Implementer's Guide》--Intel, in Chapter 6.2.2, it mentions a concept called "Doorbell", I haven't found any information about this concept in the IB specification. I wonder if the doorbell is a notification mechnism or something else? Is there something detail about it?
Thank you!

A: The definition is two sections further up under 6.2:

Protection domain is used as a form of access security for memory regions, address vectors and queue pairs as defined by the InfiniBand Architecture. The Architecture requires a protection domain before a QP is allocated. Most vendors who expect to support user mode IO, will have a form of notification handshake from user mode. In most HCA's this is a device memory address mapped to the process address space. We call this address the "doorbell" in this document.

CTRL-F is your friend...


text:
Q: Java hibernate JPA error with JUnit Testing I am using hibernate in my Java EE application in combination with my Wildfly server to persist my Classes in a mysql Database.
So far this works fine but now I am writing unit tests and I am getting crazy about some error which I get.
I would like to test my DAO-Layer in my Unit-Tests but I get these errors:
Caused by: org.hibernate.engine.jndi.JndiException: Error parsing JNDI name [java:/MySqlDS]
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

my persistence.xml ist this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="primary">
        <jta-data-source>java:/MySqlDS</jta-data-source>
        <class>org.se.bac.data.Employee</class>
        <properties>
            <!-- Properties for Hibernate -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
                    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
            <property name="hibernate.connection.username" value="student"/>
            <property name="hibernate.connection.password" value="student"/>

            <!--
                SQL stdout logging
            -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="use_sql_comments" value="true"/>
        </properties>
    </persistence-unit>

</persistence>

So, Here I am using a jta-data-source> as you can see.
If I remove this line my tests are going fine! But I can not build my project with maven anymore.
Error:
    Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
    Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver"}}

He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application. The tests and of course the maven build?
Here is my test: (Setup is already causing the error):
package org.se.bac.data.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.se.bac.data.model.Employee;

public class EmployeeDAOTest
{
    private static final JdbcTestHelper JDBC_HELPER = new JdbcTestHelper();
    private final static JpaTestHelper JPA_HELPER = new JpaTestHelper();

    private EntityManager em = JPA_HELPER.getEntityManager("primary");
    private EmpDAO dao;

    @BeforeClass
    public static void init()
    {

        JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
        JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
    }

    @AfterClass
    public static void destroy()
    {
        //JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
    }

    @Before
    public void setUp()
    {
        JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
        JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
        dao = new EmpDAOImpl();
        dao.setEm(em);

        JPA_HELPER.txBegin();

        Employee emp2 = new Employee();
        emp2.setFirstname("Max");
        emp2.setLastname("Muster");
        emp2.setHiredate("23-12-1991");

        dao.insert(emp2);
    }

And JPAHELPER Class:
package org.se.bac.data.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JpaTestHelper
{
    /*
     * Property: persistenceUnitName
     */
    private String persistenceUnitName;
    public String getPersistenceUnitName()
    {
        return persistenceUnitName;
    }
    public void setPersistenceUnitName(String persistenceUnitName)
    {
        if(persistenceUnitName == null || persistenceUnitName.length() == 0)
            throw new IllegalArgumentException("Illegal parameter persistenceUnitName = " + persistenceUnitName);
        this.persistenceUnitName = persistenceUnitName;
    }

    /*
     * Get an instance of the EntityManagerFactory.
     */
    protected EntityManagerFactory getEnityManagerFactory()
    {
        if(persistenceUnitName == null)
            throw new IllegalStateException("PersistenceUnitName must be set!");
        return Persistence.createEntityManagerFactory(persistenceUnitName);
    }

    /*
     * Manage an EntityManager.
     */

    private EntityManager em;
    public EntityManager getEntityManager()
    {
        if(em == null)
        {
            em = getEnityManagerFactory().createEntityManager();
        }
        return em;
    }
    public EntityManager getEntityManager(String persistenceUnitName)
    {
        setPersistenceUnitName(persistenceUnitName);
        return getEntityManager();
    }

    public void closeEntityManager()
    {
        if(em != null)
            em.close();
    }

    /*
     * Handle Transactions
     */

    protected void txBegin()
    {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
    }

    protected void txCommit()
    {
        EntityTransaction tx = em.getTransaction();
        if(tx.getRollbackOnly())
        {
            tx.rollback();
        }
        else
        {
            tx.commit();
        }
    }

    protected void txRollback()
    {
        EntityTransaction tx = em.getTransaction();
        tx.rollback();
    }
}

and my DAO:
package org.se.bac.data.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.se.bac.data.model.Employee;

class EmpDAOImpl // package private
        implements EmpDAO
{
    @PersistenceContext
    private EntityManager em;

    /*
     * CRUD methods
     */

    public Employee findById(int id)
    {
        System.out.println("empdaoimpl ID " + id);
        return em.find(Employee.class, id);
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

}

Wildfly Datasource:
   <datasources>
            <datasource jta="true" jndi-name="java:/MySqlDS" pool-name="MySqlDS" enabled="true" use-ccm="false">
                <connection-url>jdbc:mysql://localhost:3306/empdb?useSSL=false</connection-url>
                <driver-class>com.mysql.jdbc.Driver</driver-class>
                <driver>mysql-connector-java-5.1.44-bin.jar_com.mysql.jdbc.Driver_5_1</driver>
                <security>
                    <user-name>student</user-name>
                    <password>student</password>
                </security>
                <validation>
                    <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                    <background-validation>true</background-validation>
                    <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
                </validation>
            </datasource>
        </datasources>

A:
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application.

The problem is that the data source is managed by Wildfly which is not available on your test environment. So what you could do is define two separate persistence units (one for your production code and the other for the test) as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="primary">
        <jta-data-source>java:/MySqlDS</jta-data-source>

        <properties>
            <!-- Properties for Hibernate -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />

            <!--  SQL stdout logging -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="use_sql_comments" value="true"/>
        </properties>
    </persistence-unit>

    <persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
        <class>org.se.bac.data.Employee</class>
        <properties>
            <!-- Properties for Hibernate -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
            <property name="hibernate.connection.username" value="student"/>
            <property name="hibernate.connection.password" value="student"/>

            <!--   SQL stdout logging  -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="use_sql_comments" value="true"/>
        </properties>
    </persistence-unit>

 </persistence>

and then in your EmployeeDAOTest class modify the following line as:
private EntityManager em = JPA_HELPER.getEntityManager("testPU");

Note:

*

*I removed the JDBC connection properties from the primary persistence unit because you don't need them as you already have the data source there on Wildfly.


text:
Q: Desplegable no muestra la opción por defecto seleccionada Tengo un desplegable y no me muestra la opción predeterminada ni seleccionada. Me he basado en páginas de ejemplo como esta o esta y a ellos cuando está plegado les muestra su primera opción.
No entiendo porque pasa, ¿puede ser porque yo paso de manera dinámica con django las opciones del desplegable?
Me gustaría que se mostrase la opción seleccionada para luego con ´jquery´ poder trabajarla.
EDIT Veo que aquí el snippet si que lo hace, pero cómo muestro en mi imagen no. Solo se ve en el desplegable pero no en el principal(el de arriba)...

Gracias

<select>
  {% for node in Last_val_nodes %}
    <option selected class="black_font">{{node.0}}</option>
  {% endfor %}
</select>

A: Por defecto al aplicar un select, estará seleccionado el primer elemento, pero lo estás utilizando de manera equivocada, al poner node.0 no lo reconoce y por eso sale en blanco.
Lo correcto sería:
<select>
  {% for node in Last_val_nodes %}
    <option selected class="black_font">{{node.nombre}}</option>
  {% endfor %}
</select>

Tomando el atributo que deseas mostrar, en este caso puse nombre, podrías incluso no poner el atributo deseado, solo {{node}}, siempre y cuando dentro de tu modelo tengas el método __str__
def __str__(self):
        return self.nombre #O el elemento a mostrar


text:
Q: nodejs express jade mongodb project: how to import include chart.js I am new with this and I am using Intellij as my editor for a project with nodejs, mongodb, express and jade/pug viewing engine. I need to view my data in a graph and decided to use chart.js. I can already access and view my data in a table but I want to show it in a graph.
Can someone help me understand how to include the chart.js file in the project. I have already npm installed it and it shows in my terminal, but how do I access this in the project. I have tried different things like including it as you do in a browser file or passing the exact directory link but maybe I am not understanding this. Please help!
Thanks!
Here are the files I have, most of it is default, I have made very minor edits only to fetch and display the data from a remote mongodb, where and how should I include the chartjs stuff. I tried the CDN method but I think I am not placing the link in the right place:
app.js is as:
    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');

    //New Code to connect remote Mongodb -Sg
    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('username:passwd@ipaddress:27017/default',
              {authSource:'admin'});

    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');

    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');

    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    // Make our db accessible to our router -Sg
    app.use(function(req,res,next){
         req.db = db;
         next();
    });

     app.use('/', indexRouter);
     app.use('/users', usersRouter);

     // catch 404 and forward to error handler
     app.use(function(req, res, next) {
       next(createError(404));
     });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });

    module.exports = app;

index.js is as:
    var express = require('express');
    var router = express.Router();

    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });

/* GET envlist page. */
     router.get('/envlist', function(req, res) {
         var db = req.db;
         var collection = db.get('LORA_Sensor');
         collection.find({},{},function(e,docs){
            res.render('envlist', {
                 "envlist" : docs
            });
        });
     });

     module.exports = router;

envlist.pug file is as:
     extends layout

     block content

         h1
            Environment Parameter List

        ul
             p Co2
             each envparam, i in envlist

                li
                    p= envparam.Co2

new envlist.pug with just a graph using static data is below
    extends layout

    block content

        canvas#myChart
        script.
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
           type: 'line',
           data: {
              labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
              datasets: [{
                label: 'apples',
                data: [12, 19, 3, 17, 6, 3, 7],
                backgroundColor: "rgba(153,255,51,0.4)"
            }, {
                label: 'oranges',
                data: [2, 29, 5, 5, 2, 3, 10],
                backgroundColor: "rgba(255,153,0,0.4)"
            }]
        }
    });

layout.pug:
      doctype html
       html
        head
          title= title
          link(rel='stylesheet', href='/stylesheets/style.css')
          script(src='https://cdnjs.com/libraries/Chart.js')
        body

       block content

A: Try the CDN method by adding this to the layout.pug anywhere in the head section:
script(src='https://cdnjs.com/libraries/Chart.js')

Take a look at this question to see more details on how to reference chartjs as a local file from node_modules.
CDN is a lot easier to configure and will also be more economical as your server won't bear the load of serving the library to your users.