text:
Q: Unexpected segfault in memcmp The following simple program segfaults for me:
#include <string.h>
int main()
{
    void* voidp = NULL;
    char zeroes[sizeof(void*)];
    memset(zeroes, 0, sizeof(void*));
    int res = memcmp(&voidp, zeroes, sizeof(void*));
    return 0;
}

The debugger reveals the segfault is in the memcmp.
My machine is running 64-bit Ubuntu 8.04, gcc version is 4.2.4.
It runs fine on other machines that I've tried (both 32-bit or 64-bit).
Any ideas as to what is going on?
UPDATE: Here's the assembly code:
    .file   "failed.c"
    .text
.globl main
    .type   main, @function
main:
.LFB2:
    pushq   %rbp
.LCFI0:
    movq    %rsp, %rbp
.LCFI1:
    subq    $32, %rsp
.LCFI2:
    movq    %fs:40, %rax
    movq    %rax, -8(%rbp)
    xorl    %eax, %eax
    movq    $0, -32(%rbp)
    leaq    -16(%rbp), %rdi
    movl    $8, %edx
    movl    $0, %esi
    call    memset
    leaq    -16(%rbp), %rsi
    leaq    -32(%rbp), %rdi
    movl    $8, %edx
    call    memcmp
    movl    %eax, -20(%rbp)
    movl    $0, %eax
    movq    -8(%rbp), %rdx
    xorq    %fs:40, %rdx
    je  .L3
    call    __stack_chk_fail
.L3:
    leave
    ret
.LFE2:
    .size   main, .-main
    .section    .eh_frame,"a",@progbits
.Lframe1:
    .long   .LECIE1-.LSCIE1
.LSCIE1:
    .long   0x0
    .byte   0x1
    .string "zR"
    .uleb128 0x1
    .sleb128 -8
    .byte   0x10
    .uleb128 0x1
    .byte   0x3
    .byte   0xc
    .uleb128 0x7
    .uleb128 0x8
    .byte   0x90
    .uleb128 0x1
    .align 8
.LECIE1:
.LSFDE1:
    .long   .LEFDE1-.LASFDE1
.LASFDE1:
    .long   .LASFDE1-.Lframe1
    .long   .LFB2
    .long   .LFE2-.LFB2
    .uleb128 0x0
    .byte   0x4
    .long   .LCFI0-.LFB2
    .byte   0xe
    .uleb128 0x10
    .byte   0x86
    .uleb128 0x2
    .byte   0x4
    .long   .LCFI1-.LCFI0
    .byte   0xd
    .uleb128 0x6
    .align 8
.LEFDE1:
    .ident  "GCC: (GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)"
    .section    .note.GNU-stack,"",@progbits

UPDATE: (This is supposed to be a comment but doesn't fit into 600 characters). When I try sudo apt-get install libc6, I get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
libc6 is already the newest version.
You might want to run `apt-get -f install' to correct these:
The following packages have unmet dependencies:
  libc6: Depends: libc-bin (= 2.11.1-0ubuntu7.5) but it is not installable
         Depends: findutils (>= 4.4.0-2ubuntu2) but 4.2.32-1ubuntu2 is to be installed
  libc6-dev: Depends: libc6 (= 2.7-10ubuntu5) but 2.11.1-0ubuntu7.5 is to be installed
  libc6-i386: Depends: libc6 (= 2.7-10ubuntu5) but 2.11.1-0ubuntu7.5 is to be installed
  locales: Depends: belocs-locales-bin (>= 2.4-2.2ubuntu2) but it is not going to be installed
  locales-all: Depends: glibc-2.11-1 but it is not installable
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Finally, if I try to do sudo apt-get -f install, I get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
libc6 is already the newest version.
You might want to run `apt-get -f install' to correct these:
The following packages have unmet dependencies:
  libc6: Depends: libc-bin (= 2.11.1-0ubuntu7.5) but it is not installable
         Depends: findutils (>= 4.4.0-2ubuntu2) but 4.2.32-1ubuntu2 is to be installed
  libc6-dev: Depends: libc6 (= 2.7-10ubuntu5) but 2.11.1-0ubuntu7.5 is to be installed
  libc6-i386: Depends: libc6 (= 2.7-10ubuntu5) but 2.11.1-0ubuntu7.5 is to be installed
  locales: Depends: belocs-locales-bin (>= 2.4-2.2ubuntu2) but it is not going to be installed
  locales-all: Depends: glibc-2.11-1 but it is not installable
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
botond@adaptive1:~$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  vim-runtime linux-libc-dev mysql-common openssh-blacklist
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  libdns35
The following packages will be REMOVED:
  adduser apparmor apparmor-utils apt apt-file apt-utils aptitude at atop base-files base-passwd bash bash-completion bind9-host binutils bsdmainutils bsdutils bzip2 command-not-found
  console-setup console-terminus console-tools coreutils cpio cpp cpp-4.2 cron curl dash debconf debconf-i18n debianutils dhcp3-client dhcp3-common diff dmidecode dmsetup dnsutils dosfstools dpkg
  e2fslibs e2fsprogs ed eject ethtool fdutils file findutils friendly-recovery ftp fuse-utils g++ g++-4.2 g++-4.2-multilib gcc gcc-4.2 gcc-4.2-multilib gdb-minimal gettext-base gnupg gpgv grep
  groff-base grub gzip hdparm hostname ifupdown info initramfs-tools initscripts inputattach iproute iptables iputils-arping iputils-ping iputils-tracepath klogd laptop-detect less lib32gcc1
  lib32gomp1 lib32stdc++6 libacl1 libapr1 libaprutil1 libapt-pkg-perl libatm1 libattr1 libbind9-30 libblkid1 libboost-dev libbz2-1.0 libc6 libc6-dev libc6-dev-i386 libc6-i386 libcap1
  libck-connector0 libcomerr2 libconfig-file-perl libconsole libcurl3 libcurl3-gnutls libcwidget3 libdb-dev libdb4.6 libdb4.6++ libdb4.6++-dev libdb4.6-dev libdbd-mysql-perl libdbi-perl
  libdbus-1-3 libdevmapper1.02.1 libedit2 libelfg0 libexpat1 libfribidi0 libfuse2 libgc1c2 libgcc1 libgcrypt11 libgdbm3 libglib2.0-0 libgnutls13 libgomp1 libgpg-error0 libgpmg1
  libhtml-parser-perl libhtml-tagset-perl libhtml-tree-perl libidn11 libisc35 libisccc30 libisccfg30 libiw29 libkeyutils1 libkrb53 libldap-2.4-2 liblist-moreutils-perl liblocale-gettext-perl
  liblwres30 liblzo2-2 libmagic1 libmysqlclient15off libncurses5 libncursesw5 libneon27 libnet-daemon-perl libnewt0.52 libntfs-3g23 libopencdk10 libpam-modules libpam0g libparted1.7-1 libpcap0.8
  libpcre3 libplrpc-perl libpopt0 libpq5 libreadline5 libreadline6 librpc-xml-perl libsasl2-2 libsasl2-modules libselinux1 libsepol1 libsigc++-2.0-0c2a libslang2 libsqlite3-0 libss2 libssl0.9.8
  libstdc++6 libstdc++6-4.2-dev libsvn1 libsysfs2 libtasn1-3 libterm-readkey-perl libtext-charwidth-perl libtext-iconv-perl libtext-wrapi18n-perl liburi-perl libusb-0.1-4 libuuid1 libvolume-id0
  libwrap0 libwww-perl libx11-6 libx11-data libxau6 libxcb-xlib0 libxcb1 libxdmcp6 libxext6 libxml-parser-perl libxml2 libxmuu1 linux-image-2.6.24-23-server linux-image-server linux-server
  linux-ubuntu-modules-2.6.24-23-server locales locales-all login logrotate lsb-base lsb-release lshw lsof ltrace lvm2 lzma make makedev man-db mawk menu mii-diag mktemp mlocate module-init-tools
  mount mtr-tiny mysql-client-5.0 mysql-server mysql-server-5.0 nano ncurses-base ncurses-bin net-tools netbase netcat netcat-traditional ntfs-3g ntp ntpdate openssh-client openssh-server parted
  passwd pciutils pcmciautils perl perl-base perl-modules popularity-contest ppp pppconfig pppoeconf procps psmisc python python-apt python-central python-cxx python-cxx-dev python-dev
  python-gdbm python-gnupginterface python-minimal python-mysqldb python-pkg-resources python-pycurl python-setuptools python-simplejson python-support python2.5 python2.5-dev python2.5-minimal
  reiserfsprogs rsync screen sed sshfs startup-tasks strace subversion sudo sysklogd system-services sysvutils tar tasksel tasksel-data tcpd tcpdump telnet time tzdata ubuntu-keyring
  ubuntu-minimal ubuntu-standard ucf udev ufw update-inetd update-manager-core upstart upstart-compat-sysv upstart-logd usbutils util-linux util-linux-locales uuid-runtime valgrind vim vim-common
  vim-tiny w3m wget whiptail wireless-tools wpasupplicant x11-common xauth zlib1g
The following packages will be upgraded:
  libdns35
WARNING: The following essential packages will be removed.
This should NOT be done unless you know exactly what you are doing!
  apt libc6 (due to apt) libgcc1 (due to apt) libstdc++6 (due to apt) base-files base-passwd (due to base-files) libpam-modules (due to base-files) bash debianutils (due to bash) libncurses5 (due
  to bash) bsdutils coreutils libacl1 (due to coreutils) libselinux1 (due to coreutils) dash mktemp (due to debianutils) diff dpkg lzma (due to dpkg) e2fsprogs e2fslibs (due to e2fsprogs)
  libblkid1 (due to e2fsprogs) libcomerr2 (due to e2fsprogs) libss2 (due to e2fsprogs) libuuid1 (due to e2fsprogs) findutils grep gzip hostname login libpam0g (due to login) mount ncurses-base
  ncurses-bin perl-base python-minimal python2.5-minimal (due to python-minimal) sed sysvutils libsepol1 (due to sysvutils) tar util-linux lsb-base (due to util-linux) tzdata (due to util-linux)
  libslang2 (due to util-linux) zlib1g (due to util-linux)
1 upgraded, 0 newly installed, 316 to remove and 4 not upgraded.
4 not fully installed or removed.
Need to get 11.3kB of archives.
After this operation, 712MB disk space will be freed.
You are about to do something potentially harmful.
To continue type in the phrase 'Yes, do as I say!'
 ?]

