text:
Q: Matlab: Create fan-shaped scatter plots Fan-shaped scatter plot:

I need to generate fan-shaped scatter plots (like the one linked) with correlations between 0.1 and 0.9. So far, I've just added a cluster of dots at the right end of the plot, but this doesn't look that great and I cannot introduce enough variation to get down to a 0.1 correlation. I can only use 100 data points and the data must fall in the range of 0 - 100 in x and y values. Ideally, I want to be able to control the variation of the data points and/or the angle the fan-shape scatter plot forms. Any suggestions?
segment = linspace(0,10,33);
cluster = normrnd(10,2,1,67);
x = [segment, cluster]';
y = 2.*x + 1;
errors = [[normrnd(0, 4, length(segment), 1)]', [normrnd(0,9,length(cluster),1)]']'; %row vectors
y = y + errors;
figure
scatter(x,y)


text:
Q: C++ - Cast/Change-type of an unique_ptr Edit: Thanks, amazing help, as always :)
I can't find the solution to this, I have an unique_ptr to a base class, that has the data of a derived class, and I want to set it's type to the derived class so I can access the derived members. See this code:
#include <memory>
#include <iostream>

class Base
{
public:
    int v1 = 0xAAAAAAAA;
};

class Derived : public Base
{
public:
    int v2 = 0xBBBBBBBB;
};

int main()
{

    std::unique_ptr<Base> b1(new Derived); //How to access b1->v2 ?
    std::unique_ptr<Base> b2(new Base);

    std::getchar();
    return 0;
}

The type of b1 is Base but it's data contains the data of Derived.
See:

Is it hard to get ? I thought about manipulating memory bytes, like saying [b1+4] (pseudo thoughts) and accessing it, but I think about complicated objects, because I'm doing an entity system for a game, I can't do this :(
Thanks !

A: Your options are:
1) Cast C-like pointer (recommended)
std::unique_ptr<Base> b2(new Base);
Derived * p = static_cast<Derived *>(b2.get());

2) Implement your own static_unique_ptr_cast where you delete b1 and create a new std::unique_ptr:
template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del>
static_unique_ptr_cast(std::unique_ptr<Base, Del> && p)
{
    auto d = static_cast<Derived *>(p.release());
    return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
}

The function takes rvalue reference to ensure you're not stealing the resource from lvalue. Usage:
std::unique_ptr<Base> b1(new Derived);
std::unique_ptr<Derived> p = static_unique_ptr_cast<Derived>(std::move(b1));

Note: If you think you need to use 2) I would consider your design being flawed. The cast is not in the STL for some reason.
Edit: The static_unique_ptr_cast now keeps the deleter.

A: As Sneftel suggested, you can simply cast the pointer contained within the unique_ptr in order to access the other methods.
static_cast<Derived*>(b1.get())->v2

Keep in mind that this seems strange though. Generally if you have access to a pointer of a given type, you should not be casting it in the hope it has the type you have in mind. Instead, if you need to access methods of a given subclass, you should require that your inputs are pointers of that subclass. Storing base classes in smart pointers is generally done to leverage polymorphism, not much else.
If you are not using polymorphism, consider using a unique_ptr with the derived class in the template, and then downcasting that to the base pointer when just the base class interface is needed.
Another option is to keep the same pointer stored in two places: one as a Base, and one as a Derived - keeping in mind you'll have to use smart pointers only one one of those!

A: You can use the shared pointer casts if you use shared_ptr
std::static_pointer_cast<Derived>(b1)->v2;

your whole question is explained on the cppreference site: http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
I would be careful of the other suggestions, the standard did think of the issue and implemented a clean solution.

A: I am not sure that I understand what you are trying to do, but it looks more like a design matter.
If you have a pointer to Base, the actual object might be a Base or a derived class (not necessary Derived). That is, you cannot cast it to Derived without making some dangerous assumptions.
class B{public:virtual ~B(){}};
class D : public B{};
class DD : public B{};