Obviously, I didn't type "Yes, do as I say!". It seems something is really screwed up... any idea how to fix it?

A: I can affirm that on RHEL 5 with GCC 4.1.2, the code works fine, both 32-bit and 64-bit (AMD x86/64 architecture).
You've (probably) found a bug.
Maybe you should upgrade to GCC 4.5.2 (released in the last 24 hours or so - as of 2010-12-19).  Or maybe you need to upgrade the C library, but this is more likely to be a compiler issue than a library issue.


text:
Q: Netsuite integration with Visual Studio Online My company is using Netsuite to track defects and requests. I would like to use Visual Studio online to keep track of my sprint and port the defects and requests into the backlog. Is this possible?

A: You may be able to use VSO's Service Hooks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In react, when the route path is different, but same component. How can I prevent re-mounting? In react router (v2), when there is different route path, but same component.
How can we prevent remount the component, for example, unmounts the component and then mounts the component again.
It causes calling componentDidMount twice.
When there are some subscribe request, then my app will subscribe twice.
So the subscribed event will be called twice.
How can I solve it?

A: Just nest your react-router code. Like below,
  <Route component={Home}>
    <IndexRoute />
    <Route path="/" />
    <Route path="/market" />
  </Route>

Just define parent  tag with the component which you want to call once, and define child  tag only with the path.
Then if route path changes '/' to '/market' will not remount the component.
Below code is remounting scenario which you might don't want.
...
<Route component={Home} path="/" />
<Route component={Home} path="/trade" />

...


text: Q: Getting internal server error trying to create SSO service in Bluemix I am trying to create a Single-Sign On service in Bluemix but it keeps showing "internal server error" so I am unable to manage and configure the service.


text:
Q: Synchronized window post message using promise and custom event I'm developing a Chrome extension that fetches data from the DOM.
I have two contents scripts, one for the main frame (top-level frame) and another one for an iFrame.
I would like to be able to call a method that calls an iframe method and wait for the result.
I try to do it by using promises, post-message, and custom events.
//main-frame.js

window.addEventListener("message", this.frameMessages, false);

 const iframeElement = document.getElementById('iframeId');

function frameMessages(event){
   let dataReadyEvent = new CustomEvent('dataReady');
   iframeElement.dispatchEvent(dataReadyEvent);
}

let getDataAsync= async function getDataFromIFrame(): Promise<String> =>{
return new Promise(function (resolve) {
    chrome.runtime.sendMessage({service:'getData',frameId:frameId});
    iframeElement.addEventListener("dataReady", function dataReady() {
        resolve();
    });
}

//The promise is not been waited and there is no result :\
const data = await getDataAsync();

//iframe.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if(request.service === 'getData'){
     var element = document.getElementById(id);
      window.parent.postMessage({
                message: 'dataFromIFrame',
                frameGuid: frameGuid,
                data: element
            },
                "*"
            );
        }
    }
});


text:
Q: DMARC Report: Sometimes DKIM Fails for Mail Server IP What does it mean when some DMARC records indicate a failure for the correct server:
  <record>
    <row>
      <source_ip>1.2.3.4</source_ip>
      <count>8</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>fail</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mail.example.com</header_from>
    </identifiers>
    <auth_results>
      <spf>
        <domain>mail.example.com</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>

In the same report there are records where it passes:
 <record>
    <row>
      <source_ip>1.2.3.4</source_ip>
      <count>57</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mail.example.copm</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mail.example.copm</domain>
        <result>pass</result>
        <selector>GUID</selector>
      </dkim>
      <spf>
        <domain>mail.example.copm</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>

Would you please help me understand what this implies?

A: That implies, that 8 reported mails from same source server failed both DKIM and SPF check and 57 failed only SPF check.
So not all mails are DKIM signed (or not correctly or not sufficiently "relaxed" but the repor implies they do not have a syntactical correct signature as no selector is mentioned for the failed, left byside the fact that the implementation of reports is not very strict so this does not mean too much, probably) and there is not SPF that allows mails from mail.example.com to be sent by 1.2.3.4.


text:
Q: How to define multiple API endpoints in FastAPI with different paths but the same path parameter? I'm working on a project which uses FastAPI. My router file looks like the following:
# GET API Endpoint 1
@router.get("/project/{project_id}/{employee_id}")
async def method_one(
    project_id: str, organization_id: str, session: AsyncSession = Depends(get_db)
):

    try:
        return await CustomController.method_one(
            session, project_id, employee_id
        )
    except Exception as e:
        return custom_exception_handler(e)

# GET API Endpoint 2
@router.get("/project/details/{project_id}")
async def method_two(
    project_id: str, session: AsyncSession = Depends(get_db)
):

    try:
        return await CustomController.method_two(
            session=session, project_id=project_id
        )
    except Exception as e:
        return custom_exception_handler(e)

# GET API Endpoint 3
@router.get("/project/metadata/{project_id}")
async def method_three(
    project_id: str, session: AsyncSession = Depends(get_db)
):
    try:
        return await CustomController.method_three(
            session=session, project_id=project_id
        )
    except Exception as e:
        return custom_exception_handler(e)

The obvious expectation of workflow here is: when each of these API endpoints are triggered with their required path parameters, the controller method is executed, as defined in their body.
However, for some strange reason, when API endpoints 2 and 3 are triggered, they are executing the controller method in endpoint 1, i.e., CustomController.method_one().
Upon adding some print() statements in the method method_one() of the router, I've observed that method_one() is being called when API endpoint 2 is called, while it is actually supposed to call method_two() in the router. Same is the case with API endpoint 3.
I'm unable to understand why the method body of method_one() is getting executed, when API endpoints 2 and 3 are triggered. Am I missing out something on configuration, or something - can someone please correct me? Thanks!

A: In FastAPI, as described in this answer, because endpoints are evaluated in order (see FastAPI's about how order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.e., /project/details/... and /project/metadata/..., the first endpoint is triggered, using details or  metadata as the project_id parameter.
Solution
Thus, you need to make sure that the other two endpoints are declared before the one for /project/{project_id}/.... For example:
# GET API Endpoint 1
@router.get("/project/details/{project_id}")
    # ...

# GET API Endpoint 2
@router.get("/project/metadata/{project_id}")
    # ...

# GET API Endpoint 3
@router.get("/project/{project_id}/{employee_id}")
    # ...


text:
Q: Rails Bundler on windows refuses to install hpricot (even on manual gem install get Error: no such file to load -- hpricot) Upgraded to rails 3, and using Bundler for gems, in a mixed platform development group.  I am on Windows.  When I run Bundle Install it completes succesfully but will not install hpricot.  The hpricot line is:
gem "hpricot", "0.8.3", :platform => :mswin

also tried
gem "hpricot", :platform => :mswin

Both complete fine but when I try to do a "bundle show hpricot" I get:
Could not find gem 'hpricot' in the current bundle.

If I do a run a rails console and try "require 'hpricot'" I get:
LoadError: no such file to load -- hpricot

I have manually installed hpricot as well, and still get the above error.  This worked fine before moving to rails 3.

A: Try this in console and then do bundle install, it will work:
gem install hpricot --platform=mswin32

A: It may be that you are using a version of ruby that was built with MinGW in which case your platform will be 'mingw' rather than 'mswin'. Try changing your Gemfile line to the following:
gem "hpricot", "0.8.3", :platform => :mingw

And if you have other developers that are using the current setup and don't wan to break it for them, change it to this:
gem "hpricot", "0.8.3", :platforms => [:mswin, :mingw]


text:
Q: Android subscriptions - get reliable introductory price information I have an subscription item with an introductory price for 1 cycle. I am able to fetch this price within the app via the getIntroductoryPrice() method. Once a purchase has been done I am having trouble getting what exact price was paid for the subscription on the server side. In particular:

*

*On the app side, the "introductory price" info I get from the call above seems to be the same even if the user does not qualify (e.g. he is changing subscription from a full price one). Is there a way to see what price the user actually payed (from the app or server side?)

*On the server side, when I request the purchase receipt from the server I get information about the normal price, nothing on the introductory price nor what the user actually payed.
Is there any way for me to get reliable information on how much the user actually payed for subscriptions that include an introductory period?


text:
Q: Subdomains loading index.php for web root I'm trying to setup nginx for local dev/testing. Subdomains load up the main index.php and I cannot figure out why. The problem is that nowingnews.localhost.com and wasob.mylocalhost.com both load the index.php of http://mylocalhost/index.php.
Here is the virtualhost config for nowingnews.mylocalhost.com
server {

#Nginx should listen on port 80 for requests to yoursite.com
listen 80;
server_name nowingnews.mylocalhost.com;

#Create access and error logs in /var/log/nginx
access_log /var/log/nginx/nowingnews.access_log;
error_log /var/log/nginx/nowingnews.error_log debug;

root /var/www/html/nowingnews;

 #location / {
  #try_files $uri $uri/ /nowingnews/index.php;
  #}

#Specifies that Nginx is looking for .php files
location ~ /.*\.php$ {
include fastcgi_params;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
#if (!-f $document_root$fastcgi_script_name) {
#    return 404;
#}

fastcgi_index /index.php;

# SCRIPT_FILENAME parameter is used for PHP FPM determining
#  the script name. If it is not set in fastcgi_params file,
# i.e. /etc/nginx/fastcgi_params or in the parent contexts,
# please comment off following line:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

 # Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";

 # include the fastcgi_param setting
include /etc/nginx/fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
}
}

And here is the default config
server {

#Nginx should listen on port 80 for requests to yoursite.com
listen 80;
server_name localhost;

#Create access and error logs in /var/log/nginx
access_log /var/log/nginx/default.access_log;
error_log /var/log/nginx/default.error_log crit;

root /var/www/html/;
#The homepage of your website is a file called index.php
index index.php index.htm index.html;

#Specifies that Nginx is looking for .php files
location ~ /.*\.php$ {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;

# Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";
include fastcgi_params;

# SCRIPT_FILENAME parameter is used for PHP FPM determining
#  the script name. If it is not set in fastcgi_params file,
# i.e. /etc/nginx/fastcgi_params or in the parent contexts,
# please comment off following line:
fastcgi_index index.php;
fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
}

}

include  "/etc/nginx/sites-enabled/*";


text:
Q: Compiler "Optimizes" Out Object Initialization Function I have an object that I need to populate before using called pipelineInfo. To populate the object I use a function called createPipelineInfo. This works perfectly well when I use visual studios to compile a debug build but when I try to compile a release build the compiler "optimizes" out the entire createPipelineInfo function.
Here is the call to initialize the object and its use:
VkGraphicsPipelineCreateInfo pipelineInfo = createPipelineInfo(shaderStages, vertexInputInfo, inputAssembly, viewportState, rasterizer,
    multisampling, colorBlending, pipelineLayout, renderPass);

if (vkCreateGraphicsPipelines(logicalDevice, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
    throw std::runtime_error("failed to create graphics pipeline!");
}

The following is the createPipelineInfo function:
inline static VkGraphicsPipelineCreateInfo createPipelineInfo(
    const std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages,
    const VkPipelineVertexInputStateCreateInfo& vertexInputInfo,
    const VkPipelineInputAssemblyStateCreateInfo& inputAssembly,
    const VkPipelineViewportStateCreateInfo& viewportState,
    const VkPipelineRasterizationStateCreateInfo& rasterizer,
    const VkPipelineMultisampleStateCreateInfo& multisampling,
    const VkPipelineColorBlendStateCreateInfo& colorBlending,
    const VkPipelineLayout& pipelineLayout,
    const VkRenderPass& renderPass) {

    VkGraphicsPipelineCreateInfo pipelineInfo{};

    //Shader Stage
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.stageCount = 2;
    pipelineInfo.pStages = shaderStages.data();

    //Fixed Pipeline Stage
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    //pipelineInfo.pDepthStencilState = &depthStencil;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.pDynamicState = nullptr; // Optional

    //Pipeline Layout
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.renderPass = renderPass;
    pipelineInfo.subpass = 0;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

    return pipelineInfo;
}

On the other hand if I copy the body of the function and dump it in place of the function call everything works perfectly fine.
VkGraphicsPipelineCreateInfo pipelineInfo{};

//Shader Stage
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages.data();

//Fixed Pipeline Stage
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
//pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = nullptr; // Optional

//Pipeline Layout
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

if (vkCreateGraphicsPipelines(logicalDevice, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
    throw std::runtime_error("failed to create graphics pipeline!");
}

I'm trying to figure out why the compiler is optimizing out the function call and failing that trying to develop a work around that doesn't involve dumping the body of the function in place of every call to the function.

A: wild guess: this parameter is passed by copy
const std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages

so when taking the address of its contents here with data method call:
pipelineInfo.pStages = shaderStages.data();

you invoke undefined behaviour. The compiler isn't smart enough to 1) warn you about taking a reference to temporary because of the complexity of the calls, and 2) it doesn't automatically perform copy elision on parameter passing.
Fix: pass it by reference (note that all other parameters use a by reference mode for a reason)
const std::array<VkPipelineShaderStageCreateInfo, 2> &shaderStages


text:
Q: Return all possible sums of number array I have gone over my code a million times and can't figure out the problem. I have made a code that will return all the possible sums of numbers within an array. It works fine when there are 3 numbers in the array but if I add another number to the array it replaces a few of what should be sums with NaN.
Ex:

array = [4, 6, 3, 7] is returning:
[ 20, 16, 10, 13, 9, 14, 11, 7, 17, NaN, 13 ]
and NaN should be "10"

array = [4, 6, 3, 7];
newarray = [0];
for (i = 0; i < array.length; i++) {
    newarray[0] += array[i];
}
x = 0;
y = 1;
for (i = 0; i < array.length; i++) {
    newarray.push((newarray[0]-array[i]));
    if (i !== 0) {
        y = y+array.length;
    }
    x = i;
    while (x < array.length) {
        if (x != i) {
            newarray.push((newarray[y]-array[x]));
        }
        x++;
    }
}
console.log(newarray);`

The fact that I am getting NaN in some slots where numbers should be leads me to believe there is a problem with variable x in the while loop but my brain is being racked on where the issue actually is.
http://jsfiddle.net/nsjY6/

A: newarray[y] here cause NaN
newarray.push((newarray[y - 1]-array[x]));

[ 20, 16, 14, 17, 13, 14, 10, 6, 17, 10, 13 ]
add my version

var array = [4, 6, 3, 7];

var newarray = [];

for (i=0; i< Math.pow(2, array.length); i++) {

    var s = i.toString(2)
    var t = 0;
    for (c in s) t += s[c] * array[c];

    newarray.push(t);
}

console.log(newarray);


text:
Q: C# generics syntax for multiple type parameter constraints
Possible Duplicate:
Generic methods and multiple constraints

I need a generic function that has two type constraints, each inheriting from a different base class. I know how to do this with one type:
void foo<T>() where T : BaseClass

However, I don't know how to do this with two types:
void foo<TOne, TTwo>() where TOne : BaseOne // and TTwo : BaseTwo ???

How do you do this? (using .NET 2)

A: void foo<TOne, TTwo>()
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#constraining-multiple-parameters


text:
Q: Codesigning on the mac with dynamic resources We have a mac application that we build with jenkins and is signed on a Mac.
When the user download the dmg we add the database (with some last minute query) into the Application.app file.
The dmg is located on a CentOS server so we can't recodesign when it is shipped.
We where able to do this thanks to an exclusion in the codesigning with --resource-rules
Now with the latest update of Mavericks (10.9.5) and Yosemite we can't do this anymore because it is rendered obsolete. (see link)
So my question is: Does anyone has an idea on how to do the codesigning for Mavericks (10.9.5) and up with dynamic resources?


text:
Q: Change Data Capture vs Queueable Apex With the introduction of Change Data Capture, now there is one more way to execute Asynchronous Apex.
What are the advantages of Change Data Capture over Queueable Apex?
How Salesforce will enqueue CDC, Queuable, Future method if all three are getting executed from a single record?
Would there be any governor limits on Change Data Capture? Limits are not mentioned in CDC Guide

A: The main difference between them is "context".
A Queueable (or a @future) is called by the developer. It can be called in any operation (trigger, visualforce, flow, schedule, Aura/LWC, etc), but we have a limit on the number of queueable jobs we can schedule in a single transaction (50 in the original transaction, 1 if you are already in a future context). You control when it runs and which kind of information is available at the beggining (it can be anything: a list of ids, a single object, a string or even nothing).
A Change Data Capture trigger is run EVERYTIME there's a DML operation (create, update, delete or undelete) on a record, and it is called by Salesforce (so it does not have limits about how many triggers you can call). You don't control the input, it's always the object with a list of changed fields.

How Salesforce will enqueue CDC, Queuable, Future method if all three are getting executed from a single record?

I don't have hard info on this, but as with all Salesforce asynch calls you should NOT rely on time or order of execution. My guess is that events run before as they are "Salesforce based" and run everytime, followed by Queueable/@future by order in which they were called (they share the same queue)


text:
Q: If birthdate's are stored as type "Date" in MySQL, how would you determine if it's a user's birthday today in PHP? If birthdate's are stored as type "Date" in MySQL, how would you determine if it's a specific user's birthday today in PHP?
Is it simply a matter of grabbing the birthdate column value, doing on a explode on the -, and then checking if the day and month match the current day and month in PHP?  Or is there a simpler and less crude way of doing it?
Also, what query would you use to SELECT all users whose birthday it is today?

A: Use MySQL's date functions to extract the month and day from the users' birth dates, and compare them to the same values extracted from the current date:
SELECT * FROM table WHERE
    DAY(birthday) = DAY(CURDATE()) AND
    MONTH(birthday) = MONTH(CURDATE());

That makes sure the important values - month and day - match, regardless of the year.  Hope that helps!
PS: You might be tempted to use DAYOFYEAR as a simpler version.  Don't.  Leap years'll screw you up.
Edit: It looks like using date functions in your where clauses can really slow you down, especially in big tables.  See my last comment, below, for a bit more on that.

A: Since you'll need to exclude the year, you can use the MONTH and DAY SQL functions like so:
SELECT * FROM table WHERE MONTH(birthday) = MONTH(NOW()) AND DAY(birthday) = DAY(NOW());

Don't forget to add an index on this column or it will seriously degrade performance as data grows.
In PHP, you can just use the date function:
if (date('m-d', strtotime($row['date'])) == date('m-d'))
    //-- Today is my birthday! Hooray!

A: You could also add to your query to include a value that would be 1 if today was their birthday.  This makes it easier so in your PHP you don't have to make the comparison.
SELECT
    user_table.*,
    (MONTH(user_table.birth_date_column) = MONTH(now())
        AND DAY(user_table.birth_date_column) = DAY(now())) as birthday_today
FROM user_table

Other answers show query for getting those users whose birthday's are today

A: Find people whose birthday has the same month and day as the current date:
SELECT * from people
WHERE month(birthDate) = month(curdate())
AND dayofmonth(birthDate) = dayofmonth(curdate())

A: select * from table
where month(BirthDate) = month(curdate())
and day(BirthDate) = day(curdate());

A: For Get User list whose birthday is today in mysql field datatype must be date

$Toaday = '%'.date('m-d').'%';

$query = " select client_id,name,mobile_no from client where is_visible = 1 AND birth_date LIKE '$Toaday' ";

A: To find employees' today birthday. we can use this
SELECT *
FROM crm_employee
WHERE MONTH( dob ) = MONTH( CURDATE( ) )
AND DAYOFMONTH( dob ) = DAYOFMONTH( CURDATE( ) )


text:
Q: Getting javascript - Uncaught TypeError: Issue I am using numscroller.js for a counter but I'm getting two javascript errors:

Uncaught TypeError: Cannot read property 'top' of undefined at HTMLHeadingElement. - Line no - 40.

Can anyone help me please with the below code. It's showing the error is in the line number 40. Any help would be appreciated. Thank you in advance.
working URL - http://bluecrystaluae.com/counter/counter.html

jQuery.noConflict();

(function($) {
  $(window).on("load", function() {
    $(document).scrollzipInit();
    $(document).rollerInit();
  });

  $(window).on("load scroll resize", function() {
    $('.numscroller').scrollzip({
      showFunction: function() {
        numberRoller($(this).attr('data-slno'));
      },
      wholeVisible: false,
    });
  });

  $.fn.scrollzipInit = function() {
    $('body').prepend("

");
  };

  $.fn.rollerInit = function() {
    var i = 0;
    $('.numscroller').each(function() {
      i++;
      $(this).attr('data-slno', i);
      $(this).addClass("roller-title-number-" + i);
    });
  };

  $.fn.scrollzip = function(options) {
    var settings = $.extend({
      showFunction: null,
      hideFunction: null,
      showShift: 0,
      wholeVisible: false,
      hideShift: 0,
    }, options);
    return this.each(function(i, obj) {
      $(this).addClass('scrollzip');
      if ($.isFunction(settings.showFunction)) {
        if (!$(this).hasClass('isShown') &&
          ($(window).outerHeight() + $('#scrollzipPoint').offset().top - settings.showShift) > ($(this).offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) &&
          ($('#scrollzipPoint').offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) < ($(this).outerHeight() + $(this).offset().top - settings.showShift)
        ) {
          $(this).addClass('isShown');
          settings.showFunction.call(this);
        }
      }

      if ($.isFunction(settings.hideFunction)) {
        if (
          $(this).hasClass('isShown') &&
          (($(window).outerHeight() + $('#scrollzipPoint').offset().top - settings.hideShift) < ($(this).offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) ||
            ($('#scrollzipPoint').offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) > ($(this).outerHeight() + $(this).offset().top - settings.hideShift))
        ) {
          $(this).removeClass('isShown');
          settings.hideFunction.call(this);
        }
      }
      return this;
    });
  };

  function numberRoller(slno) {
    var min = $('.roller-title-number-' + slno).attr('data-min');
    var max = $('.roller-title-number-' + slno).attr('data-max');
    var timediff = $('.roller-title-number-' + slno).attr('data-delay');
    var increment = $('.roller-title-number-' + slno).attr('data-increment');
    var numdiff = max - min;
    var timeout = (timediff * 1000) / numdiff;
    //if(numinc<10){
    //increment=Math.floor((timediff*1000)/10);
    //}//alert(increment);
    numberRoll(slno, min, max, increment, timeout);
  }

  function numberRoll(slno, min, max, increment, timeout) { //alert(slno+"="+min+"="+max+"="+increment+"="+timeout);
    if (min <= max) {
      $('.roller-title-number-' + slno).html(min);
      min = parseInt(min) + parseInt(increment);
      setTimeout(function() {
        numberRoll(eval(slno), eval(min), eval(max), eval(increment), eval(timeout))
      }, timeout);
    } else {
      $('.roller-title-number-' + slno).html(max);
    }
  }
})(jQuery);

A: I think you forgot to return your jquery element in your plugin functions
$.fn.scrollzipInit = function() {
    return $('body').prepend("

");
};

And
$.fn.rollerInit = function() {
    var i = 0;
    return $('.numscroller').each(function() {
      i++;
      $(this).attr('data-slno', i);
      $(this).addClass("roller-title-number-" + i);
    });
 };


text:
Q: Bootstrap tabs opening tabs on another page I have a page that has bootstrap tabs on it and they are linking to the right content area on that page.
When you are lead away from that page I have the same tabs at the top that I would like to lead them back to the previous page with the right tab open.
This is what my tabs look like on the external page

Submitted

Approved

Rejected

Uploaded

As you can see I have tried linking to that page and calling out the id, which goes to the right page, but does not open that tab.
I have also tried messing around with it in jquery, but nothing valid enough to show. Any help would be much appreciated!
edit:
The tabs on the other page look like this. Just basic bootstrap tabbing.

Submitted

Approved

Rejected

Uploaded

A: I ended up working on this some more and came up with this that does select the right tab and open the right content panel
  //grabs the hash tag from the url
  var hash = window.location.hash;
  //checks whether or not the hash tag is set
  if (hash != "") {
    //removes all active classes from tabs
    $('#tabs li').each(function() {
      $(this).removeClass('active');
    });
    $('#my-tab-content div').each(function() {
      $(this).removeClass('active');
    });
    //this will add the active class on the hashtagged value
    var link = "";
    $('#tabs li').each(function() {
      link = $(this).find('a').attr('href');
      if (link == hash) {
        $(this).addClass('active');
      }
    });
    $('#my-tab-content div').each(function() {
      link = $(this).attr('id');
      if ('#'+link == hash) {
        $(this).addClass('active');
      }
    });
  }

Thank you willbeeler for the good start! :)

A: This could be greatly simplified by leveraging tab('show').
$(document).ready(function() {
   var hash = window.location.hash;

   if (hash != "")
       $('#tabs a[href="' + hash + '"]').tab('show');
   else
       $('#tabs a:first').tab('show');
});

A: i think this will work as well. i test it and it is working for me :)
$(document).ready(function() {
   var hash = window.location.hash;
   hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});

A: OK, I tested this out and it worked for me. Add the following code some place after you call jQuery. This should go on page.php (your primary page that the external page links to). Let me know if this helps.
$( document ).ready(function() {
  //grabs the hash tag from the url
  var hash = window.location.hash;
  //checks whether or not the hash tag is set
  if (hash != "") {
    //removes all active classes from tabs
    $('#tabs li').each(function() {
      $(this).removeClass('active');
    });
    //this will add the active class on the hashtagged value
    var link = "";
    $('#tabs li').each(function() {
      link = $(this).find('a').attr('href');
      if (link == hash) {
        $(this).addClass('active');
      }
    });
  }

});

EDIT: By the way, I need to give some props to the following Stack overflow question: Getting URL hash location, and using it in jQuery That's where I got that first line to find the hash variable.

A: A Little Modification that works for me:

Tab Portion:

Home

Accounts

Tab Content Portion:

Url Used in external Link:
Account</

In my Case Url looks like:
 Account


text:
Q: CakePHP - Fatal error: Call to undefined function I get the following error:

Fatal error: Call to undefined function getAvnet() in C:\xampp\htdocs\ems\app\controllers\queries_controller.php on line 23

The line is:
$ret = getAvnet('de', $searchstring);

supposedly calling
function getAvnet($country, $query)

A: You need to use
$ret = $this->getAvnet('de', $searchstring);

In general you need to use $this-> when accessing class methods and variables.
Read: http://php.net/manual/en/language.oop5.basic.php

A: $ret = $this->getAvnet('de', $searchstring);


text:
Q: Change css element style with Python Selenium I want to change the css element style using Python Selenium while doing automation to increase the height of the page. The html of the element is as follows:
<div style="overflow-y:scroll;overflow-x:hidden;height:150px;">

I know that I can use something like the code below to do this:
driver.execute_script("document.getElementById('id name').style.height = '2000px';")

or
driver.execute_script("document.getElementByClassName('class name').style.height = '2000px';")

But there is no id or class in the HTML (there's only style).

A: If no ID or class is present then please use CSS
driver.execute_script("document.getElementByCss('div[style='overflow-y:scroll']').style.height = '2000px';")

But you should check in HTML DOM for the mentioned CSS :
Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the CSS and see, if your desired element is getting highlighted with 1/1 matching node.
CSS you should check :
div[style='overflow-y:scroll']

or
div[style='overflow-y:scroll'][sytle$='height:150px;']

or
div[style='overflow-y:scroll;overflow-x:hidden;height:150px;']

Whichever has the unique entry put that in execute_script and you should be good to go after that.
Alternate way to do
element = driver.find_element_by_css_selector("div[style='overflow-y:scroll;overflow-x:hidden;height:150px;']")
driver.execute_script("arguments[0].setAttribute('style','overflow-y:scroll;overflow-x:hidden;height:2000px;')", element)


text: Q: How can I format Java Code in different IDEs as well as per pre commit hook Is there a library or maven plugin how-to auto format JAVA code against a checkstyle configuration as pre commit hook and IDE. We are working in a team where some use IDEA IntelliJ and some VS Code. How can I make sure that once the code is pushed it has the same formatting rules applied. I googled some time but I cannot find a streamlined solution. Am I missing something?


text:
Q: mysql_get_server_info() returns NULL but everything works OK The title says it all. Calling mysql_get_server_info returns (null) but everything works fine.
mysql_get_client_info() returns the correct value: 6.1.6
What can be the reason I don't receive the correct server information 5.7.17-log?

A: mysql_get_server_info assumes that there is an existing connection to a MySQL server created earlier in the running process. You'd need to call mysql_connect first, if you want it to return anything.
This is much easier to visualize (and more future proof) with mysqli_get_server_info, which takes an initialized MySQLi object as a parameter.


text:
Q: applicationWillBecomeActive in MonoTouch I'm trying to use the applicationDidBecomeActive method (and similar ones) - I can find plenty of examples in ObjC but none in Monotouch.
Have tried an override in AppDelegate and in UIViewController but the compiler finds no suitable method to override. So, how do I use this?
I want to use it (in conjunction with a timer and IdleTimerDisabled) to stop the device from going to sleep for longer than usual (it's a stopwatch-type app). Maybe I'm on the wrong track.

A: In your app delegate that inherits from UIApplicationDelegate, you can override these:
/// <summary>
/// Gets called by iOS if the app is started from scratch and is not resumed from background.
/// We have 17 seconds to leave this methos before iOS will kill the app.
/// </summary>
public override bool FinishedLaunching ( UIApplication application, NSDictionary launchOptions )

/// <summary>
/// Called if the app comes back from background or gets started. Triggered after FinishedLaunching().
/// </summary>
public override void OnActivated ( UIApplication application )

/// <summary>
/// Called if the application gets pushed to the background because the user hits the home button.
/// </summary>
public override void DidEnterBackground ( UIApplication application )

/// <summary>
/// Gets called if the app is resumed from background but NOT if the app starts first time.
/// </summary>
public override void WillEnterForeground ( UIApplication application )


text:
Q: Algunos elementos de RecyclerView desaparecen a dar Scroll estoy creando una aplicacion en Android Studio que trata del monitoreo de sensores, la informacion de los sensores la recibo de un arduino conectado a un modulo wifi HLK-RM04 configurado con una direccion ip estatica y un puerto, por medio de Socket e InputStream logro obtener la cadena de datos que es mas o menos asi:
"1,23.44,5.43:2,23.43,4.43:3,28.45:5.21:4,23.53,5.23:"
esta cadema la recibo cada 4 segundos por lo que requiero que el recyclerview actualice su vista
este es mi adaptador
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {
List<String> dataSoucer;
private RecyclerView.Adapter variantAdapter;
private RecyclerView.LayoutManager variantLayoutManager;

public myAdapter(List<String> dataSoucer) {
    this.dataSoucer = dataSoucer;
}

public void inserData(List<String> insertList){
    MyDiffUtilCallback callback=new MyDiffUtilCallback(dataSoucer,insertList);
    DiffUtil.DiffResult diffResult= DiffUtil.calculateDiff(callback);
    dataSoucer.addAll(insertList);
    diffResult.dispatchUpdatesTo(this);
}
public void updateData(List<String> newtList){
   MyDiffUtilCallback callback=new MyDiffUtilCallback(dataSoucer,newtList);
    DiffUtil.DiffResult diffResult= DiffUtil.calculateDiff(callback);
    dataSoucer.clear();
    dataSoucer.addAll(newtList);

    diffResult.dispatchUpdatesTo(this);
    notifyDataSetChanged();
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View itemView= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
    myViewHolder.setIsRecyclable(false);
    String cadena=dataSoucer.get(i);
    String[] reparto=cadena.split(",");
    myViewHolder.estanque.setText(reparto[0]);
    myViewHolder.temperatura.setText(reparto[1]);
    myViewHolder.oxigeno.setText(reparto[2]);

   // notifyDataSetChanged();

}

@Override
public int getItemCount() {
    return dataSoucer.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    TextView estanque,temperatura,oxigeno;
    TextView name_estanque,name_temperatura,name_oxigeno;
    private RecyclerView recicler;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        name_estanque=(TextView)itemView.findViewById(R.id.name_estanque);
        name_temperatura=(TextView)itemView.findViewById(R.id.name_temperatura);
        name_oxigeno=(TextView)itemView.findViewById(R.id.name_oxigeno);
        estanque=(TextView)itemView.findViewById(R.id.estanque);
        temperatura=(TextView)itemView.findViewById(R.id.temperatura);
        oxigeno=(TextView)itemView.findViewById(R.id.oxigeno);

    }
}

como pueden ver tengo un metodo que actualiza pero en la vista del recycler view al dar un poco scroll algunos elemtos desaparecen, en cuenta que tengo un Thread funcionando cada 3 segundos y esto haria que reciba los datos por medio de socket y los pase al adaptador y dibuje en el recyclerview
Este es mi ActivityMain
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List<String> datasourcer=new ArrayList<>();
private int contador_prueba=1;
private myAdapter adapter;
private NestedScrollView nested;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView=(RecyclerView)findViewById(R.id.recycler_view);

   recyclerView.setHasFixedSize(true);
   recyclerView.setLayoutManager(new LinearLayoutManager(this));

     adapter=new myAdapter(datasourcer);
     recyclerView.setAdapter(adapter);

    recyclerView.getItemAnimator().setChangeDuration(0);
    RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); }
    new Thread(new Client()).start();

}

 public void setPlayersDataAdapter(){
    int contar_temp=1;

    contador_prueba+=1;
    String contar_temp2=String.valueOf(contador_prueba);

    String cadena="1,"+contar_temp2+",5.32,:2,34.23,5.22,:3,23.23,4.32,:4,24.21,5.12,:5,23.56,6.78,:6,21.34,6.45,:7,45.34,7.23,:";
    String[] cadena2=cadena.split(":");

    int contador_for=cadena2.length;
    List<String> update=new ArrayList<>();
    try {

        int contador_array=0;

        for (int i=0;i<=contador_for;i++){
            update.add(cadena2[i]);
            adapter.updateData(update);
            adapter.notifyDataSetChanged();

        }
        contador_prueba+=1;
        // mAdapter.notifyDataSetChanged();

    }catch (Exception e){

    }

}

class Client extends Thread {

    public void run()
    {
        //List<Player> players=new ArrayList<>();

        int contar_temp=1;
        try
        {

            while (true) {

                setPlayersDataAdapter();
                sleep(4000);

            }

        }
        catch(Exception e) {}

    }
}

disculpen por el desastre pero estoy haciendo pruebas con una cadena y una variable incrementable, mi problema es que al dar un poco de scroll en la vista del recycler me elimina algunos elementos y despues de recibir otra cadena de datos me los añade pero aun asi faltan algunos elementos, en verdad no se si sea la mejor forma con recyclerview, tomando en cuenta que la aplicacion es para monitorear por eso actualizo cada 3 segundos el adaptador
`


text:
Q: Unable to retrieve data con pydelicious cuando inicializo un diccionario Quiero utilizar funciones para crear una base de datos entre usuarios y items. Utilizo las funciones que pueden ver aquí que permiten hacerlo sobre el API del.icio.us.
Sin embargo cuando inicializo el diccionario de usuarios hay problemas :
Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from deliciousrec import *
>>> delusers = initializeUserDict('programming')
<urlopen error [Errno -2] Name or service not known>, 4 tries left.
<urlopen error [Errno -2] Name or service not known>, 3 tries left.
<urlopen error [Errno -2] Name or service not known>, 2 tries left.
<urlopen error [Errno -2] Name or service not known>, 1 tries left.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "deliciousrec.py", line 10, in initializeUserDict
    for p1 in get_popular(tag=tag)[0:count]:
  File "/home/mike/.local/lib/python2.7/site-packages/pydelicious/__init__.py", line 1044, in get_popular
    return getrss(tag=tag, popular=1)
  File "/home/mike/.local/lib/python2.7/site-packages/pydelicious/__init__.py", line 1028, in getrss
    return dlcs_rss_request(tag=tag, popular=popular, user=user, url=url)
  File "/home/mike/.local/lib/python2.7/site-packages/pydelicious/__init__.py", line 457, in dlcs_rss_request
    rss = http_request(url).read()
  File "/home/mike/.local/lib/python2.7/site-packages/pydelicious/__init__.py", line 241, in http_request
    "Unable to retrieve data at '%s', %s" % (url, e)
pydelicious.PyDeliciousException: Unable to retrieve data at 'http://feeds.delicious.com/rss/popular/programming', <urlopen error [Errno -2] Name or service not known>

A mi parecer puede ser a causa de get_popular o get_urlposts. Pero ya habia errores cuando intenté descargar el API :
(test4) mike@mike-Inspiron-3543:~/Documents/programming/collective$ easy_install DeliciousAPI
Searching for DeliciousAPI
Best match: DeliciousAPI 1.6.7
Processing DeliciousAPI-1.6.7-py3.6.egg
DeliciousAPI 1.6.7 is already the active version in easy-install.pth

Using /home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/DeliciousAPI-1.6.7-py3.6.egg
Processing dependencies for DeliciousAPI
Searching for BeautifulSoup>=3.0.7
Reading https://pypi.org/simple/BeautifulSoup/
Downloading https://files.pythonhosted.org/packages/1e/ee/295988deca1a5a7accd783d0dfe14524867e31abb05b6c0eeceee49c759d/BeautifulSoup-3.2.1.tar.gz#sha256=6a8cb4401111e011b579c8c52a51cdab970041cc543814bbd9577a4529fe1cdb
Best match: BeautifulSoup 3.2.1
Processing BeautifulSoup-3.2.1.tar.gz
Writing /tmp/easy_install-owwa0x3c/BeautifulSoup-3.2.1/setup.cfg
Running BeautifulSoup-3.2.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-owwa0x3c/BeautifulSoup-3.2.1/egg-dist-tmp-2c8ro1a_
Traceback (most recent call last):
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 154, in save_modules
    yield saved
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 250, in run_setup
    _execfile(setup_script, ns)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 44, in _execfile
    code = compile(script, filename, 'exec')
  File "/tmp/easy_install-owwa0x3c/BeautifulSoup-3.2.1/setup.py", line 22
    print "Unit tests have failed!"
                                  ^
SyntaxError: Missing parentheses in call to 'print'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mike/Documents/programming/collective/test4/bin/easy_install", line 11, in <module>
    sys.exit(main())
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 2315, in main
    **kw
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/__init__.py", line 140, in setup
    return distutils.core.setup(**attrs)
  File "/home/mike/anaconda3/lib/python3.6/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/home/mike/anaconda3/lib/python3.6/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/home/mike/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 415, in run
    self.easy_install(spec, not self.no_deps)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 676, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 707, in install_item
    self.process_distribution(spec, dists[0], deps, "Using")
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 749, in process_distribution
    [requirement], self.local_index, self.easy_install
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/pkg_resources/__init__.py", line 777, in resolve
    replace_conflicting=replace_conflicting
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1060, in best_match
    return self.obtain(req, installer)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1072, in obtain
    return installer(requirement)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 676, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 702, in install_item
    dists = self.install_eggs(spec, download, tmpdir)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 887, in install_eggs
    return self.build_and_install(setup_script, setup_base)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 1155, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 1141, in run_setup
    run_setup(setup_script, args)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 253, in run_setup
    raise
  File "/home/mike/anaconda3/lib/python3.6/contextlib.py", line 100, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/home/mike/anaconda3/lib/python3.6/contextlib.py", line 100, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 166, in save_modules
    saved_exc.resume()
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 141, in resume
    six.reraise(type, exc, self._tb)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/_vendor/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 154, in save_modules
    yield saved
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 250, in run_setup
    _execfile(setup_script, ns)
  File "/home/mike/Documents/programming/collective/test4/lib/python3.6/site-packages/setuptools/sandbox.py", line 44, in _execfile
    code = compile(script, filename, 'exec')
  File "/tmp/easy_install-owwa0x3c/BeautifulSoup-3.2.1/setup.py", line 22
    print "Unit tests have failed!"
                                  ^
SyntaxError: Missing parentheses in call to 'print'


text:
Q: Point of Tangency between Two Circles I made sure to look around this site a couple times before asking my question. A lot of people have already asked how to find the point of tangency or intersection between two circles, but none of them could really help me solve the problem.
I'm being asked to find the point of tangency between two circles and all I am given are just the two circles -- no equations of tangent lines, etc. Here's a picture of what I'm working with:

The equation of the green circle is $x^2$ + $y^2$ = 5.
The equation of the orange circle was given as $x^2$ - 12x + $y^2$ + 6y = -25, which I rewrote as ($x-6)^2$ + $(y+3)^2$ = 20.
How do I find the coordinates of the circles' point of tangency?
Thank you in advance!

A: The equations are:
\begin{gather}
    x^2 + y^2 = 5 \tag{1} \\
    x^2 -12x + y^2 + 6y + 25 = 0 \tag{2}
\end{gather}
If you substitute  (1) into (2), you get
\begin{align}
    -12 x + 6y + 30 &= 0 \implies y=2x-5\tag{3}
\end{align}
Substitute this back into (1):
\begin{align}
    x^2 + (2x-5)^2 &= 5 \\\implies
    x^2 + 4x^2 - 20x + 25 &= 5 \\\implies
    5x^2 - 20x + 20 &= 0 \\\implies
    x^2 -4 x + 4 &= 0 \\\implies
    (x-2)^2 &= 0
\end{align}
Therefore $x=2$.  By (3), $y=-1$.

A: Their centers are $(0,0)$ and $(6, -3)$, and their radii are $\sqrt5$ and $\sqrt {20}$ respectively. Now draw a line segment connecting their centers, and we see that the point of tangency is where this line segment intersects both circles. We see that this line segment has a slope of $-\frac{1}{2}$, so its equation is $y=-\frac{1}{2}x$. Now find where this intersect either circle, and you're good to go.

A: If two circles are tangent, the point of tangency $P=(p_x,p_y)$ is on the line that goes through their centers $A=(a_x,a_y)$ and $B=(b_x,b_y)$, so it is a linear combination of both:
$$(p_x,p_y) = \frac{dist(A,P)}{dist(A,B)}\ \ (a_x,a_y) + \frac{dist(B,P)}{dist(A,B)}\ \ (b_x,b_y)$$


text:
Q: JQuery animate() - stopping all animations I have a question regarding the stopping of more than one animation, I have some pseudo code code below to show my situation:
CSS
#aDiv
{
    position: absolute;
    background-image: url("gfx/nyancat.png");
    width: 46px;
    height: 50px;
    background-size: 55%;
    background-position: center center;
    background-repeat: no-repeat;
}

JQUERY
    function doAnimate(aDiv)
    {
    $(aDiv).animate({   //do stuff for first animation
                            height: (H*2)+"px",
                            width:  (W*2)+"px",
                            left: "-="+(W*0.5)+"px",
                            top: "-="+(W*0.5)+"px",
                            opacity: 1

                }, 500 , "linear", function()
{ $(aDiv).animate( //do stuff for second animation
                {
                        height: H+"px",
                        width:  W+"px",
                        left: "+="+(W*0.5)+"px",
                        top: "+="+(H*0.5)+"px",
                        opacity: 0.01

                }, 500, function()
                        {   //call itself
                            doAnimate( aDiv );
                        }
                    );
                }
        );
}

//somewhere else in the code
doAnimate(aDiv);

When I call the stop() function on the aDiv ( $(aDiv).stop() ), does this stop both animations? The reason I'm asking is because that I have an animating div that is called upon window load, but upon calling stop and then restarting the animation - the animation doesn't run as it previously did so  I have to refresh the page. Thanks
edit: fiddle added

A: Just using .stop() fulfils my requirement. I'm using JQuery 1.7 so the .finish() functionality isn't available to me. For my problem, changing the background size css value from auto to the original value (55% in my case) seemed to have fixed it.


text:
Q: Failed to start jboss.deployment.unit."war".POST_MODULE I created a Maven Project using the RESTful Web Service from Database in NetBeans by following this tutorial:
http://jaxenter.com/from-database-to-restful-web-service-to-html5-in-10-minutes-105524.html and http://jaxenter.com/from-database-to-restful-web-service-to-html5-in-five-minutes-107078.html
When I tried to run this in Glassfish 4.1 as a packaged war file, my RESTful Web Service works fine.
However, I want to use JBoss EAP 6.1 instead of Glassfish, however it ran into many problems. Here's the message from JBoss when I run standalone.sh:
18:16:33,320 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC0000
01: Failed to start service jboss.deployment.unit."mhc-maven-jboss-1.0-SNAPSHOT.
war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployme
nt.unit."mhc-maven-jboss-1.0-SNAPSHOT.war".POST_MODULE: JBAS018733: Failed to pr
ocess phase POST_MODULE of deployment "mhc-maven-jboss-1.0-SNAPSHOT.war"
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(Deplo
ymentUnitPhaseService.java:127) [jboss-as-server-7.2.0.Final-redhat-8.jar:7.2.0.
Final-redhat-8]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(Se
rviceControllerImpl.java:1811) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-
1]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceCont
rollerImpl.java:1746) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1145) [rt.jar:1.7.0_51]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:615) [rt.jar:1.7.0_51]
        at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_51]