int main()
{
  std::unique_ptr< B > pb( new D );
  D* pd = dynamic_cast< D* >( pb.get() );
  DD* pdd = dynamic_cast< DD* >( pb.get() ); // null
  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: USB to Ethernet device not working I have USB 3.0 to Gigabit Ethernet Adapter. I'm trying to get working on Ubuntu 18.04
$ lsusb
Bus 002 Device 002: ID 0b95:1790 ASIX Electronics Corp. AX88179 Gigabit Ethernet
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 0eef:c0aa D-WAV Scientific Co., Ltd
Bus 001 Device 003: ID 8087:0a2a Intel Corp.
Bus 001 Device 002: ID 0bda:58c6 Realtek Semiconductor Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hu

$ ifconfig
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 1904  bytes 206432 (206.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1904  bytes 206432 (206.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.126  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::5b52:8606:7116:4b51  prefixlen 64  scopeid 0x20<link>
        ether 70:1c:e7:75:7e:cf  txqueuelen 1000  (Ethernet)
        RX packets 12058  bytes 10801854 (10.8 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 8521  bytes 1601052 (1.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:    18.04
Codename:   bionic

$ lsmod
Module                  Size  Used by
rfcomm                 77824  4
ccm                    20480  6
pci_stub               16384  1
vboxpci                24576  0
vboxnetadp             28672  0
vboxnetflt             28672  0
vboxdrv               471040  3 vboxnetadp,vboxnetflt,vboxpci
bnep                   20480  2
binfmt_misc            20480  1
nls_iso8859_1          16384  1
snd_hda_codec_hdmi     49152  1
snd_soc_skl            90112  0
snd_soc_skl_ipc        65536  1 snd_soc_skl
snd_hda_ext_core       24576  1 snd_soc_skl
snd_soc_sst_dsp        32768  1 snd_soc_skl_ipc
snd_soc_sst_ipc        16384  1 snd_soc_skl_ipc
snd_soc_acpi           16384  1 snd_soc_skl
snd_hda_codec_realtek   106496  1
snd_hda_codec_generic    73728  1 snd_hda_codec_realtek
snd_soc_core          241664  1 snd_soc_skl
snd_compress           20480  1 snd_soc_core
ac97_bus               16384  1 snd_soc_core
snd_pcm_dmaengine      16384  1 snd_soc_core
snd_hda_intel          40960  6
snd_hda_codec         126976  4 snd_hda_intel,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek
arc4                   16384  2
dell_laptop            20480  1
dell_smbios_smm        16384  0
dcdbas                 16384  1 dell_smbios_smm
snd_hda_core           81920  7 snd_hda_intel,snd_hda_codec,snd_hda_ext_core,snd_soc_skl,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek
dell_smm_hwmon         16384  0
snd_hwdep              20480  1 snd_hda_codec
intel_rapl             20480  0
btusb                  45056  0
x86_pkg_temp_thermal    16384  0
btrtl                  16384  1 btusb
intel_powerclamp       16384  0
btbcm                  16384  1 btusb
coretemp               16384  0
uvcvideo               86016  0
snd_pcm                98304  8 snd_hda_intel,snd_hda_codec,snd_pcm_dmaengine,snd_hda_ext_core,snd_hda_core,snd_soc_skl,snd_hda_codec_hdmi,snd_soc_core
btintel                16384  1 btusb
bluetooth             548864  33 btrtl,btintel,bnep,btbcm,rfcomm,btusb
videobuf2_vmalloc      16384  1 uvcvideo
kvm_intel             212992  0
videobuf2_memops       16384  1 videobuf2_vmalloc
ax88179_178a           24576  0
iwlmvm                364544  0
videobuf2_v4l2         24576  1 uvcvideo
snd_seq_midi           16384  0
videobuf2_core         40960  2 uvcvideo,videobuf2_v4l2
usbnet                 45056  1 ax88179_178a
snd_seq_midi_event     16384  1 snd_seq_midi
mii                    16384  2 usbnet,ax88179_178a
hid_multitouch         20480  0
kvm                   598016  1 kvm_intel
ecdh_generic           24576  1 bluetooth
videodev              184320  3 uvcvideo,videobuf2_core,videobuf2_v4l2
mac80211              778240  1 iwlmvm
media                  40960  2 uvcvideo,videodev
snd_rawmidi            32768  1 snd_seq_midi
snd_seq                65536  2 snd_seq_midi_event,snd_seq_midi
irqbypass              16384  1 kvm
intel_cstate           20480  0
snd_seq_device         16384  3 snd_seq,snd_rawmidi,snd_seq_midi
snd_timer              32768  2 snd_seq,snd_pcm
iwlwifi               282624  1 iwlmvm
intel_rapl_perf        16384  0
dell_smbios_wmi        16384  0
dell_wmi               16384  0
snd                    81920  25 snd_compress,snd_hda_intel,snd_hwdep,snd_seq,snd_hda_codec,snd_timer,snd_rawmidi,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_seq_device,snd_hda_codec_realtek,snd_soc_core,snd_pcm
input_leds             16384  0
joydev                 24576  0
dell_smbios            16384  4 dell_wmi,dell_laptop,dell_smbios_wmi,dell_smbios_smm
cfg80211              622592  3 iwlmvm,iwlwifi,mac80211
wmi_bmof               16384  0
dell_wmi_descriptor    16384  2 dell_wmi,dell_smbios_wmi
hid_sensor_incl_3d     16384  0
serio_raw              16384  0
soundcore              16384  1 snd
hid_sensor_gyro_3d     16384  0
hid_sensor_rotation    16384  0
hid_sensor_magn_3d     16384  1
hid_sensor_accel_3d    16384  1
hid_sensor_trigger     16384  11 hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
industrialio_triggered_buffer    16384  5 hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
kfifo_buf              16384  1 industrialio_triggered_buffer
hid_sensor_iio_common    16384  6 hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
industrialio           69632  10 hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation,industrialio_triggered_buffer,kfifo_buf
idma64                 20480  0
virt_dma               16384  1 idma64
intel_vbtn             16384  0
soc_button_array       16384  0
int3403_thermal        16384  0
processor_thermal_device    16384  0
intel_lpss_pci         20480  0
mei_me                 40960  0
int3402_thermal        16384  0
mei                    90112  1 mei_me
int340x_thermal_zone    16384  3 int3402_thermal,int3403_thermal,processor_thermal_device
shpchp                 36864  0
intel_pch_thermal      16384  0
intel_soc_dts_iosf     16384  1 processor_thermal_device
intel_lpss             16384  1 intel_lpss_pci
intel_hid              16384  0
sparse_keymap          16384  3 dell_wmi,intel_hid,intel_vbtn
int3400_thermal        16384  0
acpi_thermal_rel       16384  1 int3400_thermal
acpi_pad              180224  0
mac_hid                16384  0
sch_fq_codel           20480  5
parport_pc             36864  0
ppdev                  20480  0
lp                     20480  0
parport                49152  3 lp,parport_pc,ppdev
ip_tables              28672  0
x_tables               40960  1 ip_tables
autofs4                40960  2
algif_skcipher         16384  0
af_alg                 24576  1 algif_skcipher
dm_crypt               40960  2
hid_sensor_custom      20480  0
hid_sensor_hub         20480  8 hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_iio_common,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation,hid_sensor_custom
intel_ishtp_hid        20480  0
usbhid                 49152  0
crct10dif_pclmul       16384  0
crc32_pclmul           16384  0
ghash_clmulni_intel    16384  0
pcbc                   16384  0
i915                 1617920  29
i2c_algo_bit           16384  1 i915
drm_kms_helper        172032  1 i915
syscopyarea            16384  1 drm_kms_helper
sysfillrect            16384  1 drm_kms_helper
sysimgblt              16384  1 drm_kms_helper
fb_sys_fops            16384  1 drm_kms_helper
aesni_intel           188416  8
intel_ish_ipc          20480  0
aes_x86_64             20480  1 aesni_intel
crypto_simd            16384  1 aesni_intel
glue_helper            16384  1 aesni_intel
ahci                   36864  3
cryptd                 24576  5 crypto_simd,ghash_clmulni_intel,aesni_intel
psmouse               147456  0
intel_ishtp            40960  2 intel_ishtp_hid,intel_ish_ipc
drm                   401408  16 i915,drm_kms_helper
libahci                32768  1 ahci
i2c_hid                20480  0
wmi                    24576  4 dell_wmi,wmi_bmof,dell_wmi_descriptor,dell_smbios_wmi
hid                   118784  5 hid_sensor_hub,i2c_hid,usbhid,hid_multitouch,intel_ishtp_hid
video                  45056  3 dell_wmi,dell_laptop,i915
pinctrl_sunrisepoint    28672  0

Any advice? My wifi works fine if btw.

A: I'm sorry but it seems that driver for your device is already included into the Linux kernel.
On my Ubuntu 18.04.1 LTS with 4.15 kernel I have the following output of modinfo ax88179_178a:
$ modinfo ax88179_178a
filename:       /lib/modules/4.15.0-33-generic/kernel/drivers/net/usb/ax88179_178a.ko
license:        GPL
description:    ASIX AX88179/178A based USB 3.0/2.0 Gigabit Ethernet Devices
srcversion:     5198353D2D0B5A7C431BB10
alias:          usb:v050Dp0128d*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v17EFp304Bd*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v04E8pA100d*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v0DF6p0072d*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v2001p4A00d*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v04B4p3610d*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v0B95p178Ad*dc*dsc*dp*ic*isc*ip*in*
alias:          usb:v0B95p1790d*dc*dsc*dp*ic*isc*ip*in* <--- yours VID and PID!
depends:        usbnet,mii
retpoline:      Y
intree:         Y
name:           ax88179_178a
vermagic:       4.15.0-33-generic SMP mod_unload
signat:         PKCS#7
signer:
sig_key:
sig_hashalgo:   md4

The driver may be installed with
sudo apt-get install linux-modules-extra-$(uname -r)

If you want - you can use the driver, provided by Trendnet:
cd ~/Downloads
wget http://downloads.trendnet.com/tu3-etg/utilities/linux_tu3-etg.zip
unzip linux_tu3-etg.zip
make
sudo make install
sudo modprobe usbnet
sudo insmod ax88179_178a.ko

If it does not work then remove Trendnet's driver with:
sudo rm /lib/modules/$(uname -r)/kernel/drivers/net/usb/ax88179_178a.ko
sudo /sbin/depmod -a

and reinstall kernel modules package from repositories with
sudo apt-get install linux-modules-extra-$(uname -r) --reinstall

Note: just tested D-Link DUB-1312 (2001:4a00), it works out the box even on Ubuntu 16.04 LTS with Linux 4.4 using preinstalled kernel module ax88179_178a:
$ cat /var/log/syslog | grep kernel
Sep 21 22:07:46 hostname kernel: [  767.258696] usb 4-1: new SuperSpeed USB device number 3 using xhci_hcd
Sep 21 22:07:46 hostname kernel: [  767.281700] usb 4-1: New USB device found, idVendor=2001, idProduct=4a00
Sep 21 22:07:46 hostname kernel: [  767.281707] usb 4-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Sep 21 22:07:46 hostname kernel: [  767.281712] usb 4-1: Product: D-Link DUB-1312
Sep 21 22:07:46 hostname kernel: [  767.281716] usb 4-1: Manufacturer: D-Link Elec. Corp.
Sep 21 22:07:46 hostname kernel: [  767.281719] usb 4-1: SerialNumber: 000000000015B6
Sep 21 22:07:47 hostname kernel: [  767.608195] ax88179_178a 4-1:1.0 eth0: register 'ax88179_178a' at usb-0000:00:14.0-1, D-Link DUB-1312 USB 3.0 to Gigabit Ethernet Adapter, 18:0f:76:xx:xx:xx

$ lsusb -d 2001:4a00
Bus 004 Device 003: ID 2001:4a00 D-Link Corp.

$ lsmod | grep ax88179_178a
ax88179_178a           24576  0
usbnet                 45056  1 ax88179_178a
mii                    16384  2 usbnet,ax88179_178a

A: I have exactly the same laptop as OP with Ubuntu 18.04, and the same problem. For me, a workaround was to unplug/replug the usb ethernet dongle WITHOUT having the ethernet cable plugged into the dongle. After that, lsusb shows my device as:
Bus 002 Device 025: ID 0bda:8153 Realtek Semiconductor Corp.
Bus 002 Device 024: ID 05e3:0616 Genesys Logic, Inc. hub

After this, the ethernet cable can be replugged. I already had dhcp ready on the router side, so at this point the ethernet comes up and is properly connected (check with "ip address show").
Note: My ethernet usb dongle hardware is probably different from OP, but the workaround is worth a try.
Is it a bug that the usb ethernet device will not start properly when the ethernet cable is plugged in before plugging the usb side of the device? It seems like incorrect behavior to me.


text:
Q: Play Framework: How can I read a png image using the WS client? Hi I'd like to read a PNG from a web service and then respond back to the client with the PNG. (think something like an image proxy). I am using Java and the Play Framework 2.0 with the WS class.
Currently I have:
public static Result getimage(){

  WSRequestHolder requestHolder = WS.url("http://someimageserver/myimage.png");
  Promise<WS.Response> getImageResult = requestHolder.get();
  //How do I create an play.mvc.Result from this so I can sent it back to the callee?

}

Any help is much appreciated.

A: In Play 2.0.4 you can't do that in Java. First there is no method for binaries in the API: http://www.playframework.org/documentation/api/2.0.4/java/play/libs/WS.Response.html . I tried the method WS.Response.getBody(), but the bytes weren't correct.
But the Scala API supports binary files in Play 2.0.4:
package controllers

import play.api._
import libs.ws.WS
import play.api.mvc._

object Application extends Controller {

  def getImage = Action {
    Async {
      WS.url("http://someimageserver/myimage.png").get().map { r =>
        Ok(r.getAHCResponse.getResponseBodyAsBytes).as("image/png")
      }
    }
  }

}

From Play 2.1 on there is support for binaries in Java: https://github.com/playframework/Play20/blob/master/framework/src/play-java/src/main/java/play/libs/WS.java#L565

A: Thanks, looks like I'll have to be patient :) . I found a workaround though (using ning directly).
//imports
import java.util.concurrent.Future;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Response;

//request
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
BoundRequestBuilder prepareGet = asyncHttpClient.prepareGet(url);
Future<Response> fResponse = prepareGet.execute();
Response r = fResponse.get();
InputStream responseBodyAsStream = r.getResponseBodyAsStream();

return ok(responseBodyAsStream).as('image/png');


text:
Q: Cannot calculate payslip without an Unpaid leave in Odoo I created a payslip for a month without any unpaid leave.
While calculating the payslip it shows every amount as zero for all other salary rules but if there is an unpaid leave(LOP) on that month it can be computed
These are my salary rules for unpaid leave:
Condition :
result=bool(worked_days.LOP)

Calculation :
lop_days=worked_days.LOP and (worked_days.LOP.number_of_days*-1)

result=((categories.BASIC/30)*lop_days)+((categories.DA/30)*lop_days)+((categories.ALW/30)*lop_days)

This is the result after computing the payslip without unpaid leave/LOP


text:
Q: find_element_by_id not working on a specific site but works for Youtube SOLVED!
I didn't know what iframes were and Arundeep Chohan mentioned them in the comments which lead me down a rabbit hole and know I got it to work.
I would like his answer but he left it as a comment. Thanks Arundeep!
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I am trying to write a program to automatically log me into a site but the find_element_by_id doesn't seem to work for this login page. I got it to work for Youtube but so far the id I am looking for doesn't seem to be detected on this site.
I have also tried find_element_by_name and find_element_by_class to no avail either.
Below is my code
# Imports
import selenium
from selenium import webdriver

# Variables
UsNam = "MY_USERNAME"

# Assigning Firefox to browser
browser = webdriver.Firefox(executable_path=r"C:\Users\ME\Geckodriver\geckodriver-v0.27.0-win64\geckodriver.exe")

# Opening the webpage
browser.get("https://THESITEIWANTTOLOGINTO.com/abunchofloginpagestuff")

# Finding the login input
NameEntry = browser.find_element_by_id('USER')
browser.implicitly_wait(15)

# Entering the username
NameEntry.send_keys(UsNam)

Here is the element that I can't seem to find in selenium,
<input class="form-control ng-pristine ng-invalid ng-invalid-required" type="text" name="USER" id="USER" data-payxautoid="paychex.app.login.userName.input.username" placeholder="Enter Username" maxlength="50" data-ng-model="user.username" data-payx-focus="" data-ng-change="clearShowError()" required="" data-payx-form-value="siteminder.username">

One thing that is weird that I just noticed is when I copy and paste the element the id doesn't appear there. It should read "input id="USER" class=..."
Any help would be greatly appreciated. I tried reading the other Overflow questions and didn't find any answers which is why I am here now
Thanks
EDIT: Here is my error message
Traceback (most recent call last):
  File "C:/Users/Crow/PycharmProjects/Login/main.py", line 15, in <module>
    NameEntry = browser.find_element_by_id('USER')
  File "C:\Users\Crow\PycharmProjects\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Users\Crow\PycharmProjects\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\Crow\PycharmProjects\Login\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Crow\PycharmProjects\Login\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="USER"]

A: After driver.get()
driver.implicitly_wait(10)

Then do the search. You could use webdriver waits instead.
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

Inspect the page and check your iframes. Copy what the xpath,css,id of your iframe is and insert it into the above line and change accordingly.
Instead of wait and search:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "User"))).send_keys(UsNam)

Import
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

A: I can think of 2 solutions:

*

*Make the browser implicitly wait before searching for the element, as to give time for the website to load.

*Use xpath instead of finding by id name, as simple as right clicking the element in inspect element and clicking copy full xpath.


text:
Q: Perfect Tense with since Could someone explain which one is the correct answer and why
He hasn't played since he ……… the accident.
a) had b) has had c) has c) had had
thanks

A: The only correct answer to my ears is A.
The construction
(Present perfect phrase) since (event)
means
(Time line; x represents the event)
-----x-------(present)
The present perfect phrase is true for all times to the right of the x. (You can say "ever since" to emphasize that it is true for all times to the right of x, no exceptions.)
The dashes continue to the present, which is why the first phrase uses a perfect. The event is discrete, which is why it uses a simple past.
I think the criterion of "does it affect the present" is always relative. Everything affects the present. It affects the present very much that the Big Bang happened, but we use the simple past. In a "since" sentence, there is a feeling that a discrete event in the past has caused effects that continue to today. To emphasize this difference, we use the simple past for the discrete action and the present perfect for the continuous effect.


text:
Q: Warn in VS Code when Promise return type is unawaited? I'm using Visual Studio Code typescript and am wondering if there is a way for the editor to display some kind of warning whenever there is an async function call (function returns a Promise) but the caller does not await it (so that the programmer does not accidentally assume that a function is synchronous and use it as such).

A: As long as you are using typescript, the type system should alert you that you can't use a promise wherever you use the resolved value of that promise:
function foo(): Promise<number> {
    return new Promise(resolve => resolve(123))
}

const myNumber: number = foo() // forgot await
// ^ Type 'Promise<number>' is not assignable to type 'number'.

Playground
So, in effect, typescript already does what you want, just not in the way you're thinking.

Also, there are very good reasons that a promise may not be awaited. One maybe that you want a bunch of async operations in parallel, so you collect the promises and pass them Promise.all. Or perhaps you're at the top level which does not allow await, and it's simpler to use then instead.
So instead, just let the type system work as intended and don't worry about it. Doing it wrong will give you type errors like the one above when you start to actual use the awaited values.


text:
Q: How to get the regular expression for starting double quotes? What will be the regular expression for  "id="fn1"" so as to get only fn1?
I have tried this
System.Text.RegularExpressions.Regex.IsMatch(sLast, "(^\bid=\")[A-Za-z0-9]")

This doesnt work. What should I change?


text:
Q: Nginx Configuration throws 500 Internal Server Error According to error.log:
2016/05/10 16:48:27 [crit] 11638#0: *1 connect() to unix:/var/run/php5-fpm.sock failed (2: No such file or directory) while connecting to client upstream, client: 123.456.789, server: example.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:"

And below is the content of "/etc/nginx/sites-available/default":
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    #root /usr/share/nginx/html;
    root /var/www;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name example.com;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.

        try_files $uri $uri/ /index.html;

        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }

    location @handler{
        rewrite / /index.php;
    }

    location /doc {
        root /usr/share;
        autoindex on;
        allow 127.0.0.1;
        deny all;
    }

    location /images {
        root /usr/share;
        autoindex off;
    }

    # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
    #location /RequestDenied {
    #   proxy_pass http://127.0.0.1:8080;
    #}

    error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        #root /usr/share/nginx/html;
        root /var/www;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~* \.php$ {
    #   try_files $uri=404;
    #   fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #   # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #
    #   # With php5-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;
    #   # With php5-fpm:
    #   fastcgi_pass unix:/var/run/php5-fpm.sock;
    #   fastcgi_index index.php;
    #   fastcgi SCRIPT_FILENAME $document_root$fastcgi_script_name;
    #   include fastcgi_params;

        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

When i do ls /var/run/ i don't see any php5-fpm.sock file (even though i have "sudo service php5-fpm start" or "sudo service php5-fpm restart"). I am not sure why is this happening.
I am relatively new with nginx, and currently experimenting nginx with magento. Basically am trying to install Magento using nginx.
When i browse to example.com, instead of seeing default magento installation i get "500 Internal Server Error" message.
The configuration above is based on multiple references:
https://thomas-leister.de/linux/nginx-php-fpm-installieren-ubuntu-server/

and
https://www.howtoforge.de/anleitung/installation-von-nginx-mit-php5-und-php-fpm-mit-mysql-unterstutzung-unter-ubuntu-11-10/

Can anyone help me with this ? Thank you.
EDIT 1:
I am using Ubuntu 14.04 (AWS EC2).
EDIT 2:

EDIT 3:

A: Just read your error log one more time. Nginx tries to communicate with php-fpm on socket unix:/var/run/php5-fpm.sock but it does not exist. This produces 500 internal error.

When i do ls /var/run/ i don't see any php5-fpm.sock file. I am not sure why is this happening.

You just need to set up php-fpm. At first, try running
service php5-fpm restart and check if there are any errors. If there are some - fix them. Othervise, correct the path to socket.


text:
Q: Populate html table on jQuery success event Here's my problem.
I have this html table:

      Usuario
      Nombre
      Apellido
      Cedula/Rif
      Direccion
      E-mail
      Telefono1
      Telefono2
      Status
      Acción

and I have this ajax request:
$.ajax({
   type    : "POST",
   url     : "service.php",
   dataType: "json",
   data: {
       action:"search",
       type: 'users',
       parameter: parameter,
       parameterContent: parameterContent,
   },
   success:function(data) {
       $('#searchResults').show();
       var len = data.length;
       for (var i = 0; i< len; i++) {
       var username  = data[i].username;
       var name  = data[i].uname;
       var lastname  = data[i].lastname;

   }
})

What is the correct way to populate the html table with the info that comes via JSON? I have been trying with no success. I have done tests with append() html() but no success at all, can someone please point me into the right direction?
What I want is to take the info that comes via JSON and populate the table dynamically with this info.

A: Try this:
for (var i = 0; i < len; i++) {
   var username = data[i].username;
   var name  = data[i].name;
   var lastname = data[i].lastname;
   $('#table tbody').append('
'+username+'	'+name+'	'+lastname+'
')
}

A: You could try this:
    var table = $("#table tbody");
    $.each(data, function(idx, elem){
        table.append("
"+elem.username+"	"+elem.name+"	   "+elem.lastname+"
");
    });

More information can be found here:
http://api.jquery.com/jQuery.each/

A: Thanks, at the end i did it like this:
  $.ajax({
                        type    : "POST",
                        url     : "service.php",
                        dataType: "json",
                        data: {
                        action:"search",
                        type: 'users',
                        parameter: parameter,
                        parameterContent: parameterContent,
                        },
                            success:function(data) {

                                $('#searchResults').show();

                                    var len = data.length;
                                    for (var i = 0; i< len; i++) {

                                    var username  = data[i].username;
                                    var name  = data[i].name;
                                    var lastname  = data[i].lastname;
                                    var idnumber  = data[i].idnumber;
                                    var address  = data[i].address;
                                    var email  = data[i].email;
                                    var phone1 = data[i].phone1;
                                    var phone2 = data[i].phone2;
                                    var active = data[i].active;

                                    $("#generated").append("
"+ username +"	"+ name +"	"+ lastname +"	"+ idnumber +"	"+ address +"	"+ email +"	"+ phone1 +"	"+ phone2 +"	"+ active +"
");

                                }

                            }

A: JS
$(document).ready(function() {
  $.ajax({
    type: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    url: 'https://localhost:44387/api/employee/employeelist',
    dataType: "json",
    success: function(data) {
      var employeeTable = $('#tblEmployee tbody');
      employeeTable.empty();
      $('#tblEmployee').show();
      var len = data.length;
      for (var i = 0; i < len; i++) {
        var EmpId = data[i].EmpId;
        var FirstName = data[i].FirstName;
        var LastName = data[i].LastName;
        var Contact = data[i].Contact;
        var Address = data[i].Address;
        var Gender = data[i].Gender;
        var Salary = data[i].Salary;
        var Gender = data[i].Gender;
        var ActiveHours = data[i].ActiveHours;
        var Remark = data[i].Remark;
        var IsAvailable = data[i].IsAvailable;
        var Hiredate = data[i].Hiredate;
        var IsActive = data[i].IsActive;
        employeeTable.append('
' + EmpId + '	' +
          FirstName + '	' + LastName + '	' + Contact +
          '	' + Address + '	' + Gender +
          '	' + Salary + '	' + ActiveHours +
          '	' + Remark + '	' + IsAvailable +
          '	' + Hiredate + '	' + IsActive +
          '	<button type="button" class="btn btn-sm btn-primary editingTRbutton fas fa-pencil-alt noUnderlineCustom text-white" data-toggle="modal" data-target="#editModal">' + 'Edit' + '</button>' + '
');
      }

    },
    error: function(err) {
      alert(err);
    }
  })
});

HTML
<form id="Employeeform">

          ID
          First Name
          Last Name
          Contact
          Address
          Gender
          Salary
          ActiveHours
          Remark
          IsAvailable
          Hiredate
          IsActive
          Action

</form>


text:
Q: How to disable the URLCache completely with Alamofire Using Xcode 7.3 iOS 9.2 all in Swift none of that horrible Objective C
I have been working on this for a while and been around the block three times now. I have tried this post here and it didn't work
http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml
I have also try to use apple documentation but that is so crappy I cannot make sense of if.
So what I am doing is making two Alamofire calls to my server. One to test the credentials of the login information to see if the input is right. The second is to download and return the customer information for there viewing. Both are working fine when I call it the first time. The problem is when I logout of the app i clear all the user information from the page. But when I logbook in during the same session, it calls the first one right so if I put in the wrong username or password it returns false even if I login correctly the first time. But when I download the customer data, it keeps downloading the old information from the first time I accessed the user information. It uses the new username and password but still downloads the old stuff.
This is my Login and Logout functions:
//MARK: ButtonControllers
@IBAction func onLoginClick(sender: AnyObject) {

    errorMessageUI.text = "Checking Creditials"
    email = userNameInput.text!
    password = passwordInput.text!
    buildLoginUrl = checkLoginUrl + emailTag + email + passwordTag + password
    print(buildLoginUrl)
    print("Login Cred")
    checkLoginCredentials(buildLoginUrl)
}

@IBAction func onLogoutClick(sender: AnyObject) {

    //null out everything for logout
    email = ""
    password = ""
    self.loginInformation.setObject(self.email, forKey: "email")
    self.loginInformation.setObject(self.password, forKey: "password")
    self.loginInformation.synchronize()
    performSegueWithIdentifier("logoutSegue", sender: self)
    //self.view = LoginView
}

And this is the alamofire calls
//MARK: Check Credentials Method
//Function to log into the server and retrive data
func checkLoginCredentials(myUrl : String)
{
    Alamofire.request(.GET, myUrl)
        .validate(statusCode: 200..<300)
        .responseString { response in
            print("Cred Success: \(response.result.isSuccess)")
            print("Cred Check: \(response.result.value)")
            //clear all url chache
            NSURLCache.sharedURLCache().removeAllCachedResponses()

            if response.result.value != nil
            {
                let checker : String = response.result.value!
                if checker.lowercaseString.rangeOfString("false") != nil {
                    self.canILogin = false
                    self.errorMessageUI.text = "Wrong username or Password try again"
                }else{
                    self.canILogin = true
                    print("Downloading Json file for customer info")
                    self.loadingImage.hidden = false
                    self.downlaodCustomerinfo(self.customerInfoUrl, myUser: self.email, myPass: self.password)
                    //defaults.setBool(textColorSwitch.on, forKey: "DarkText")
                    self.loginInformation.setObject(self.email, forKey: "email")
                    self.loginInformation.setObject(self.password, forKey: "password")
                    self.loginInformation.synchronize()
                }

                print("Login? " + self.canILogin.description ?? "none" )
            }else
            {
                //Stop the program from downloading anything to avoid crashes
                self.loadingImage.hidden = true
                print("I cannot download User Info")
                self.errorMessageUI.text = "A connection error occured"
                //set the json to be empty to avoid a crash
                //reset the json file incase there is anythig in it
                self.downloadJson = ""

            }

    }
}//end of checkLoginCredentials function

//MARK: Download Customer Infoamtion
func downlaodCustomerinfo(myUrl : String, myUser : String, myPass : String)
{

    //clear all url chache
    NSURLCache.sharedURLCache().removeAllCachedResponses()
    print("Username: " + myUser)
    print("Password: " + myPass)
    print("Download Url: " + myUrl )
    print("Jsonfile before download: " + self.downloadJson)
    Alamofire.request(.GET, myUrl)
        .authenticate(user: myUser, password: myPass)
        .validate(statusCode: 200..<300)
        .responseString { response in
            //print("Success: \(response.result.isSuccess)")
            print("Info Download: \(response.result.value)")

            if response.result.value != nil{

                self.downloadJson = response.result.value!
                print("Json file: " + self.downloadJson)
                self.parseCustomerInfo(self.downloadJson)
            }else
            {
                self.loadingImage.hidden = true
                print("I cannot download User Info")
                self.errorMessageUI.text = "A connection error occured"
                //set the json to be empty to avoid a crash
                self.downloadJson = "{}"
            }

    }
}//end of download

UPDATED Code:
Cause the system to return false from the Alamofire response
  //Create a non-caching configuration.
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
    config.URLCache = nil
    //Create a manager with the non-caching configuration that you created above.
    let manager = Alamofire.Manager(configuration: config)

    print("Username for download: " + myUser)
    print("Password: " + myPass)
    manager.request(.GET, myUrl)
        .authenticate(user: myUser, password: myPass)
        .validate(statusCode: 200..<300)
        .responseString { response in
            //print("Success: \(response.result.isSuccess)")
            print("Info Download: \(response.result.value)")

            if response.result.value != nil{

                self.downloadJson = response.result.value!
                print("Json file: " + self.downloadJson)
                self.parseCustomerInfo(self.downloadJson)
            }else
            {
                self.loadingImage.hidden = true
                print("I cannot download User Info")
                self.errorMessageUI.text = "A connection error occured"
                //set the json to be empty to avoid a crash
                self.downloadJson = "{}"
            }

    }

}//end of downloadCustomer function

A: Why are you not configuring the session? If you configure the session correctly, there will be no caching.
Example:
//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil

//Allow cookies if needed.
config.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()

//Create a manager with the non-caching configuration that you created above.
self.manager = Alamofire.Manager(configuration: config)

//Examples of making a request using the manager you created:

//Regular HTML GET request:
self.manager.request(.GET, "https://stackoverflow.com")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["text/html"])
    .responseString { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }
    print("Result: \(response.result.value)")
}

//JSON GET request:
self.manager.request(.GET, "someURL", parameters: params, encoding: .URL, headers: headers)
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseJSON { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }

        print(response.result.value as? [String: AnyObject])
}

Edit:
let manager = {() -> Alamofire.Manager in
    struct Static {
        static var dispatchOnceToken: dispatch_once_t = 0
        static var instance: Alamofire.Manager!
    }

    dispatch_once(&Static.dispatchOnceToken) {
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
        config.URLCache = nil

        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        config.HTTPCookieStorage = cookies
        Static.instance = Alamofire.Manager(configuration: config)
    }

    return Static.instance
}()

manager.request(.GET, "https://stackoverflow.com")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["text/html"])
    .responseString { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }
    print("Result: \(response.result.value)")
}

P.S. You can also look into:

NSURLSessionConfiguration.ephemeralSessionConfiguration() - Returns a
  session configuration that uses no persistent storage for caches,
  cookies, or credentials.


text:
Q: How to communicate with index from AS2 file, being loaded by an AS3 file We are loading an actionscript2 swf into an actionscript3 swf. as3 is embeded on the index page using the satay method.
Is it possible to get a variable set on the index page from within the actionscript2 page, without using the as3 page as an intermediary (as this is not an option)?
We've tried ExternalInterface, but how would we target the embeded flash file directly?
Alternatively, is it possible to send variables to the as2 file, when loading it from the as3 file? (a la get vars? or a flash vars?)

A: You talk about targetting the embedded flash file directly and yet you ask for setting an javascript variable. That's a bit confusing.
So, you're setting an js variable on the page from as2, right?
Check out this blogpost, as it has some good points
Here's another way to talk to js if you do not like ExternalInterface.

A: I think what you are looking for is the swfbridge
What you would do is create an as2 wrapper swf that loads the as2 file that you want to use. You can add whatever functions or properties that you want to use in the original as2 file to the wrapper and then, using the bridge, call them from the as3 code.
Takes a bit of doing but the example he provides show how it works.


text:
Q: helm chart : strings concatenation I am trying to concatenate variable in helmchart to develop connection strings.
connection string:
ConnectionStrings:TheSourceContext="Server=10.xx.xx.xx,1433;Database=Test;User Id=Test; Password=pass123;"

I am passing user id &password as secret but it is not working. it is not building up the requried strings.
      - name: DBUSERD
        valueFrom:
          secretKeyRef:
            key: dbuser
            name: api-catalogue
      - name: DBPASSD
        valueFrom:
          secretKeyRef:
            key: dbpass
            name: api-catalogue
      - name: ConnectionStrings__TheSourceContext
        value: {{ .Values.const.DBSVR }}{{ .Values.app.connectionStringsServer }},{{.Values.app.connectionStringsPort }}{{ .Values.const.DB }}{{ .Values.app.connectionStringsDB }}{{ .Values.const.DBUSR }}$(DBUSERD){{ .Values.const.DBPASS }}($DBPASSD)*

How to correct above variable so that it will work?


text:
Q: thumbnail image of youtube video in YouTubeThumbnailView android studio I want to access the thumbnail image of YouTube video in YouTubeThumbnailView android studio.
The code:
public static void thumbnailfunc(Activity context,final String VIDEO_ID, int ThumbnailID)
{
    YouTubeThumbnailView thumbnail =context.findViewById(R.id.ThumbnailID);

    thumbnail.initialize(API_KEY, new OnInitializedListener()
    {
        @Override
        public void onInitializationSuccess(
                YouTubeThumbnailView youTubeThumbnailView,
                final YouTubeThumbnailLoader youTubeThumbnailLoader)
        {
            youTubeThumbnailLoader.setVideo(VIDEO_ID);
            youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener()
            {
                @Override
                public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s)
                {
                    //need to release the loader!!!
                    youTubeThumbnailLoader.release();
                }

                @Override
                public void onThumbnailError(
                        YouTubeThumbnailView youTubeThumbnailView,
                        YouTubeThumbnailLoader.ErrorReason errorReason)
                {
                    //need to release the loader!!!
                    youTubeThumbnailLoader.release();
                }
            });
        }

        @Override
        public void onInitializationFailure(
                YouTubeThumbnailView youTubeThumbnailView,
                YouTubeInitializationResult youTubeInitializationResult)
        {
            //handle error here
        }
    });
}

And here is the error I get:
Caused by: java.lang.NullPointerException:
  Attempt to invoke virtual method 'void
    com.google.android.youtube.player.YouTubeThumbnailView.initialize(
      java.lang.String,
      com.google.android.youtube.player.YouTubeThumbnailView$OnInitializedListener)'
    on a null object reference

A: Your log report clearly shows that Android Studio it is unable to find the Thumbnail view R.id.ThumbnailID in your layout. Please check!


text:
Q: What is the difference between Action and Actions in Selenium? I would like to know the difference between Action and Actions in Selenium

A: Action:
In Selenium, Action is an interface which represents a single user-interaction action. It is defined in org.openqa.selenium.interactions. It contains one of the most widely used method perform(). You can find more about the implementing Classes and Methods in this link.
Action Example:
In the below image, if we mouse hover the keyword Action, the violet colored I indicates that Action is an interface.

Actions:
In Selenium, Actions is a Class. It is defined in org.openqa.selenium.interactions. This is the user-facing API for emulating complex user gestures. Actions Class implements the builder pattern, which can build a CompositeAction containing all actions specified by the method calls. You can find more about the Method Summary in this link.
Actions Example:
In the below image, if we mouse hover the keyword Actions, the green colored C indicates that Actions is a Class.

A: Action is an interface :
public interface Action

Action Interface representing a single user-interaction action.
VS
Actions is a Class that extends from Object
public class Actions
extends java.lang.Object

The user-facing API for emulating complex user gestures. Use this class rather than using the Keyboard or Mouse directly.
Edit:
Thanks to @mrfreester pointed out. You can string a bunch of actions together using Actions, and then once you call build() it will store that set of steps as an Action. Once you have an Action, you can call perform() to execute that set of steps.


text:
Q: Why menu in ActionBar in Android can get focus with view.setPadding(0, actionBarHeight, 0, 0) in which actionBarHeight is not for sure? I have view like follow:

--------------------------------------------------------------------------------------
+                             Here is ActionBar                                     +
+                                                       Menu1     Menu2    Menu3    +
+-----------------------------------------------------------------------------------+
|    Here is A View such as ListView wrapped by LinearLayout                        |
|   Content1                                                                        |
|   Content2                                                                        |
|   Content3                                                                        |
|   Content4                                                                        |
|   Content5                                                                        |
-------------------------------------------------------------------------------------

This is my layout file:
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/content_root"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ListView
            android:id="@+id/file_item"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

</LinearLayout>

item.xml
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@android:id/text1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@drawable/selector_list_item"
    />

styles.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="@android:style/Theme.Holo.Light">
        <!-- Customize your theme here. -->
        <item name="android:windowActionBarOverlay">true</item>
    </style>

</resources>

ListViewActivity.java
public class ListViewActivity extends Activity {
    public static final String LOG_TAG = "LOG: " + ListViewActivity.class.getName();

    private FileNode mCurrentNode;

    private ListView mDetailsView;

    private List<FileNode> mNodeList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.file_details);

        mCurrentNode = new FileNode(Environment.getExternalStorageDirectory());

        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.content_root);
        linearLayout.setPadding(0, 88, 0, 0);     // 88 is just the exactly value make the action bar get focued(but platform depended), 87 is not ok
        mDetailsView = (ListView) findViewById(R.id.file_item);

        ArrayList<String> itemList = new ArrayList<String>();
        itemList.add("item1");
        itemList.add("item2");
        itemList.add("item3");
        itemList.add("item4");
        itemList.add("item5");
        itemList.add("item6");
        itemList.add("item7");
        itemList.add("item8");
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.text_item, itemList);

        mDetailsView.setAdapter(adapter);

        ActionBar actionBar = getActionBar();
        if (actionBar == null) return;

        actionBar.show();
    }

    private void loadFile() {
        mNodeList = new ArrayList<FileNode>();
        if (mCurrentNode == null) return;

        File[] files = mCurrentNode.getFile().listFiles();
        if (files == null) return;

        for (File f : files) {
            mNodeList.add(new FileNode(f));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_normal, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

Here is the problem:
At the beginning, I can not get the Menu in ActionBar focused with press up key in remote control. Then I add some code like follow:
mView = (LinearLayout)findViewLayout(R.id.view_root);
int actionBarHeight = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
    actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
            getResources().getDisplayMetrics());
}

mView.setPadding(0, actionBarHeight, 0, 0);

Then, the Menu can get focused.
The curcial code is mView.setPadding(0, actionBarHeight, 0, 0);, I have tried to assign some other value to actionBarHeight, this value is not dependent for just now, if actionBarHeight makes you see the first item(do not need to see all, just a little is enough), the ActionBar will get foucsed.

A: Switch android:windowActionBarOverlay from true to false (or just remove it, false should be the default).


text:
Q: When an XPath's target element is specified by ID, can other parts have any effect on the speed or efficiency? Suppose that a document contains a large amount of elements. For example, elements with the species name structured like the phylogenetic tree. The div with the id="dog" is a descendant of the div with the id="carnivora".
In this case, is it any faster/more efficient to try to locate dog with //div[@id='carnivora']//div[@id='dog'] (which limits the search area to only the carnivora element and its descendants) instead of just //div[@id='dog']? Or is even //div[@id='dog'] (which limits the search target types to only divs, not something like span, etc) faster/more efficient than //*[@id='dog']?

A: It seems that //div[@id='dog'] has O(N) complexity, while //div[@id='carnivora']//div[@id='dog'] ~ O(N^2), where N is a total number of divs. Maybe not N^2, maybe N*logN.
I've created an xml file, 25000 lines
<?xml version="1.0" encoding="UTF-8"?>
<doc>

</doc>

and run two xpaths ontop of it:

*

*//div[@id='carnivora']//div[@id='dog'] – 8 sec

*//div[@id='dog'] – 0.1 sec


text:
Q: Trouble using ng-functions So I have 3 html pages (with 3 different angular controllers), every page displays a table with rows, and on every page the rows should either be displayed red or green (according to the errorstate):

    {{case.name}}
    ........

    {{case.errormessage}}

Now it wouldn't make sense to have 3 setRowColor methods (one in every controller), but I also can't create a factory service, since I wouldn't be able to call it inside ng-class.
So my idea was to make a normal JS function, and just use class instead of ng-class, but this doesn't seem to work along with ng-repeat.
here's the method:
function setRowColor(col) {
    return {passed: col == '0', failed: col != '0'};
};

whereas I have a .passed and .failed class in my stylesheet.
Is there a way of getting class to work? Or is there any better approach to solve my problem?

A: The function setRowColor should be defined in your controller's $scope.
$scope.setRowColor = function() {
    ...
};

To keep only one definition of this function you should create an AppController which would be set on the body tag:

    ...

Define the above function inside AppController and your problem should be fixed.

A: How about using a ternary in the ng-class instead?

    {{case.name}}
    ........


text:
Q: "card not found" when using "composer network ping --card admin@trial.card" I am trying to deploy my own business network
So I made my own .bna file and card called admin@trail.card
After I importing the card using :
composer card import --file admin@trial.card
I run composer card list to verify that the card has been imported
$ composer card list

The following Business Network Cards are available:

Connection Profile: hlfv1
┌─────────────────────┬───────────┬──────────────────┐
│ Card Name           │ UserId    │ Business Network │
├─────────────────────┼───────────┼──────────────────┤
│ admin@trial         │ admin     │ trial            │
├─────────────────────┼───────────┼──────────────────┤
│ PeerAdmin@hlfv1     │ PeerAdmin │                  │
└─────────────────────┴───────────┴──────────────────┘

Issue composer card list --card <Card Name> to get details a specific card

now when I try to ping it I get an error saying that card is not found
composer network ping --card admin@trial.card
Error: Card not found: admin@trial.card
Command failed

I also tried using composer-playground
$composer-playground
but I get an error popup saying :
Error: Error trying to ping. Error: No business network has been specified for this connection
How to solve this issue?
P.S. My fabric environment is running(./startFabric.sh and createPeerAdminCard.sh) I rechecked my docker using docker ps and everything is up.
Also, my TransactionLogic.js file is still incomplete so if that's the issue please let me know. (out of 3 transaction function I have finished 1 and want to test it)
It works on https://composer-playground.mybluemix.net/ but not on my localhost

A: Sorry I found where the issue was that the command should have been
composer network ping --card admin@trial
rather than
composer network ping --card admin@trial.card
I'll keep this post up incase someone makes the same mistake as me.


text:
Q: How to get the specific line string (UTF8) or specific line string length in source editor using OpenToolsAPI I want to fetch the entire line string (UTF8) and want to do operation on the line string. I have tried following code. but if we are having multibyte characters am not able to do this.
J:=1;
  CurrentRowStr :='';
  while True do
  begin
    //detect end of line
    Buffer.EditPosition.Move(Changes[I].FLine,J);
    CurrentRowStr := CurrentRowStr + Buffer.EditPosition.Character ;
    J := J+1;
  end;
  CurrentRowStr := Buffer.EditPosition.Read(J-1);

if anyone can help me to get particular line string using OpenToolsAPI, it would be great help.

A: You can use a IOTAEditReader to get entire lines. The following code is from my Conversion Helper Package. Most of this revolves around the GetCurrentLineParams function:
function GetEditor: IOTASourceEditor;
var
  ModuleServices: IOTAModuleServices;
  Module: IOTAModule;
  I: Integer;
begin
  ModuleServices := BorlandIDEServices as IOTAModuleServices;
  Module := ModuleServices.CurrentModule;
  for I := 0 to Module.GetModuleFileCount - 1 do
    if Supports(Module.GetModuleFileEditor(I), IOTASourceEditor, Result) then
      Break;
end;

function GetLineAtCharPos(const Editor: IOTASourceEditor;
  const EditView: IOTAEditView; CharPos: TOTACharPos): string;
var
  EditReader: IOTAEditReader;
  Start, Len: Integer;
  Res: AnsiString;
begin
  CharPos.CharIndex := 0;
  Start := EditView.CharPosToPos(CharPos);
  Inc(CharPos.Line);
  Len := EditView.CharPosToPos(CharPos) - Start;
  if Len > 0 then
  begin
    SetLength(Res, Len);
    EditReader := Editor.CreateReader;
    EditReader.GetText(Start, PAnsiChar(Res), Len);
    Result := string(PAnsiChar(Res));
  end;
end;

function GetCurrentLine(const Editor: IOTASourceEditor;
  var BufferStart, Index: LongInt): string;
var
  BufferLength: LongInt;
  EditReader: IOTAEditReader;
  Res: AnsiString;
begin
  GetCurrentLineParams(Editor, BufferStart, BufferLength, Index);
  SetLength(Res, BufferLength);
  EditReader := Editor.CreateReader;
  EditReader.GetText(BufferStart, PAnsiChar(Res), BufferLength);
  Result := string(PAnsiChar(Res)); // just to be sure.
end;

function GetCurrentCharPos(const Editor: IOTASourceEditor; out EditView:
  IOTAEditView): TOTACharPos;
var
  CursorPos: TOTAEditPos;
begin
  EditView := Editor.GetEditView(0);
  CursorPos := EditView.CursorPos;
  EditView.ConvertPos(True, CursorPos, Result);
end;

procedure GetCurrentLineParams(const Editor: IOTASourceEditor;
  var Start, Length, Index: Integer);
var
  EditView: IOTAEditView;
  CharPos: TOTACharPos;
begin
  CharPos := GetCurrentCharPos(Editor, EditView);
  Index := CharPos.CharIndex + 1;
  CharPos.CharIndex := 0;
  Start := EditView.CharPosToPos(CharPos);
  Inc(CharPos.Line);
  Length := EditView.CharPosToPos(CharPos) - Start;
end;

function GetCurrentLineStart(const Editor: IOTASourceEditor): Integer;
var
  L, I: Integer;
begin
  GetCurrentLineParams(Editor, Result, L, I);
end;

function GetCurrentLineLength(const Editor: IOTASourceEditor): Integer;
var
  S, I: Integer;
begin
  GetCurrentLineParams(Editor, S, Result, I);
end;


text:
Q: Why does ActiveMQ restart automatically and how do i prevent it? We've been using AMQ 5.5.1 in production for several months. Occasionally, we observe that the broker decides to refresh itself with no outside trigger. When this happens, our queue senders fail until the broker is back online some 10 minutes later. I cannot find any information or settings that would cause this behavior .. and let me control it.
Is this normal for the broker to recycle on its own like this? If so, what things would cause it?
2012-12-11 11:02:11,603 | INFO  | Refreshing   org.apache.activemq.xbean.XBeanBrokerFactory$1@f6ac0b: startup date [Tue Dec 11 11:02:11 EST 2012]; root of context hierarchy | org.apache.activemq.xbean.XBeanBrokerFactory$1 | WrapperSimpleAppMain
 2012-12-11 11:02:13,806 | WARN  | destroyApplicationContextOnStop parameter is deprecated, please use shutdown hooks instead | org.apache.activemq.xbean.XBeanBrokerService | WrapperSimpleAppMain
 2012-12-11 11:02:13,821 | INFO  | PListStore:D:\Tools\ActiveMQ\apache-activemq-5.5.1\bin\win32\..\..\data\localhost\tmp_storage started | org.apache.activemq.store.kahadb.plist.PListStore | WrapperSimpleAppMain
 2012-12-11 11:02:13,868 | INFO  | Using Persistence Adapter: KahaDBPersistenceAdapter[D:\Tools\ActiveMQ\apache-activemq-5.5.1\bin\win32\..\..\data\kahadb] | org.apache.activemq.broker.BrokerService | WrapperSimpleAppMain
 2012-12-11 11:02:16,618 | INFO  | KahaDB is version 3 | org.apache.activemq.store.kahadb.MessageDatabase | WrapperSimpleAppMain
 2012-12-11 11:02:16,697 | INFO  | Recovering from the journal ... | org.apache.activemq.store.kahadb.MessageDatabase | WrapperSimpleAppMain

A: I found that the wrapper exe process was forcing the restart.
I was able to see in the wrapper.log (windows service) that the process was being restarted because the JVM was not responding. So this is not an issue with the broker auto-restarting per se.. it was an issue with the broker JVM somehow becoming hung (separate problem).
Here are the wrapper log entries for those interested:
ERROR  | wrapper  | 2012/12/11 11:01:58 | JVM appears hung: Timed out waiting for signal from JVM.
ERROR  | wrapper  | 2012/12/11 11:01:58 | JVM did not exit on request, terminated
STATUS | wrapper  | 2012/12/11 11:02:04 | Launching a JVM...


text:
Q: What's the difference between WP_MEMORY_LIMIT and WP_MAX_MEMORY_LIMIT? What's the difference beetween
define( 'WP_MEMORY_LIMIT', '96M' );
and
define( 'WP_MAX_MEMORY_LIMIT', '256M' );
In my host I have this
define( 'WP_MEMORY_LIMIT', '786M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );

is this correct, should the WP_MAX_MEMORY_LIMIT be higher ?

A: The WP_MEMORY_LIMIT is the default limit set in the front-end, but it can be raised up to WP_MAX_MEMORY_LIMIT in wp-admin pages, as well as certain other functions such as image manipulation.
In short, you'll want to have the WP_MEMORY_LIMIT set primarily for front-end access, in a way that you won't use up your memory when many concurrent users hit the server.  You'd want WP_MAX_MEMORY_LIMIT set higher to allow for admin functions that have heavier requirements, but lower concurrency.

A: WordPress tells us:

the WP_MEMORY_LIMIT option allows you to specify the maximum amount of
  memory that can be consumed by PHP. This setting may be necessary in
  the event you receive a message such as "Allowed memory size of xxxxxx
  bytes exhausted".

Or as the PHP docs put it

[A memory limit] helps prevent poorly written scripts for eating up all available
  memory on a server.

The WordPress Codex also says this about these constants:

This setting [WP_MEMORY_LIMIT] increases PHP Memory only for WordPress, not other
  applications. By default, WordPress will attempt to increase memory
  allocated to PHP to 40MB (code is at the beginning of
  /wp-includes/default-constants.php) for single site and 64MB for
  multisite, so the setting in wp-config.php should reflect something
  higher than 40MB or 64MB depending on your setup.

And this about the WP_MAX_MEMORY_LIMIT specifically:

Administration tasks require much [more] memory than [a] usual operation. When in
  the administration area, the memory can be increased or decreased from
  the WP_MEMORY_LIMIT by defining WP_MAX_MEMORY_LIMIT.

So WP_MEMORY_LIMIT is the limit and WP_MAX_MEMORY_LIMIT, if set, will override the former in the admin.
Now when you ask "is this correct", there is no way for us to tell you definitively.
You may want to raise those limits if your site is growing in visitors and or active plugins but if you are not experiencing any issues I would say you are fine for now.
If you choose to up the limits I have outlined the different methods to increase PHP memory in this answer. Note the last part about your host potentially limiting this value.


text:
Q: Why would a custom VSCode Extension work in development but not when published? I am stumped. I worked several months developing a language extension for VSCode and it works great in the extension development environment. But when I publish it, it does not function. I have tried everything to no avail.
Any suggestions as to why it wouldn't work specifically when published would be greatly appreciated.
Extension:
https://marketplace.visualstudio.com/items?itemName=dehilster.nlp
Source code:
https://github.com/VisualText/vscode-nlp

A: It turns out that there was a dependency missing (in this case tslib) and I had to add it to the package building directly. For some reason, the tslib being listed as a dependency in the package.json file didn't seem to fix it. So I added the folder node_modules/tslib/**/* to the .vscodeignore file and then it worked. THis is not the way ultimately do this but it works for now.


text:
Q: Permutation of a word with conditions how many distinct arrangements there are of the word MATEMATICA so that:
-1)there are two consecutive M
-2)there aren't consecutive vowel
-3)both of the precedent conditions are true;

For the n° 1: writing the word as MMXXXXXXXX there are $\frac{8!}{3!2!}$ distinct permutation of the X's part and there are 9 permutation of the block MM so there're $\frac{8!}{3!2!} * 9 = 30240$ permutation in which there's the M's are consecutive.
For n°2: writing the word as XMXTXMXTXCX the X's are the n° of the vowel + a blank space
there are $6! = 720$ permutation of the X's but the blank space cannot be inside the word so
$720 - 4 = 716$ permutation.
Now,i'm not sure I've done it right (i don't have the solution) and I don't know how to do the n° 3

A: EDIT: This only applies for part 3.
For 1, it is useful to think of the two "M"s as one entity, since they must be together. "MATEMATICA" has 10 letters, so if you think of the two "M"s together as a single letter, you have 9 letters, meaning there are \frac{9!}{2!}{3!} valid combinations (after eliminating the double-counting from "T" and "A")
This should drastically simplify part 2. A useful observation for 2 is that there are 5 vowels in 9 letters (remembering that two M's are treated as one letter), meaning the odd-places must have vowels and even-places must have consonants.

A: *

*Use X instead of MM, and count the number of permutations of AAACEITTX instead:
$\binom93\cdot\binom61\cdot\binom51\cdot\binom41\cdot\binom32\cdot\binom11=30240$

*Put AAAEI in the odd places and CMMTT in the even places, and then vice versa:
$\binom53\cdot\binom21\cdot\binom11\cdot\binom51\cdot\binom42\cdot\binom22\cdot2=1200$

*Put AAAEI in the odd places and CXTT in the even places:
$\binom53\cdot\binom21\cdot\binom11\cdot\binom41\cdot\binom31\cdot\binom22=240$


text:
Q: Print the power of 10 - Printf in C I have to print the powers of 10 ranging from 0-19. The problem is when I want to display the first power, which should be 1 (10^0), I just can't force printf to not repeat the 0's whatsoever. I am allowed to only use one printf in my program and one { } block (which is main function).
#include <stdio.h>

int main(void) {
    int power = 19;
    for (int i = 0; i <= power; i++)
        printf("1%0*d\n",i, 0);
    return 0;
}

My output:
10 // this should be 1, but printf still puts 0 here
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000000
100000000000
1000000000000
10000000000000
100000000000000
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
10000000000000000000

A: Instead of using %d, use %s with a variable precision, and have it print from a string of zeros.  If the precision is 0, no characters are printed.
#include <stdio.h>

int main(void) {
    int power = 19;
    char zeros[] = "00000000000000000000";
    for (int i = 0; i <= power; i++)
        printf("1%.*s\n",i, zeros);
    return 0;
}

A: As commented by @Weather Vane, use unsigned long long with can handle values up to at least 18,446,744,073,709,551,615 or 264 - 1.
int main(void) {
  unsigned long long power = 0;
  for (int i = 0; i <= 19; i++)
    printf("%d %llu\n", i, power = power ? power*10 : 1);
  return 0;
}

Output
0 1
1 10
2 100
...
17 100000000000000000
18 1000000000000000000
19 10000000000000000000

Or if one does not like to hard code initialization stings like "00000000000000000000",  assign the elements in the same loop.
Note "%.*s" can print a non- null character terminated char array.
#define MAX10POWER 30

int main(void) {
  char zeros[MAX10POWER];
  for (int i = 0; i <= MAX10POWER; zeros[i++] = '0')
    printf("%d 1%.*s\n", i, i, zeros);
  return 0;
}

Output
0 1
1 10
2 100
...
28 10000000000000000000000000000
29 100000000000000000000000000000
30 1000000000000000000000000000000

Or a sneaky variation of Weather Vane good answer to go up to 21.
int main(void) {
  for (unsigned long long power = 1, i = 0; i <= 21; i++, power *= 8)
    printf("%lld %llo\n", i, power);
}

A: You can achieve the desired result like this:
#include <stdio.h>

int main(void) {
    unsigned long long power = 1;
    for (int i = 0; i <= 19; i++, power *= 10)
        printf("%llu\n", power);
    return 0;
}


text:
Q: How to cast an Xrm.EntityCollection to a List? Overview:
I'm coding a FetchXML query to return users with disabled mailboxes in a Dynamics 2015 online CRM instance. Now I've come to a stage where the query results need to be bound to a ListView. (The project is using the Dynamics SDK 2015 libs.)
In order to do this I've tried to cast the returned result which is an EntityCollection -> to a list. But the CRMSDKTypeProxy can't be found in my code for the cast.
I was following this example's second answer in order to do the casting:
Convert Entity Collection to Ilist where Entity Collection does not implement IEnumerable
Question:
Does anyone know how to reference the CRMSDKTypeProxy? Or any alternative way to cast my collection to a list?
Code: (short example)
if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
{
    CrmServiceClient svcClient = ctrl.CrmConnectionMgr.CrmSvc;
    if (svcClient.IsReady)
    {
        // Get data from CRM .
        string DisabledMailBoxUsersFetchXML =
            @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                <entity name='systemuser'>
                <attribute name='fullname' />
                <attribute name='businessunitid' />
                <attribute name='title' />
                <attribute name='address1_telephone1' />
                <attribute name='positionid' />
                <attribute name='systemuserid' />
                <order attribute='fullname' descending='false' />
                <link-entity name='mailbox' from='mailboxid' to='defaultmailbox' alias='aa'>
                    <filter type='and'>
                    <condition attribute='statecode' operator='eq' value='1' />
                    </filter>
                </link-entity>
                </entity>
            </fetch>";

        var DisabledMailBoxUsersResult = svcClient.GetEntityDataByFetchSearchEC(DisabledMailBoxUsersFetchXML);

        if (DisabledMailBoxUsersResult != null)
        {
            //perform the cast here --->
            var disabledMailBoxUsersList = (from t in DisabledMailBoxUsersResult.Entities select t as CRMSDKTypeProxy.SystemUser).ToList();
            disabledMailboxUserLBx.ItemsSource = disabledMailBoxUsersList;
        }
        else
            MessageBox.Show("All user's mailboxes are approved..");

    }
}

A: @Henk van Boeijen is partially correct. Rather than use the service.Retrieve in his example replace it with your svcClient.GetEntityDataByFetchSearchEC(DisabledMailBoxUsersFetchXML) call.
var userList = svcClient.GetEntityDataByFetchSearchEC(DisabledMailBoxUsersFetchXML).Entities.Select(e => e.ToEntity<SystemUser>());

If your'e not using the early bound entities then you can simply call .ToList() on the Entity collection.
var userList = svcClient.GetEntityDataByFetchSearchEC(DisabledMailBoxUsersFetchXML).Entities.ToList();

The Entities property of the EntityCollection is a DataCollection which extends the Collection object and you can call the usual methods.

A: You can use the ToEntity<T> method to do the conversion to a strong typed entity like this: (In this snippet service is an object implementing the IOrganizationService interface and query is a QueryExpression object.)
// RetrieveMultiple will never return null, so this one-liner is safe to use.
var userList = service.RetrieveMultiple(query)
    .Entities
    .Select(e => e.ToEntity<SystemUser>())
    .ToList();

I noticed you are using the CrmServiceClient in the Microsoft.Xrm.Tooling.Connector namespace. This was introduced in Dynamics CRM 2013.
Your code could look like this:
var userList = svcClient.OrganizationServiceProxy
    .RetrieveMultiple(new FetchExpression(fetchXml))
    .Entities
    .Select(e => e.ToEntity<SystemUser>())
    .ToList();

and alternatively this should work too:
var userList = svcClient.GetEntityDataByFetchSearchEC(fetchXml)
    .Entities
    .Select(e => e.ToEntity<SystemUser>())
    .ToList();


text:
Q: The use of inline functions in Objective-C I do not understand the point of 'inline functions'.
I know they are faster (such as macros) than ordinary functions, but why isn't every function an 'inline-function'?

A: Functions that are called from more than one place in code could be inlined, but the expense of that (ever so slight) performance boost is code size. Generally it's considered better to add the few instructions to make a subroutine call than it is to consume additional space inlining a function.
Functions that are called from exactly one place may be inlined without extra overhead.

A: *

*Code size - if a function is called from multiple locations duplicating the code everywhere can quickly cause significant growth in overall code size.

*Code size - Infinite! It is simply impossible to inline code which is recursive, directly or indirectly.


text:
Q: java.lang.UnsupportedOperationException: The application must supply JDBC connections in Spring JPA JNDI example I am using Spring + Spring Data JPA using JNDI example. In this example I've developed the test case which calls one JPA Method, when I execute that I see the following error
java.lang.UnsupportedOperationException: The application must supply JDBC connections
    at org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl.getConnection(UserSuppliedConnectionProviderImpl.java:62)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:56)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1858)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1835)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1815)
    at org.hibernate.loader.Loader.doQuery(Loader.java:899)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
    at org.hibernate.loader.Loader.doList(Loader.java:2522)
    at org.hibernate.loader.Loader.doList(Loader.java:2508)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
    at org.hibernate.loader.Loader.list(Loader.java:2333)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
    at com.transcelerate.common.jpa.repository.DemoTest.testgetStudyUserRolesBySite(JPATest.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

JPADemoTest.java
public class JPADemoTest {
    private static EntityManager em = null;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        if (em == null) {
            em = (EntityManager) Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
        }
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void testgetStudyUserRolesBySite(){
        String queryStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";  // This will be our native Jpa

        TypedQuery<StudentEntity> query = em.createQuery(queryStr, StudentEntity.class);

        List<StudentEntity> entities = query.getResultList();

        if(entities != null){
            System.out.println("Size : "+entities.size());
            for (UserRoleMapEntity userRoleMapEntity : entities) {
                StudentEntity studentEntity = userRoleMapEntity.getUserProfile();
                System.out.println("FIRSTNAME : "+studentEntity.getFirstName());
                System.out.println("LASTNAME  : "+studentEntity.getLastName());
            }
        }
    }
}

application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd         http://www.springframework.org/schema/data/jpa  http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <tx:annotation-driven transaction-manager="com.common.google.jpa.transactionManager" />
    <context:component-scan base-package="com.common.google.jpa" />

    <jpa:repositories base-package="com.common.google.jpa.repository,com.common.google.jpa.repository.custom"
                      transaction-manager-ref="com.common.google.jpa.transactionManager" />

    <bean id="com.common.google.database.transcelerateDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:XXX/datasources/Test" />
    </bean>
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="com.common.google.jpa.transactionManager"
          class="org.springframework.orm.jpa.JpaTransactionManager"
          p:entityManagerFactory-ref="com.common.google.jpa.entityManagerFactory" />

    <bean id="com.common.google.jpa.entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:dataSource-ref="com.common.google.database.transcelerateDataSource"
          p:jpaVendorAdapter-ref="vendorAdapter">
        <property name="persistenceUnitName" value="com.common.google.jpa.persistenceUnit"/>
    </bean>

    <bean id="vendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
          p:database="ORACLE"
          p:showSql="true" />
</beans>

persistence.xml
<?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="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <class>com.common.google.jpa.entity.StudentEntity</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
            <property name="hibernate.listeners.envers.autoRegister" value="false" />
            <property name="hibernate.bytecode.use_reflection_optimizer" value="false" />
            <property name="hibernate.jdbc.batch_size" value="20" />
            <property name="hibernate.order_inserts" value="true" />
            <property name="hibernate.order_updates" value="true" />
        </properties>
    </persistence-unit>
</persistence>


text:
Q: run rake task from crontab I use Ubuntu, I try run my rake task from cron
My rake task:
namespase :import do
   task :import_twitter => :environment do
      puts "Twitter importing...."
   end
end

schedule.rb file
every 1.minutes do
  rake "import:import_twitter", :output => {:error => 'error.log', :standard => 'cron.log'}
end

with whenever I generate crontab task
 # Begin Whenever generated tasks for: /home/administrator/www/my_application/config/schedule.rb
    PATH=/usr/local/rvm/gems/ruby-1.9.2-p0/bin:/bin:/usr/local/rvm/rubies/ruby-1.9.2-p0/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

    * * * * * cd /home/administrator/www/my_application && RAILS_ENV=production /usr/bin/env rake import:import_twitter >> cron.log 2>> error.log

# End Whenever generated tasks for: /home/administrator/www/my_application/config/schedule.rb

In crontab error.log I have
/usr/local/rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:340:in `bin_path': can't find executable rake for rake-0.8.7 (Gem::Exception)
    from /usr/local/rvm/gems/ruby-1.9.2-p0/bin/rake:19:in `<main>'

But when I run this task from console it work
path_to_my_project >rake  import:import_twitter

What's wrong?

A: I have the same issue with rvm and whenever. If I want it's works I define the HOME VARIABLE and comment the PATH variable and it's works.
I thinks it's a rvm issue with loading of your environment.
# Begin Whenever generated tasks for: supermarmite
SHELL=/bin/bash
HOME=/var/rails/supermarmite
#PATH=/var/rails/supermarmite/.rvm/gems/ruby-1.9.2-p0/bin:/var/rails/supermarmite/.rvm/gems/ruby-1.9.2-p0@global/bin:/var/rails/supermarmite/.rvm/rubies/ruby-1.9.2-p0/bin:/var/rails/supermarmite/.rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/local/mongodb/bin

0 * * * * source ~/.bashrc && cd /var/rails/supermarmite/site/releases/20100930044915 && RAILS_ENV=production rake -s evaluate_notify

# End Whenever generated tasks for: supermarmite


text:
Q: DRF Django filter range for a CharField I needed to save creation time as string in model, so I used CharField.
But now I have problem filtering by queryparams for obtain objects in range of two times. I see that 'lte' and 'gte' are not working for strings.
Anyone have some ideas on how i could do that?


text:
Q: invalid operands of types 'volatile uint8_t* and 'uint8_t (*) I have problem with address/pointer conversion
I had followed code with OOTB recive (uint8_t* Buf, uint32_t *Len);  function, that is runned asynchronously when data interrupt is recived
uint8_t UserRxBufferFS[APP_RX_DATA_SIZE]; //static buffer

volatile uint8_t * __usrRxIndex = UserRxBufferFS; //volatile pointer to data end

static int8_t recive (uint8_t* Buf, uint32_t *Len)
{
    uint8_t result = USBD_OK;
    //copy *Len number of data from Buf to UserRxBufferFS
    memcpy(UserRxBufferFS+__usrRxIndex, Buf, *Len);

    if( (uint32_t)( (__usrRxIndex )- UserRxBufferFS) + *Len > 0xff){ //calculate buffer overflow
        __usrRxIndex = UserRxBufferFS; //buffer
    } else {
        __usrRxIndex += *Len;
    }
}

Then I trying to catch end of data by volatile __usrRxIndex, that is updated every time when data are captured.
But When I trying to compile this using g++ compilator I got error:
error: invalid operands of types 'volatile uint8_t* {aka volatile unsigned char*}' and 'uint8_t (*)[512] {aka unsigned char (*)[512]}' to binary 'operator-'

I made some workaround and calculate each address as number and then do substraction but my question is why g++ compilator dont allow arrays and pointer substraction? Is some easy way to not get this error?

A: In
memcpy(UserRxBufferFS+__usrRxIndex, Buf, *Len);

That addition should not compile and it does not make sense. You probably want:
memcpy(__usrRxIndex, Buf, *Len);

Another thing is that you detect buffer overflow after memcpy already corrupted memory. It needs to detect the buffer overflow before memcpy.


text:
Q: Rails zip array matching by column I have two arrays and i'm using a zip method to join them together in a loop. I'm having an issue when a record doesn't exist in the zip method it throws out the order of the data.
For example:
My view
<% @temperature.zip(@rain).each do |temp, rain| %>
 <%= temp.site_no %> | <%= temp.temperature %> | <%= rain.present? ? rain.total_rain : '0' %>
<% end %>

Should display data in a manner of:
Site no | Temp | Rain
   1    |  20  |  10
   2    |  22  |  0
   3    |  18  |  3

But because site two doesn't exist in the @rain zip method it places the second row of data at the end. I have two variables as i'm accessing the rain total at 8am every day.
Controller
@temperature = Weather.select('DISTINCT ON(site_no) site_no, temperature, lat, long, timestamp').group(:site_no, :temperature, :lat, :long, : timestamp).order(: site_no).where('timestamp > ?', 7.days.ago)
@rain = Weather.select('site_no, SUM(rain) as total_rain').where('timestamp > ?', 7.days.ago).where('timestamp::time = ?', "08:00").group(:site_no)

So site 2 has no rain at 8am for any days selected, so therefore doesn't exist in the @rain variable. I've tried to match via conditionals by site_no, but still no luck.
Schema
create_table "weathers", force: :cascade do |t|
 t.integer "site_no"
 t.decimal "temperature"
 t.decimal "rain"
 t.datetime "timestamp"
 t.decimal "lat"
 t.decimal "long"
end

A: The correct way to approach is this setting up a two table system and grouping, joining and selecting aggregates.
# rails g model site name lat:decimal lon:decimal
class Site < ApplicationRecord
  # This is a truely ridiculous name
  # @see https://en.wikipedia.org/wiki/Weathers_(band)
  has_many :weathers

  def self.with_aggregates(from: 7.days.ago, to: Time.current)
    w = Weather.arel_table
    left_joins(:weathers)
      .select(
        :id,
        w[:rain].sum.as('total_rain'),
        w[:temperature].average.as('average_temperature'),
        w[:temperature].maximum.as('high_temperature'),
        w[:temperature].minimim.as('low_temperature')
      )
      .group(:id)
      .where(weathers: { timestamp: from..to })
  end
end

# for the love of god use the correct terms
# Observation or Forecast instead of abusing the english language
class Weather < ApplicationRecord
  belongs_to :site # Use `site_id` instead of `site_no`.
end

This will let you simple display it without zipping anything as you're actually doing it right and letting the database do the number crunching.
<% Site.with_aggregates.each do |site| %>
 <%= site.id %> | <%= site.average_temperature %> | <%= site.total_rain %>
<% end %>


text:
Q: Nodejs: How to catch exception in net.createServer.on("data",...)? I've got a standard socket-server (NO HTTP) setup as follows (contrived):
var server = net.createServer(function(c) { //'connection' listener
  c.on('data', function(data) {
    //do stuff here
    //some stuff can result in an exception that isn't caught anywhere downstream,
    //so it bubbles up. I try to catch it here.
    //this is the same problem as just trying to catch this:
    throw new Error("catch me if you can");
  });
}).listen(8124, function() { //'listening' listener
   console.log('socket server started on port 8124,');
});

Now the thing is I've got some code throwing errors that aren't catched at all, crashing the server. As a last measure I'd like to catch them on this level, but anything I've tried fails.

*

*server.on("error",....)

*c.on("error",...)
Perhaps I need to get to the socket instead of c (the connection), although I'm not sure how.
I'm on Node 0.6.9
Thanks.

A: process.on('uncaughtException',function(err){
   console.log('something terrible happened..')
})

A: You should catch the Exceptions yourself.  There is no event on either connection or server objects which would allow you to handle exception the way you described.  You should add exception handling logic into your event handlers to avoid server crash like this:
c.on('data', function(data) {
  try {
     // even handling code
  }
  catch(exception) {
    // exception handling code
  }