Caused by: java.lang.NullPointerException
        at org.jboss.as.jpa.processor.PersistenceRefProcessor.getPersistenceUnit
BindingSource(PersistenceRefProcessor.java:203)
        at org.jboss.as.jpa.processor.PersistenceRefProcessor.getPersistenceUnit
Refs(PersistenceRefProcessor.java:124)
        at org.jboss.as.jpa.processor.PersistenceRefProcessor.processDescriptorE
ntries(PersistenceRefProcessor.java:75)
        at org.jboss.as.ee.component.deployers.AbstractDeploymentDescriptorBindi
ngsProcessor.deploy(AbstractDeploymentDescriptorBindingsProcessor.java:95)
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(Deplo
ymentUnitPhaseService.java:120) [jboss-as-server-7.2.0.Final-redhat-8.jar:7.2.0.
Final-redhat-8]
        ... 5 more

18:16:33,370 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 26) JBAS0
18559: Deployed "mhc-maven-jboss-1.0-SNAPSHOT.war" (runtime-name : "mhc-maven-jb
oss-1.0-SNAPSHOT.war")
18:16:33,372 INFO  [org.jboss.as.controller] (Controller Boot Thread) JBAS014774
: Service status report
JBAS014777:   Services which failed to start:      service jboss.deployment.unit
."mhc-maven-jboss-1.0-SNAPSHOT.war".POST_MODULE: org.jboss.msc.service.StartExce
ption in service jboss.deployment.unit."mhc-maven-jboss-1.0-SNAPSHOT.war".POST_M
ODULE: JBAS018733: Failed to process phase POST_MODULE of deployment "mhc-maven-
jboss-1.0-SNAPSHOT.war"

My pom.xml (some parts of it Auto-generated by NetBeans) is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.mhc</groupId>
  <artifactId>mhc-maven-jboss</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>mhc-maven-jboss</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>6.0</version>
        <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>6.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
          <groupId>org.jboss.as.plugins</groupId>
              <artifactId>jboss-as-maven-plugin</artifactId>
              <version>7.5.Final</version>
        </plugin>
    </plugins>
  </build>
    <repositories>
        <repository>
            <id>unknown-jars-temp-repo</id>
            <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
            <url>file:${project.basedir}/lib</url>
        </repository>
    </repositories>
</project>

My persistence.xml is (which is almost the same with the one I created using Glassfish server):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                                 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="mhcDS" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/mhcDS</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties/>
    </persistence-unit>
</persistence>

A: Make sure you have the following points checked:

*

*Create a JNDI Datasource Entry in the JBOSS_HOME/standalone/configuration/standalone.xml (examples are given within) or via the Admin Page

*Watch the Server Logs on Startup (/standalone/logs/server.log). You should see the following line:[org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-4) JBAS010400: Bound data source [java:jboss/datasources/mhcDS]

*Even though it is not required by the JPA Spec, add the desired Provider in the persistence.xml (Default for JBoss EAP 6 is Hibernate, so add the following Line as the first child under the persistence-unit Element: <provider>org.hibernate.ejb.HibernatePersistence</provider> (Further Information can be found here: https://docs.jboss.org/jbossas/docs/Server_Configuration_Guide/4/html/ch01s02s01.html)


text:
Q: Why merged entities are updated on insert? When inserting an entity, let say article:
Article::id
Article::text
Article::author -> User

The article has an author (ManyToOne)
User::id
User::name
User::created

if I fetch the user in the database using the entity manager:
$user = $em->find(1);

$article = new Article();
$article->text = "balh blah";
$article->user = $user;

$em->persist($article);
$em->flush();

I only have an insert into the database which is correct.
INSERT INTO Article ...

Now if I use a user that is stored in the session (or cache):
$user = $cache->find(1);
$user = $em->merge($user);

$article = new Article();
$article->text = "balh blah";
$article->user = $user;

$em->persist($article);
$em->flush();

I can see 2 queries in mysql:
INSERT INTO Article ...
UPDATE user set created="..." WHERE id = 1

and if user as more OneToMany relationship, each one of them is updated too. Knowing that the user entity did not change I don't understand why Doctrine is performing those update.
In addition, there is only the created (datetime) object that is updated, none of the other fields are updated.
I have no cascade setup so it should not trigger anything on Article persist().
Anyone?

A: What is your annotation for created_at column? And is there @PreUpdate annotation somewhere in your User class or BaseUser if it is extending one?
Also; try the same thing but without $em->merge($user). I never used it and I don't even know what it is used for but that might be the problem.


text:
Q: Definitions: 'locality' vs 'causality' I'm having trouble unambiguously interpreting many answers here due to the fact that the terms locality and causality are sometimes used interchangeably, while other times seem to mean very different things to the author.
My current understanding is that 'a-causality' is "obviously forbidden" in a physical theory, because it violates Lorentz invariance and leads to logical paradoxes. (Although there are supposedly viable models such as De Broglie–Bohm that are a-causal and yet somehow OK because the a-causality is not accessible to experimental apparatus -- this only brings further confusion to the table.)
'Non-locality' on the other hand, seems to refer to, for example, correlations between events at space-like separation. In this sense 'non-locality' does not imply 'a-causality.'
On the other hand Bell (1964) uses the term 'non-local' to refer to, as he says in his conclusion, "not Lorentz invariant." So I think he is using the word 'locality' interchangeably with 'causality.'
This is the sense in which many, such as Luboš Motl seem to use the term, for example here, while others, such as Ron Maimon, seem to use the term differently, for example here, where he says:

The nonlocality of gravity doesn't mean that Lorentz invariance is broken

This is very confusing. Can someone give an authoritative set of definitions here that we can refer to?

A: I agree that these terms —especially 'locality'— are used for different concepts and this is annoying. I will list several notions of causality and locality.
Causality (or Einsteinian locality): Results of experiments carried out at a space-like distance are not correlated. This assumes that there are not previous correlations before making the experiment. In a quantum theory, this implies that observables must commute at a space-like distance. A violation of this property in a Special Relativistic theory may give rise to time travels paradoxes.
Micro-causality (only used in field theory): A theory whose fundamental variables or the dynamical degrees of freedom commute or anticommute at space-like distance is sometimes said to be local. Note that there are theories which violate this property without violating causality.
Lagrangian density (only used in field theory): A theory whose action functional is expressed as a space-time integral of a local Lagrangian density is sometimes said to be local. Note that there are theories which violate this property without violating causality.
Non-local character of gravity: Here I will mention a few points, which are not independent of each other:

*

*Equivalence principle: Free-fall observers cannot detect the gravitational field by making local experiments. All they feel are (non-local) tidal forces. This implies that we cannot define a gravitational energy-momentum tensor.

*Gravitational entropy is not an extensive magnitude: The entropy  of a Schwarzschild black hole does not scale with the volume, but with the horizon area. This means that the degrees of freedom are not local, but live on the boundary.

*Usually, as we increase energy in a theory, we explore lower and lower distances and find out substructure and new particles/degrees-of-freedom (atoms, nuclei, nucleons, quarks). However, when we take into account gravity, when we increase the energy sufficiently, we inevitably form a black hole, which are not substructure o new, more-fundamental degrees of freedom, but a solution of the theory.

*Horizons: A free-fall observer feels nothing when they cross the horizon (if the horizon is large enough, otherwise they would get spaghettificated due to tidal forces (non-local effect)). The space-time curvature at the horizon can be arbitrarily small. However, this is a physical boundary, in the sense of being a non-return point.
Cluster decomposition principle: Results of experiments carried out at the same time (in a given reference-frame) but in different spatial regions are not correlated. This assumes that there are not previous correlations before making the experiment. This property together with Poincare invariance implies causality. Relativistic QFT and non-relativistic condensed matter QFT verify this notion of locality. This property imposes certain smooth dependence of the Hamiltonian density on the creation/annihilation operators.
Non-local wave-function's collapse (quantum notion):  People sometimes say that quantum mechanics is non-local because the collapse is a non-local process. In my opinion, the wave-function collapse is not a physical process, but something that affects our mathematical description of the physical system. A sort of algorithm to incorporate new information to the theory. So, in my opinion, this non-local collapse is not a signal of physical non-locality.
Non-local states and observables (quantum notion): In quantum mechanics there exist non-localized states and observables and I have heard people to call this non-locality. A particle whose linear momentum is very well defined may be an example of a non-localized state and the scattering operator may be an example of a non-local observable given that relate states at far past and future. Entangled states could be listed here.
Entanglement (or non-local correlations, quantum notion): In quantum mechanics there are quantum correlations which are non-local such as the spin correlations of the singlet state. One needs to measure the z component of both particles which can be very separated. A singlet state may also be called non-local. Since one cannot use these correlations to send information (a parallel classical channel is required, and this cannot be superluminal), therefore this property does not imply violations of causality.
Incompatibility of QM with local (causal) realism: QM and experiments violate Bell's inequalities. This leads to the incompatibility of QM and nature with either local (causal) realism (local hidden variables) or free will. People are currently discussing this on this site.
Only the first notion of locality (causality) must be required in a Poincare invariant theory. Semantic issue: Some people call a theory "special-relativistic" if the theory is Poincare invariant and causal, while other people by "special-relativistic" just mean Poincare invariant.
Examples:

*

*Non-relativistic quantum mechanics and non-relativistic QFT verify the cluster decomposition principle. However, there are non-local observables, entanglement, etc.

*Relativistic QFT verify causality and the cluster decomposition principle.

*Quantum Electrodynamics in Coulomb gauge is a relativistic QFT, but it does not have a Lagrangian or Hamiltonian density.

*Para-statistics theories verify the cluster decomposition principle, but they do not verify micro-causality.

*Classical General Relativity has a local Lagrangian density and it is locally Lorentz invariant, but it allows time machines in some topologies (and in these cases is not a causal theory) and horizons have non-local properties.

A: non interchangeable...
Locality and Causality in the same dish...
Norsen:
"It isn't necessarily that something in region 2 is causally
influencing something in region 1, or vice versa. It is
always possible that there is some other event, neither
in region 1 nor region 2, which was not determined by
[λ], and which itself causally influences both [beables in
region 1] and [in region 2]. The point is, though, that this
causal influence would have to be non-local"
Norsen, T. Found. Phys. 39, 273. 2009.

Zeilinger:
"What we cannot exclude, as with any experiment, is the possibility that an earlier common cause in the overlap of the backward light cones of the two events"
Zeilinger, A. New Journal of Physics 14 053030. 2012

and i add:
contextuality subsumes non-locality


text:
Q: What is the Maclaurin series of $\tan z$? I'm wondering how is the Maclaurin series of $\tan z$ where $z\in\mathbb{C}$. Some first idea is see it:
\begin{eqnarray}
\tan z = \frac{\sin z}{\cos z}
\end{eqnarray}
and the Maclaurin series respectively are:
\begin{eqnarray}
\sin z = \sum_{n=0}^{\infty} \frac{(-1)^{n}z^{2n+1}}{(2n+1)!} \hspace{0.5cm} \text{and }\hspace{0.5cm} \cos z = \sum_{n=0}^{\infty} \frac{(-1)^{n}z^{2n}}{(2n)!}
\end{eqnarray}
but the quotient seems weird. Do you know other way to find this series?


text:
Q: How to index a heap allocated matrix in C? I am making a minesweeper program in C.
I have this as a global variable:
typedef struct box_t
{
  int box_type;
  int num_mines_bordering;
  int is_flagged;
} box_t;

// my global
box_t * gameboard = NULL;

Later in the application it is allocated in the heap based on the number of rows and columns:

gameboard = (box_t *)malloc((rows * cols) * sizeof(box_t));

All is well, however, they way I index it now seems incorrect and error-prone. I can't simply do  gameboard[x][y] because I get compiler errors and what I have now seems incorrect:
#define GET_LOC(ROW, COL) gameboard[(ROW * sizeof(box_t)) + (COL * sizeof(box_t)) * sizeof(box_t)]
// if you call this it would look like: box_t * loc = &GET_LOC(somerow, somecol);

Is there a better way to index it?

A: The compiler knows the type and hence the size of each array entry, so the only special thing is the number of columns cols:
box_t *gameboard = malloc((rows * cols) * sizeof(*gameboard));
gameboard[row * cols + col] = ...;

A: You could use Variably Modified Type (VMT) (i.e. a pointer to VLA). The issue is that this type cannot be defined at file scope. The simplest solution is using void* for a global variable and VMT for a local, properly typed view.
void* gameboard_glob = NULL;
int gameboard_rows, gameboard_cols;

void allocate(int rows, int cols) {
  gameboard_rows = rows;
  gameboard_cols = cols;
  gameboard_glob = malloc(sizeof(box_t[rows][cols]);
}

void foo(void) {
  box_t (*gameboard)[gameboard_cols] = gameboard_glob;

  .. do stuff with `gameboard[r][c]`
}

Alternatively, one can do allocation and convenient initialization with:
box_t (*gameboard)[cols] = calloc(rows, sizeof *gameboard);

... initialize with gameboard[r][c]

gamebard_glob = gameboard;

The memory is freed with simple free(gamebard_glob).
Note that this type of VLA does not allocate any memory on stack. All the memory is allocated from heap with malloc/calloc. Moreover, the number of rows can be changed with realloc. This solution requires any C99 compliant compiler what includes pretty much any mainstream compiler except infamous MSVC.


text:
Q: OSError (Errno 9) when using multiprocessing.Array in Python I'm trying to use a multiprocessing.Array in two separate processes in Python 3.7.4 (macOS 10.14.6). I start off by creating a new process using the spawn context, passing as an argument to it an Array object:
import multiprocessing, time, ctypes

def fn(c):
    time.sleep(1)
    print("value:", c.value)

def main():
    ctx = multiprocessing.get_context("spawn")
    arr = multiprocessing.Array(ctypes.c_char, 32)

    p = ctx.Process(target=fn, args=(arr,))
    p.start()

    arr.value = b"hello"
    p.join()

if __name__ == "__main__":
    main()

However, when I try to read it, I get the following error:
Process SpawnProcess-1:
Traceback (most recent call last):
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
    self.run()
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/federico/Workspace/test/test.py", line 6, in fn
    print("value:", c.value)
  File "<string>", line 3, in getvalue
OSError: [Errno 9] Bad file descriptor

The expected output, however, is value: hello. Anyone know what could be going wrong here? Thanks.

A: The array should also be defined in the context that you define for the multiprocessing like so:
import multiprocessing, time
import ctypes
from multiprocessing import Process

def fn(arr):
    time.sleep(1)
    print("value:", arr.value)

def main():
    ctx = multiprocessing.get_context("spawn")
    arr = ctx.Array(ctypes.c_char, 32)
    p = ctx.Process(target=fn, args=(arr,))
    p.start()
    arr.value = b'hello'
    p.join()

if __name__ == "__main__":
    main()


text:
Q: Penetration depth of gamma rays in liquid Xenon This is not a homework problem. I am trying to understand what the graph below can tell me about the "distance" a gamma ray of energy $E$ MeV will travel in liquid Xenon

A second useful graph may be

A: The variables are explained earlier in the NIST data sheet (table of contents).
The x-axis of this graph is the energy in MeV of the gamma photon penetrating the material. The y-axis gives the attenuation rate of the photon beam in historically idiosyncratic units. The attenuation rate gives the fraction of gamma beam energy intensity (W/m$^2$) remaining after penetrating a given distance into a material. Mathematically,
$$I(t) = I_0e^{-(\mu/\rho)\rho t},$$
where $t$ is the thickness of the material, $I(t)$ is the intensity of the gamma beam after penetrating a distance $t$ into the material, and the $\mu/\rho$ data is the attenuation distance $\mu$ scaled by the material density $\rho$. This data does not give energy loss per distance (MeV/cm) in the same way that particle stopping power charts do.
The data is presented in the strange $\mu/\rho$ way because, back when these tables were first being compiled, it was found that dividing the attenuation length ($\mu$) by the density ($\rho$) resulted in most materials having a similar range of values. This made for easy plotting and the realization that for shielding, what matters is getting enough mass between the radiation source and whatever needs protecting. Less dense materials require a greater thickness to provide the same shielding as less dense materials.
The quanitiy $\mu_{en}$ is the rate of energy absorption by the material. This is less than the energy loss by the gamma photons because--especially at higher energies--energy lost by the primary gamma photons is lost from the material as secondary radiation (ionized electrons, lower energy photons, etc.).

The second graph showing stopping power does allow for the caclulation of the energy loss per distance traveled (MeV/cm after multiplying the y-axis value by the density of the material). You can estimate the stopping distance using (source):
$$\Delta x = \int_0^{E_0} \frac{dE}{S(E)}$$
where $\Delta x$ is the mean penetrating distance, $E$ is the particle's energy, $E_0$ is the particle's starting energy, and $S(E)$ is the (non-mass-scaled) stopping power at the given energy.


text:
Q: why does the second link click redirect to partial not dialog I have an edit partial view to load in a dialog, which works the first time it's called, the edit then saves the data, great.
However if you don't refresh the page, which I don't want to have to do, and click 'edit' again, you are redirected to the partial page I am trying to load.
It looks like the AJAX is being ignored and the Action method in the controller is being called instead.
I have unobtrusive added through the bundles in my layout page, which the main view uses, the partial doesn't, but I don't believe it needs to.
I have also tried using preventDefault and different approached of return false; with no success, like the below:
editBtn.click(function (e) {
            editDialogPlaceholder.load(this.href, function () {
                e.preventDefault(); //tried
                $(this).dialog('open');
                return false; //tried
            })
        return false;
    });

How can I stop this?
AJAX/JS
$(function () {
        var editBtn = $('.editLink');
        var editDialogPlaceholder = $('#editDialogUI');

        editBtn.button();
        // build the dialog form
        editDialogPlaceholder.dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            open: function (event, ui) {
                $(this).load('@Url.Action("Edit","Announcements")');
            },
            buttons: {
                "Save": function () {
                    saveAnnouncement();
                    fetchList();
                    $(this).dialog("close");
                },
                "Close": function () {
                    $(this).dialog("close");
                }
            }
        });
        // on click load the dialog form, return false to stop redirect
        editBtn.click(function () {
            editDialogPlaceholder.load(this.href, function () {
                $(this).dialog('open');
            })
            return false;
        });
    });
    //post data back to the controller to save to the db
    function saveAnnouncement() {
        $.ajax({
            url: '@Url.Action("Edit","Announcements")',
                type: 'POST',
                data: $('form').serialize()
            })
        }

        function fetchList() {
            var aList = $('#announcementList');
            aList.load('@Url.Action("Fetch")');
        }

Edit action method
[HttpGet]
        public ActionResult Edit(int id)
        {
                var announcementModel = (from a in db.DbAnnouncement
                           where a.Id == id
                           select a).SingleOrDefault();
                return PartialView("Edit", announcementModel);
        }

Html.ActionLinks being used to open the dialog - second time of clicking it redirects to the partial specified in the controller.
<div class="announcementTableCell">
                    @Html.ActionLink("Edit", "Edit", new { id = Model[i].Id }, new { @class = "editLink" })

                    @Html.ActionLink("Delete", "Delete", new { Model[i].Id }, new { @class = "dltLink" })
                </div>

A: Solution as proposed in comments was to use jQuery.fn.on for the click button as the page wasn't being refreshed at the time, so binding to a static element that wasn't being refreshed meant that the action method was being called and as such redirecting to the partial view.
Therefore the working button click code:
$('#announcementList').on("click", ".editLink", function () {
            editDialogPlaceholder.load(this.href, function () {
                $(this).dialog('open');
            })
            return false;
        });


text:
Q: How to prioritize sum before string conversion in JavaScript? Is there a way instead to do like this
"4"+4+3 which will be equal with "443" to somehow do first 4+3 like the result to be "47" (as string)? I have tried in many ways, but no one seems to work. Some ideeas? Thanks.
ps. Not switching numbers

A: Put the values you want to add in brackets and then concatenate
"4"+(4+3)

A: Use this

console.log("4"+ (4+3))

A:     const num1=4;
    const num2=3

    console.log("4"+(num1+num2));

you can use the following code


text:
Q: 11 cylinders intercepted I have been working on this problem for about(over) two months now. This is not school work.
The final objective of this problem is to find the area of these 11 cylinders which are enclosed in a sphere.
In the image below, every line represents the center of a cyllinder.
$a = 60^{\circ}$ and $b = 30^{\circ}$
$r_{cylinder} = 0.5mm$
$length_{each\,cylinder} = 1.5mm$
Notice that although the cylinders are 1.5mm in length, they are completely connected, like if grabbed the image below and enlarged, meaning that the base will always be inside of the total object.

This second picture shows the that there is also two other cylinders perpendicular to the other 9.
This problem came to me when I read about the Steinmetz Solid, and wondered what would happen if I aligned them in this specific formation, simple curiosity.

Then, all of this is enclosed in a sphere of a radius of 1.5mm

A: Is this what you meant? (Sorry I can't put an image in a comment.)

The sphere is partially transparent so you can see the cylinders inside.

A: For this problem consider sun .The ball  is centre and rays are the cylinders so the area of the 11 cylinders would be a shape like a flat tyre like cylinder whose radius is length  of the small cylinders and height is the diameter of small cylinders .This my way of thinking. Soory if I have interpreted something wrong.!!


text:
Q: OpenSSH connection trouble I'm trying to use Putty 0.60 to log in to an OpenSSH 5.3 server. Connections with openssh from another Linux server are possible, but Putty fails. Putty's event log tells me "software caused connection abort" right after the DH key exchange, the server log doesn't report anything (set to INFO). I analyzed the traffic with Wireshark and got a whole bunch of "TCP retransmission" and "TCP DUP ACK" after said key exchange.
Sometimes I was able to log in, but at some point (usually < 2 min.) the connection froze without any logged messages. Sadly, I didn't capture a trace.
The server is my own (Funtoo with genkernel and gentoo-sources 2.6.34), so I may tweak it, but I'd still like to know what causes the error. Any suggestions? Thank you!

A: Ok, that was weird.
The problems cause was a network BIOS setting: a specified static IP and NIC = shared (Broadcom Extreme II) - system in question is a Dell Blade. By these settings, I somehow ended up with multiple MAC addresses for the IP - which killed my SSH connections. I honestly hope this helps somebody else...


text:
Q: How to display only an array's 5 elements from a MongoDB collection? Introduction
I am trying to make a query that outputs only an array, and within that array outputs only 5 elements of that array. I've gotten them working individually but cannot get them to work together.
Code
Output only array in its entireity:
db.mycoll.find({
    "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),
    "myarr.platform": "9 and 3 quarters"
},{
    myarr: 1
}).pretty()

Output only 5 elements of array, but also displays other fields:
db.mycoll.find({
    "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),
    "myarr.platform": "9 and 3 quarters"
},{
    myarr:{ $slice: 5 }
}).pretty()

Any help would be appreciated!

A: I found a solution by explicitly setting _id: 1 in the projection. This uses the property of find that if any field is included in the projection, all other fields will be excluded, unless also explicitly included.
db.mycoll.find({
     "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),
     "myarr.platform": "9 and 3 quarters"
},{
    "myarr" : { $slice: 5 },
    "_id" : 1
}).pretty()

For more, read the note here: https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection