text:
Q: How to use VTK_array in VTK pipeline (Python)? I am new to vtk and am trying to do volume rendering with a DICOM file.
When I try to read the DICOM file using VTK with the following code:
import vtk
reader = vtk.vtkDICOMImageReader()
reader.SetDirectoryName(r"C:\Users\I_0001")
reader.Update()

I get the following error:
ERROR: In ..\IO\Image\vtkDICOMImageReader.cxx, line 143
vtkDICOMImageReader (000001DC61D2FED0): Couldn't open C:\Users\I_0001

ERROR: In ..\IO\Image\vtkDICOMImageReader.cxx, line 237
vtkDICOMImageReader (000001DC61D2FED0): Either a filename was not specified or the specified directory does not contain any DICOM images.

ERROR: In ..\Common\ExecutionModel\vtkExecutive.cxx, line 753
vtkCompositeDataPipeline (000001DC5C4A0A90): Algorithm vtkDICOMImageReader(000001DC61D2FED0) returned failure for request: vtkInformation (000001DC5F8E72A0)
  Debug: Off
  Modified Time: 207
  Reference Count: 1
  Registered Events: (none)
  Request: REQUEST_DATA
  FORWARD_DIRECTION: 0
  ALGORITHM_AFTER_FORWARD: 1
  FROM_OUTPUT_PORT: 0

I know the file is not corrupted as it works when I try to read it with pydicom.  I tried to read the files with pydicom into a numpy array and then use the numpy_support.numpy_to_vtk to convert into a vtk array. But then I don't know how to insert those images into my vtk pipeline that uses the reader.GetOutputPort() to initiate the pipeline. Can someone help me to insert my DICOM file images which are VTK arrays into the VTK pipeline?
This is my current code:
# reading the data and converting it to VTK array using numpy_support
fileVolume = r"C:\Users\I_0001"
dicomVolume = pydicom.read_file(fileVolume)
shape = dicomVolume.pixel_array.shape
VTK_data = numpy_support.numpy_to_vtk(num_array=dicomVolume.pixel_array.ravel(), deep=True, array_type=vtk.VTK_FLOAT)

#need to insert VTK data here instead of using the vtk DICOM Image Reader
# Create the reader for the data.
reader = vtk.vtkDICOMImageReader()
reader.SetDirectoryName(r"C:\Users\I_0001")
reader.Update()

mapper = vtk.vtkDataSetMapper()
mapper.SetInputData(reader.GetOutput())

A: Using the VTKWithNumpy example linked by @Nico Vuaille I was able to convert my numpy array into a VTK image object.


text:
Q: PHP Code is not running on my Apache server My PHP code is written as such:
<?php
    phpinfo();
?>

And is saved in /var/www/html/ as index.php
I am accessing it through 127.0.0.1/index.php
I have a completely clean install of Apache2, PHP7, and libapache2-mod-php7.0
When I access it on apache it shows nothing but a blank page as if nothing is being run. I have tested to make sure the module is loaded with a2enmod, and have confirmed it is.
Nothing on the forums has applied to me thus far, so I posted this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: getting "#N/A" error when using importhtml formula I was trying to import table from morningstar website to run some analysis of my own.
When I used =importhtml(B3,"table") where B3 represents the link to the site, I am getting the "N/A" error.
http://financials.morningstar.com/ratios/r.html?t=AAPL&region=usa&culture=en-US
The importhtml works fine with gurufocus site.
Can you help me out? I haven't been able to figure out what the issue could be.
from what i understand, morningstar doesn't use HTML or XML format for their table. If that is the case, is there a script I can use in Google Sheets that will let me extract data from morningstar?

A: You can use importdata to pull it in. try this:
=importdata("http://financials.morningstar.com/ajax/exportKR2CSV.html?&callback=?&t=AAPL&region=usa&culture=en-US&cur=&order=asc")

you can actually swap out the portion of the url that says &t=AAPL
for any other ticker symbol e.g. &t=BAC
"http://financials.morningstar.com/ajax/exportKR2CSV.html?&callback=?&t=BAC&region=usa&culture=en-US&cur=&order=asc"

A: There is no table in the HTML source of that page. It looks like this:

The empty div called "financeWrap" is then filled with data by one of many client-side scripts running on the page. Since the Google bot does not execute JavaScript on imported pages, it never sees the data. Unfortunately, this means it is impossible to import the data from that page using Sheets commands.


text:
Q: Call native destroy method from flutter I have an app, and on destroy(closing) the app I need to perform a task, I tried didChangeAppLifecycleState method but it didn't work:
 @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.inactive) {
      // app is inactive
    } else if (state == AppLifecycleState.paused) {
      // app is paused
    } else if (state == AppLifecycleState.resumed) {
      // app is resumed
    } else if (state == AppLifecycleState.detached) {
      print("app detached");
    }
  }

Is there a way to call the destroy native method from Flutter?


text:
Q: How to display saved data? I have a table, I want to refresh it without reloading the whole page. so, how can I do this?
HTML
<div ng-controller="myController as vm">
  //My Grid here...
</div>

Controller
$scope.save = function(obj){
   //here is save the data
}

Now I need to display saved data in my grid without reloading.

A: What you are asking is totally absurd from the viewpoint of Angular.js. Angular is itself used so that $scope binds the values from controller to view and you never need to refresh. So your question in itself is contradicting.
What you might have meant is to send and recieve json values and updating them in view after some dealy or at some point in time. For that you have to run your service again from Service/Factory and as soon as you get result, bind them in Controller with your model.

A: You can update it in your controller using scope variable, like below:
app.controller('yourcontroller', function($scope, $http) {
    $scope.orderDetail = "some value";
});

A: So, in that case, what can be done is:
Inside your $scope.save function call another function getSavedData() which will get all the data.
Like:
$scope.save = function(obj){
  //save code goes here...
  getSavedData(); //after save.. and bind it to your $scope varibale
}

Thanks (Answered own question)


text:
Q: NextJS - Unexpected token < in JSON at position 0 I followed a tutorial about NextJS and have now tried to modify it a bit. I wanted to include the data.json file in the page. But I always get the error message "Unexpected token < in JSON at position 0".
I know that I should convert the JSON file into a string(?). How do I have to do that?
  let res = await fetch(`${server}/data`);
  const articles = await res.json();

  return {
    props: {
      articles,
    },
  };
}

My GIT-Repo is here: https://gitlab.com/pauernet/nextjs-test/

A: Your problem is that the data.json file is not in the public folder. You have to move it there from your root folder. Only files in the public folder can be accessed by domain.tld/file. Also you have to specify the full file name:
let res = await fetch(`${server}/data.json`);


text:
Q: program crashing on assembler (arrays and loops) well, my program works in a following way: it makes and array, then makes a loop which finds the quantity of numbers which divide on operand m without a leftover.
The code assembles, but running the exe file makes the masm64 ruin
include \masm64\include64\masm64rt.inc
.data
mas dq 2,5,8
m dq 2
res dq 0
title1 db "Решение уравнения. masm64",0
txt1 db "Уравнение с массивом",10,
"Количесвто чисел, которые делятся на %d без остатка:%d",10,10,
"Автор:Тарадай Святослав",0
buf1 dq 3 dup(0),0
.code
entry_point proc
mov rax,3
mov rbx,0
mov rcx,mas
main:
add rcx,1
xor rdx,rdx
div m
cmp rdx,0
jz yes
jnz no
cmp rcx,rax
je done
yes:
add rbx,1
jmp main
no: jmp main
done:
mov res,rbx
invoke wsprintf,ADDR buf1,ADDR txt1,m,res
invoke MessageBox,0,ADDR buf1,ADDR title1,MB_ICONINFORMATION
invoke ExitProcess,0
entry_point endp
end

can you please say what's up with this one? i'll be happy to hear anything about this one


text:
Q: Understand a warning from an OpenCV window object I am using the OpenCV Python library as GUI for some experimts.
The program I wrote works perfectly. I do not post it all here because
cv2.namedWindow(PLOT_EYMOL_CONTROLLER)It is very large and takes different files.
The problem is, I read a warning on the terminal, and I would like to know what is me actually warning on. The message is
GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed

It refers to a CV window which I defined like this
cv2.namedWindow('Controller')

A: I solved the issue by removing the line
cv2.namedWindow('Controller')

It seems the warning comes when you create an object and do not use it for a long time. The library routines, automatically creates the object in case you refer to it.


text:
Q: How to display a grid of more than 1000 thumbnails as ui views in UI Scrollview with smooth scrolling I have to implement a application which displays a grid view of thubmnails each of which is a clickable object. The grid view will display 2 images( which i suppose can be a uiview). And 4 rows per page.
The use should be able to smoothly scroll through the image grid view. The images for the thumbnails will be fetched from the url i get from server. However assuming i have the urls in my model how can i implement this feature to display them.
Few problems i have encountered are:

*

*All the images(UIviews) cant be loaded due to memory constraints. Hence paging can be enabled.

*On implemented paging using uiscrollview delegate the ui becomes irresponsive for some time. I am downloading the images in a NSOperation queue and posting the image on mainthread for displaying on screen.
I want the scrolling to be very smooth without jerky feature.
How can i implement this?
TIA,
Praveen S

A: I was having a similar problem.
What i did was at an instance i kept only 3 pages(or screens with 4 rows as you said) in the memory and cleared remaining all.
If suppose there are 3 screens s1, s2, s3. And the user is viewing s2. Whenever he scrolls to s3 i will remove s1 and load a new page s4. So that at any point of time there will be 3 screens only.
And the users will have a better experience. And also less memory will be occupied.


text:
Q: NLTK not working on iPython I'm working with MacOS, I've installed Python and iPython, but when I type:
import nltk

ipython tells me that there is no module named nltk. However, when I type in:
import sys

import nltk

It works perfectly fine. Can someone explain why this isn't working correctly? I'm a newbie to Python so please be gentle. Thanks.


text:
Q: If you plug in a bridge rectifier directly to a power outlet, and touching one of the outputs, isn't it like touching live wire? If you touch the output of the Full bridge Rectifier, and the circuit is powered directly from the city power, does it shock you with every positive wave of the 120ac? How about a half bridge rectifier? Its only one diode, but what happens if you touch the other end of the output, and how does this guy not get shocked:  https://www.youtube.com/watch?v=sI5Ftm1-jik (2:00),  and how does switched mode wall adapters isolate the live wire? This is so confusing!

A: First of all, it is always good practice NOT to touch live power wires. In the case of the video you mentioned and, almost all appliances and power supplies, there will be an isolation transformer connecting the mains to the circuit you are touching.
For a single phase, there are live, neutral and earth wires, on the mains side. The neutral and earth wires will be connected together and, ideally, be at the same potential. If you touch the live wire, you will likely form a circuit to the earth and be shocked. If a 1:1 isolation transformer is in between, you'll just have live and neutral wires effectively with no direct connection to earth, and if you touch the live wire on the secondary side, it is less likely a connection to earth will be formed (it can still happen though so don't touch)
There is a good discussion of this here: https://www.soundonsound.com/sound-advice/crosstalk-readers-writes.


text:
Q: SSH fails with error "Permission denied (Password)" I am trying to SSH into a PC (lets call it B) with Ubuntu Server 18.04 from a Raspberry Pi (lets call it A) with Raspbian Stretch Lite. Both are on my local network.
PublicKeyAuth is disabled and PasswordAuth is enabled on B
(a copy of my /etc/ssh/sshd_config on B is appended to the end of the question)
When I try to ssh user@B from A it fails with the message Permission denied (Password)
after looking at the output of ssh -v user@B I thought that it might still try to use the PublicKeyAuth and found this other question discussing how to force the client to use PasswordAuth.
But the suggested command doesn't work either, so it seems to be another issue.
I also deleted the entry for B from my known_hosts file on A in case this comes with any default values attached, but ssh still failed.
When I try to ssh from my notebook with the same settings on B it asks me for a password instead and logs me in after I supply it.
It is possible to just add the key of A manually on B, but I would like to know what I misconfigured in order to avoid it the next time!
Output of ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@ip on A:
OpenSSH_7.4p1 Raspbian-10+deb9u4, OpenSSL 1.0.2l  25 May 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "192.168.x.x" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to 192.168.x.x [192.168.x.x] port 22.
debug1: Connection established.
debug1: identity file /home/user/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4p1 Raspbian-10+deb9u4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.6p1 Ubuntu-4
debug1: match: OpenSSH_7.6p1 Ubuntu-4 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 192.168.x.x:22 as 'user'
debug3: hostkeys_foreach: reading file "/home/user/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/user/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from 192.168.x.x
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:ycsiE8n8WxPvLtO29np2RbItqRhExmsSITflO7c67qQ
debug3: hostkeys_foreach: reading file "/home/user/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/user/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from 192.168.x.x
debug1: Host '192.168.x.x' is known and matches the ECDSA host key.
debug1: Found key in /home/user/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug2: key: /home/user/.ssh/id_rsa (0x1f2c0c0)
debug2: key: /home/user/.ssh/id_dsa ((nil))
debug2: key: /home/user/.ssh/id_ecdsa ((nil))
debug2: key: /home/user/.ssh/id_ed25519 ((nil))
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: password
debug3: start over, passed a different list password
debug3: preferred password
debug3: authmethod_lookup password
debug3: remaining preferred:
debug1: No more authentication methods to try.
Permission denied (password).

My /etc/ssh/sshd_conf on B:
#   $OpenBSD: sshd_config,v 1.101 2017/03/14 07:19:07 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

PubkeyAuthentication no
PasswordAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!

#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem   sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#   X11Forwarding no
#   AllowTcpForwarding no
#   PermitTTY no
#   ForceCommand cvs server

A: I had PasswordAuthentication no added to my /etc/ssh/ssh_config on A!
After commenting out the line it worked.


text:
Q: Rails: form_for with submodel for user selecting For example, I have a product model. Each product has one type named ProductType. Now I want to create product.
Here is my simple form using slim:
= form_for @product, url: product_path, :html => {:method => post} do f
  = f.label :name
  = f.text_field :name
  = f.submit 'Create'

I want in this form, there is a drop-down list that list all type of product (load from ProductType) and user can choose one. How can I do this in rails (using form_for)
thanks

A: collection_select is built for exactly this purpose.
Assuming ProductType has a name attribute, try
= form_for @product, url: product_path, :html => {:method => post} do f
  = f.label :name
  = f.text_field :name

  # collection_select creates a select box with the options set from the collection
  = f.label :type
  = f.collection_select :type, ProductType.all, :name, :id

  = f.submit 'Create'

Review the documentation:
http://apidock.com/rails/v4.2.7/ActionView/Helpers/FormOptionsHelper/collection_select


text:
Q: Рекурсия не могу понять почему возврат идет None Подскажите почему выдает None, и как остановить, если нашел переход?
n=['1','2','3','4','5','6','7','8']
def obr(m,stroka,k):
    st=stroka
    if st.count(n[0])>=2 and st.count(n[1])>=1 and st.count(n[2])>=1 and st.count(n[3])>=1 and  st.count(n[4])>=1 and st.count(n[5])>=1 and st.count(n[6])>=1 and st.count(n[7])>=1 and st[-1]=='1':
        print (st)
        return st
    for i in range(len(m)):
        if m[i][0]==stroka[-1]:
            k=0
            print(m,stroka,k)
            obr(m[:i]+m[i+1:],stroka+m[i][1], k)

        if m[i][1]==stroka[-1]:
            print(m,stroka,k)
            k=0
            obr(m[:i]+m[i+1:],stroka+m[i][0], k)

def nach(teleports_string):
    mas=sorted(teleports_string.split(','))
    k=0
    s=obr(mas,'1',0)

    print(s)

    #return any route from 1 to 1 over all points

    return "123456781"

nach("12,23,34,45,56,67,78,81") == "123456781"
nach("12,28,87,71,13,14,34,35,45,46,63,65") == "1365417821"
nach("12,15,16,23,24,28,83,85,86,87,71,74,56") == "12382478561"
nach("13,14,23,25,34,35,47,56,58,76,68") == "132586741"

A: Если функция явно ничего не возвращает, то она по факту возвращает None:
def foo():
    pass

print(foo())  # None

В цикле внутри функции obr функция вызывает саму себя, но возвращаемое значение никак не используется. По сути цикл просто прокручивается до конца, и функция возвращает None, так как не было явного return с возвращением конкретного значения. Предположу, что по задумке функция должна была выглядеть так:
def obr(m,stroka,k):
    st=stroka
    if st.count(n[0])>=2 and st.count(n[1])>=1 and st.count(n[2])>=1 and st.count(n[3])>=1 and  st.count(n[4])>=1 and st.count(n[5])>=1 and st.count(n[6])>=1 and st.count(n[7])>=1 and st[-1]=='1':
        print (st)
        return st
    for i in range(len(m)):
        if m[i][0]==stroka[-1]:
            k=0
            print(m,stroka,k)
            return obr(m[:i]+m[i+1:],stroka+m[i][1], k)

        if m[i][1]==stroka[-1]:
            print(m,stroka,k)
            k=0
            return obr(m[:i]+m[i+1:],stroka+m[i][0], k)


text:
Q: Give the transformation matrix that send $\vec i$ on $ [1,1/2,0]$ I'm asked to give the linear transformation that sends $\vec i$ on $[1,1/2,0]$ , $\vec j$ on $[-1/3,1,0]$ , $\vec k$ on $[1/4,1/4,1]$.
Is it a translation where I need to use the actual $i,j,k$ vectors or is it just changing the $i,j,k$ vectors to the new ones? It's in french and it says 'qui envoie $\vec i $ sur $[1,1/2,0]$'
What would be transformation matrix ?

A: Each of the image vectors is one column of the corresponding matrix representation of the linear map.
To see this, consider the following, for coefficients $\alpha, \beta, \ldots$:
$$A(\vec i) = \begin{bmatrix} \alpha & \delta & \eta \\ \beta & \epsilon & \theta \\ \gamma & \zeta & \iota \end{bmatrix} \begin{bmatrix}1 \\ 0 \\ 0\end{bmatrix} = \begin{bmatrix} \alpha \\ \beta \\ \gamma \end{bmatrix}$$
But you know the result should be
$$A(\vec i) = \begin{bmatrix} 1 \\ 1/2 \\ 0\end{bmatrix}$$

A: (It sounds like) you want a linear transformation $T: \mathbb{R}^3 \to \mathbb{R}^3$ such that $$T\pmatrix{1 \\ 0 \\ 0} = \pmatrix{1 \\ \frac{1}{2} \\ 0}.$$
(and so on). That means you want a $3\times 3$ matrix $T= (t_{ij})$ such that for example
$$
\pmatrix{t_{11} & t_{12} & t_{13} \\ t_{21} & t_{22} & t_{23} \\ t_{31} & t_{32} & t_{33}}\pmatrix{1 \\ 0 \\ 0} = \pmatrix{1 \\ \frac{1}{2} \\ 0}.
$$
From this you should be able to see what the entries $t_{ij}$ are.


text:
Q: Selenium Automation Organize Project I would like to automate few applications. This application consist of web, mobile (Android + IOS) and API. How to organize this project for this situation.
Im automation in selenium using Java. In C#, once can create a project consists of multiple sub projects. How to do it in Java?
Please advise.
A billion thanks for your help.

A: It depends on which build automation tool you choose to work with.
When you work with C# you probably use MSBuild
In Java Stack the most popular build automation tools are maven and gradle and both support multi-module projects, It is up to you to choose which one suits your project requirements.
See
Gradle vs. Maven
Multi-Module Project with Maven
Introduction to Gradle
Maven Scopes and Gradle Configurations Explained

A: I am not 100% sure what your goal is, but when it's about setting up Selenium (JAVA) projects and run them automatically, I can recommend you to use Maven & Jenkins to achieve this goal. Find further information in the following link:
https://www.guru99.com/maven-jenkins-with-selenium-complete-tutorial.html
I hope I could help.


text:
Q: decode mp3 from streaming URL I am trying to decode mp3 from icecast server but i am getting hip: bitstream problem, resyncing skipping 164 bytes... error. I am decoding using lame decoder.
hip_t hipVal;
hipVal = hip_decode_init();
while(1)
{
Readdatafromnet(ringBuf, (void**)&buffer);
sampleno = hip_decode(hipVal,buffer,irhandle->size, pcmrBuffer, pcmlBuffer);
player_write(handle, pcmrBuffer, sampleno);
}
hip_decode_exit(hipVal);


text:
Q: Queue multiple async calls with callbacks I need to fetch some images from the gallery, process them (resize, compress...) and save them to a certain path. However, i need to queue the calls because older devices won't be able to process multiple images at the same time.
I am using Glide, this is the code used for processing one image:
fun processImage(context: Context, sourcePath: String, destinationPath: String, quality: Int, width: Int, height: Int, deleteOriginal: Boolean, callback: ((success: Boolean) -> Unit)) {
    val sourceFile = File(sourcePath)
    val destinationFile = File(destinationPath)

    GlideApp.with(context)
            .asBitmap()
            .load(sourceFile)
            .into(object : SimpleTarget<Bitmap>(width, height) {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    try {
                        destinationFile.writeBytes(ImageUtilities.imageToByteArray(resource, quality, Bitmap.CompressFormat.JPEG, false))
                        if (deleteOriginal) {
                            val originalFile = File(sourcePath)
                            originalFile.delete()
                        }
                        callback.invoke(true)
                    } catch (ex: Exception) {
                        callback.invoke(false)
                    }
                }
            })
}

Now i am queuing the calls manually by calling processNextImage which calls itself recursively until all the images are processed:
private fun processImages(sourceImagePaths: List<String>) {
        processNextImage(sourceImagePaths, 0)
}

private fun processNextImage(sourceImagePaths: List<String>, index: Int) {
    val imagePath = sourceImagePaths[index]
    val destination = FileUtilities.generateImagePath()
    processImage(this, imagePath, destination, 90, 1000, 1000, false) {
        processedImagePaths.add(destination)
        if (index + 1 < sourceImagePaths.count())
            processImage(sourceImagePaths, index + 1)
        else
            success()
    }
}

However I don't think this is the best way to do it and I tried to look into Kotlin coroutines but all I found were examples when the queued code is already blocking, which doesn't fit my case because Glide already handles the resizing asynchronously and returns the result in a callback onResourceReady
Any ideas for a clean way to do this?

A: As described in the official documentation, there is a simple pattern to follow if you want to turn a callback-based API into one based on suspendable functions. I'll paraphrase that description here.
Your key tool is the function from the standard library called suspendCoroutine(). Assume that you have someLongComputation function with a callback that receives a Result object:
fun someLongComputation(params: Params, callback: (Result) -> Unit)

You can convert it into a suspending function with the following straightforward code:
suspend fun someLongComputation(params: Params): Result =
    suspendCoroutine { cont ->
        someLongComputation(params) { cont.resume(it) }
}

Note how the type of the object passed to the original callback became simply the return value of the suspendable function.
With this you can see the magic of coroutines happen right in front of you: even though it looks exactly like a blocking call, it isn't. The coroutine will get suspended behind the scenes and resume when the return value is ready — and how it will resume is totally under your control.

A: I was able to solve the issue using suspendCoroutine as suggested in Marko's comment, here is my code:
private fun processImages(sourceImagePaths: List<String>) {
    async(UI) {
        sourceImagePaths.forEach { path ->
            processNextImage(path)?.let {
                processedImagePaths.add(it)
            }
        }

        if (processedImagePaths.isEmpty()) finishWithFailure() else finishWithSuccess()
    }
}

private suspend fun processNextImage(sourceImagePath: String): String? = suspendCoroutine { cont ->
    val destination = FileUtilities.generateImagePath()
    processImage(this, sourceImagePath, destination, 90, 1000, 1000, false) { success ->
        if (success)
            cont.resume(destination)
        else
            cont.resume(null)

    }
}

The method processImages iterates over the list of paths, and calls processNextImage for each path. Since processNextImage contains a suspendCoroutine, it will block the thread until cont.resume is called, which guarantees that the next image will not be processed before the current one is done.


text:
Q: Best way to store text in elasticsearch that does not need to be search, analyzed or aggregatable? What is better solution for storing just a text in elasticsearch 5.x for a text field no longer then 256 characters, when this field does NOT need to be:

*

*searchable

*indexed

*analyzed

*sortable...

Option 1)
Set mapping to text with index=false
Option 2)
Set mapping to keyword with index=false, doc_values=false
What is more space efficient? Or what is the difference between these two mappings whit these settings?
Thank you.

A: I would definitely use the keyword type so your text is not analyzed (as if it was a text field).
In addition to the settings you mentioned, I'd set a few more parameters, such as the ignore_above and include_in_all.
So:
    "field_name": {
      "type":  "keyword",
      "index": false,
      "doc_values": false,
      "ignore_above": 256,
      "include_in_all": false
    }


text:
Q: PHP preg_match array and echo the matches out I have post with youtube link inside.
So i want to find all matches, replace it with custom link and echo it out.
**This is sample post:
  Life is good
 {youtube}NgBZrRCPCH8{/youtube}

 Fun is great!
 {youtube}joRCPCH8{/youtube}

 Earth is round and roll
 {youtube}pwnkfH8{/youtube}**

Youtube link is something like json:
   {youtube}NgBZrRCPCH8{/youtube}
Something like youtube.com/NgBZrRCPCH8
Here is what i have been trying.
    $con="Life is good
     {youtube}NgBZrRCPCH8{/youtube}

     Fun is great!
     {youtube}joRCPCH8{/youtube}

     Earth is round and roll
     {youtube}pwnkfH8{/youtube}";

$pattern="/{youtube}/";

$replace="";

$first= preg_replace($pattern,$replace,$con);

$pat="{/youtube}";

$rep="";

$sec=preg_replace($pat,$rep,$first);

$patt="/{}/";

$repl="";

$last=preg_replace($patt,$repl,$sec);

if($last){echo '

';}

THANKS...

A: i am not sure what you are trying to do,but as per my understanding i did this
$re = '/{youtube}(.*){\/youtube}/m';
$str="Life is good
     {youtube}NgBZrRCPCH8{/youtube}

     Fun is great!
     {youtube}joRCPCH8{/youtube}

     Earth is round and roll
     {youtube}pwnkfH8{/youtube}";

preg_match_all($re, $str, $matches);

$re = '/([\w ]+)[^a-zA-Z {}]+(?!{)/m';

preg_match_all($re, $str, $matches1);

echo '
';
foreach ($matches[1] as $key => $value) {
    echo '

    '.$matches1[0][$key].'

';
}
echo '
';

output

A: An other way:
$trans = array ('{youtube}'  => ' '" frameborder="0" allowfullscreen>

');

$result = '

'
        . substr(strtr($str, $trans), 0, -20) . '
';


text:
Q: $\mathbb{Q}(\omega2^{1/3}) \neq \mathbb{Q}(\omega^{2}2^{1/3})$ I am reading An Introduction to The Theory of Numbers by Niven et al.. In the section on Algebraic Number Fields (section 9.3 in the 5th edition) towards the end the authors mention that $\mathbb{Q}(\omega2^{1/3}) \neq \mathbb{Q}(\omega^{2}2^{1/3})$. I am able to reduce the problem to showing that if $\omega^{2}2^{1/3}\notin\mathbb{Q}(\omega 2^{1/3})$ or $\omega 2^{1/3}\notin\mathbb{Q}(\omega^{2}2^{1/3})$ holds then the claim is true. Now I am stuck and don't know how to proceed. Thanks in advance.
Note: If possible, use the theorems given in the book as I am not too comfortable with the methods from an algebra course (will take one soon :) ).

A: Suppose $\omega^22^{1/3}\in\mathbb{Q}\left(\omega2^{1/3}\right)$. Then $\omega\in\mathbb{Q}\left(\omega2^{1/3}\right)$. Thus we have a tower of fields:
$$\mathbb{Q}\subseteq\mathbb{Q}\left(\omega\right)\subseteq\mathbb{Q}\left(\omega2^{1/3}\right)$$
The minimal polynomial of $\omega$ over $\mathbb{Q}$ has degree 2, so we see that the first field extension above has degree 2. So by multiplicativity, we'd have to have that the total extension had degree divisible by 2. But the minimal polynomial of $\omega2^{1/3}$ over $\mathbb{Q}$ is the same as that of $2^{1/3}$, which has degree 3. Thus we cannot have $\omega^22^{1/3}\in\mathbb{Q}\left(\omega2^{1/3}\right)$.
(Make sure you can prove all the steps I take for granted—e.g., the minimal polynomials of the relevant elements, field extension degree multiplicativity).

A: I am posting a solution based on the theorems given in the book for future reference.
First note that $\omega 2^{1/3}$ is an algebraic number of degree 3. By theorem 9.14, if $\omega^{2}2^{1/3}\in \mathbb{Q}(\omega 2^{1/3})$ then,
$$\omega^{2}2^{1/3} = a_{0}+a_{1}\omega 2^{1/3} + a_{2}(\omega 2^{1/3})^{2}$$
where $a_{0}, a_{1}, a_{2}\in \mathbb{Q}$.
Multiplying both sides by $\omega$ and comparing the real and imaginary parts, we get
$$a_{0} = a_{1}2^{1/3}$$ and
$$2^{1/3} = \frac{a_{0}+a_{1}2^{1/3}}{2}+a_{2}4^{1/3}$$
$$\implies 2^{1/3} = a_{1}2^{1/3}+a_{2}4^{1/3}$$
$$\implies 2^{1/3} = \frac{1 - a_{1}}{a_{2}} \in \mathbb{Q}$$
A contradiction.

A: Observe that $a=2^{1/3},b=2^{1/3}\omega,c=2^{1/3}\omega^2$ are the distinct roots of $f(x) =x^3-2\in\mathbb {Q} [x] $.
If $\mathbb {Q} (b) =\mathbb{Q} (c)=K $ then both the roots $b, c$ are in $K$ and hence $a=-(b+c) \in K$. Hence $K$ contains all the roots $a, b, c$.
Next note that $f(x) $ is irreducible of degree $3$ thus each of $\mathbb {Q} (a), \mathbb {Q} (b) =K, \mathbb{Q} (c) =K$ is of degree $3$ over $\mathbb {Q} $. Since $\mathbb{Q} \subseteq \mathbb{Q} (a) \subseteq K$ it follows that $\mathbb{Q} (a) =K$.
But this is a contradiction as $\mathbb{Q} (a) \subseteq \mathbb {R} $ and $K$ contains complex numbers $b, c$.


text:
Q: getFilesDir() android function is undefined if i dont extend my class with activity If i have my class as
import java.io.File;

import java.io.FileOutputStream;

//Extends Activity

public class MyClass extends Activity
{

File fileDir = getFilesDir(); //no error

   . ....
}

But if i don't extend MyClass , i get an error saying "getFilesDir()" undefined.
some thing like
   public class MyClass2
    {

    ....

    File fileDir = getFilesDir(); //error

    }

A: That is the method of the Context class. You have to obtain an instance of the class to invoke it.

A: http://developer.android.com/reference/android/content/ContextWrapper.html#getFilesDir()
getFilesDir is member of ContextWrapper. So if you don't extend ContextWrapper it's normal for the compiler to throw error undefined reference.


text:
Q: CCRotateTo and CCRotateBy differnce //CCRotateBy
id action=[CCRotateBy actionWithDuration:1.0 angle:45];
[player runAction:action];

//CCRotateTo
id action=[CCRotateTo actionWithDuration:1.0 angle:45];
[player runAction:action];

the above two code produce same results...I need to know the difference between using rotateTo and rotateBy...
please advise...

A: CCRotateBy is also very handy when it comes to ever rotating sprites:
CCSprite *halo = [CCSprite spriteWithFile:@"halo.png"];
[halo setOpacity:160];
CCRotateTo * rotRight = [CCRotateBy actionWithDuration:0.5 angle:40.0];
[halo runAction:[CCRepeatForever actionWithAction:rotRight]];

with the CCRotateBy action you never need to think about any angles...

A: CCRotateTo rotates the object to the specified angle, while CCRotateBy rotates the object to its current angle + the specified angle. They would be equivalent if your object's initial rotation is 0. However, if its initial angle was 90, CCRotateTo would rotate it towards angle 45, while CCRotateBy would rotate it towards angle 135.


text:
Q: Динамические точки в строчке Есть вот такой макет:

Вопрос: как сделать точки между заголовком и значением ?
Значения справа могут иметь разную длину символов.

A:

p {
  display: flex;
  justify-content: space-between;
}

span:nth-child(2) {
  display: inline-block;
  width: 100%;
  border-bottom: 2px dotted;
}

  exp

  1000

  lorem20

  ip10

  do

  50

  dollor

  1000

  dollorin

  400


text:
Q: Is this matrix in row echelon form? Is this matrix in row echelon form?
3x3 matrix is:
$$
\left(
\begin{matrix}
    1 & 3 & 4 \\
    0 & 0 & 1 \\
    0 & 0 & 0 \\
\end{matrix}
\right)
$$
Last element of 2nd row is 1, in a cell above it is a 4. I think Row echelon form allows 4 and 1 in this form. But is that 0 in 2nd row(which has 3 above it) is allowed in row echelon form? So the question is,'Is 3 allowed above 0 in row echelon form?'

A: The matrix as given is indeed in row echelon form, but not reduced row echelon form.  For the latter, replace the $4$ by a $0$.

A: To be in Row Echelon Form requires two things of a matrix:

*

*All non-zero rows are above any all-zero row.

*The leftmost non-zero element (the pivot) in any row is to occur strictly to the right of any pivot in the rows above it.

So the given matrix checks out okay.   It is Row Echelon.
You can, however, reduce it further by a row operation as you suggest.


text:
Q: A holomorphic function in the unit disc without radial limit I try to do some problems from Rudin's RCA Chapter 13 (Approximation by Rational Functions). It's Exercise 5: For $n=1,2,3,\ldots$, let $\Delta_n$ be a closed disc in $U$, and let $L_n$ be an arc (a homeomorphic image of $[0,1]$) in $U \setminus \Delta_n$ which intersects every radius of $U$. There are polynomials $P_n$ which are very small on $\Delta_n$ and more or less arbitrary on $L_n$. Show that $\{\Delta_n\}$, $\{L_n\}$, and $\{P_n\}$ can be so chosen that the series $f=\Sigma P_n$ defined a function $f \in H(U)$ which has no radial limit at any point of $T$.
I can apply Runge's Theorem to construct polynomials $P_n$ which are very small on $\Delta_n$. However, I don't understand what the phrase "more or less arbitrary on $L_n$" means. It is very unclear to me, so I can't solve this problem. Does anyone know what this phrase means and how to prove this exercise?

A: "more or less arbitrary" means that they can approximate any analytic function in the neighborhood of $L_n$ as well as one wants while also approximating well a given analytic function in a disc away from said neighborhood - polynomials are finite maps of the plane in the sense that the preimage of any point is finite, so obviously the
"more or less" is needed
To finish the problem, one can take $\Delta_n$ the disc of radius $1-\frac{1}{4n}$, $L_n$ an arc that goes say three quarters around on the circle of radius $1-\frac{1}{4n+1}$ them moves there to the radius $1-\frac{1}{4n+2}$ and keeps going another half around the circle, so overall it goes around and a quarter say but still is an arc with different ends and take then $V_n$ a small tubular neighborhood of $L_n$ disjoint of $\Delta_n$ (eg you can take the width $\frac{1}{(4n+2)^3})$.
Construct inductively $P_n, n \ge 1$ as follows.
Take $P_0=0$ and then $f_1(z)=P_0(z), z \in \Delta_1, f_1(z)=1, z \in V_1$, is analytic on the union of those two open sets as they are disjoint,  and since the complement of $\Delta_1 \cup V_1$ is obviously connected, we can construct a polynomial $P_1$ s.t. $|P_1(z)-f_1(z)| \le \frac{1}{2}, z \in \Delta_1 \cup V_1$.
Assume now $P_n$ constructed and then $f_{n+1}(z)=P_n(z), z \in \Delta_{n+1}, f_{n+1}(z)=1, z \in V_{n+1}, n$ even, $f_{n+1}(z)=0, z \in V_{n+1}, n$ odd is analytic on the union of those two open sets as they are disjoint,  and since the complement of $\Delta_{n+1} \cup V_{n+1}$ is obviously connected, we can construct a polynomial $P_{n+1}$ s.t. $|P_{n+1}(z)-f_{n+1}(z)| \le \frac{1}{2^{n+1}}, z \in \Delta_{n+1} \cup V_{n+1}$ (technically Runge applies on compact subsets of this, but we can just enlarge it a little, while clearly we respect the construction for $P_0, P_1$ etc)
Pick $K$ a compact disc in $U$ (open unit disc), then $K \subset \Delta_n, n \ge n_K$, hence $|P_{n+1}(z)-P_n(z)| \le \frac{1}{2^{n+1}}, z \in K, n \ge n_K$, hence there is a function $f$ on $K$ s.t $P_n \to f$ uniformly on $K$ and $f$ is analytic in the interior of $K$, hence by taking these compact discs to fill $U$, we get $f$ analytic on $U$, s.t $P_n \to f$ uniformly on compact sets.
But now let $z \in V_{2n}$. Since $V_{2n} \subset \Delta_m, m \ge 2n+1$, we get $|f(z)| \le (\sum_{k=2n}^{\infty}{|P_{k+1}(z)-P_k(z)|})+|P_{2n}(z)| \le (\sum_{k=2n}^{\infty}\frac{1}{2^{k+1}})+ \frac{1}{2^{2n}} = \frac{1}{2^{2n-1}}$, while if $z \in V_{2n+1}$, we get $|f(z)-1| \le \frac{1}{2^{2n}}$ since $|P_{2n}| \le \frac{1}{2^{2n}}$ on $V_{2n}$, but $|P_{2n+1}-1| \le \frac{1}{2^{2n+1}}$ on $V_{2n+1}$, Since by construction any radius intersects all sets $V_n$, $f$ cannot have a radial limit anywhere!
Note that any such function must be highly unbounded in the sense that for almost all the points on the boundary the image of any triangular neighborhood of it (as small as you want) is dense in the plane.


text:
Q: Eclipse - black background in javadoc popup I am using Elementary OS, based on Ubuntu 12.04 and Eclipse Luna.
The background color of javadoc popups is black and font color is dark grey, so it is unreadable.
I tried to change background in eclipse preferences, but it did not change.
Then I used google, and found solution, that I need to change tooltip bg color. So I did it. But still no change.
Anyone knows how to change that color ?

A: I had the same problem with Ubuntu 16.04 and Eclipse Mars. I solved the problem by adding the following lines in eclipse.ini :

--launcher.GTK_version
  2

A: As a KDE user, you have to change the tooltip background color with System Settings. Navigate to
Application Apperearence -> Colors (Left side menu) -> Colors (Colors tab on right side)
and adjust the Tooltip Background and Tooltip Text colors. In your case, adjusting the tooltip background should be enough.
The setting is under GNOME UBUNTU in Settings.

A: I would get a blank assist popup window and if I clicked on the window it would turn black and not show any text.
I tried many things to get the text to show up like changing the eclipse foreground and back ground colors or the above system settings.
I then started to look at the VcXsrv X server program I was running to display on my windows box.
I turned off the 'Native opengl' in the 'Extra Settings' screen of the XLaunch program.
This fixed my problem.


text:
Q: How to pass the varible value from one layer to other layer in flash actionscript?
Hello below is the image of my project , you can see dice layer with 25th frame and at 25th frame its having a variable value and I need to pass it to JS layers 1st frame which is another layer down the roll layer please do the needful.

A: You can do :
dice / frame 25 :
// here the String type is just for example of course, set the type of your var
// the shared_var var is global, so you can use it in any frame of any layer
var shared_var:String = 'data'

JS / frame 1 :
// we have to verify if shared_var is defined and not null
// because in the first iteration of your animation, shared_var does not exist yet because it's defined in the frame 25
if(shared_var){

    // here trace is just for example, you do what you want with your var
    trace(shared_var)  // gives : data

}


text:
Q: How to get probabilities (instead of a single - actual - class) from NaiveBayesModel in MLlib? I have built a NaiveBayesModel in MLlib. It works fine but I would like to get back the probabilities of each class for given input instead of the model's final - and single - decision, that is, whether the input belongs to class 1.0 or class 0.0. Any ideas?

A: I do not think they support this yet, but I know is in their roadmap to add probabilities to several classifiers prediction outputs.


text:
Q: Should every possible branch in a method have a separate junit? This is more of a design question.
Suppose you have a method like this (as an example):
if (x == 5) {
  c = 1;
} else {
 if (z != 2) {
  b = 6;
} else {
   a = 3;
}

Do you think it's best practice to have a junit for each possible branch? Ie, testx5, test xnot5znot2, testxnot5z2, etc, or something like:
void testMethod() {
// x is 5
test/assert code;

// x not 5, z not 2
test/assert code;

// x not 5, z is 2
test/assert code

// etc
}

EDIT: Just to be clear, my goal is complete code coverage. I just want to know opinions on whether I should make a new test for each branch or combine them in one test. Thank you for your input.

A: What you're discussing is called Branch Coverage.
The conventional wisdom is if it's important enough to write code to cover that use case, it's important enough to write a test case to cover that code. So this would seem to say that 100% branch coverage is an excellent goal (and will also imply 100% statement coverage, but not necessarily 100% loop or 100% condition coverage).
However, you also need to balance the effort of writing tests with the value of getting those tests. For example, if the code you're testing has a try/catch to catch a checked exception, but the exception is almost never thrown (or difficult to cause to be thrown in a test case), then writing a test to cover that exception is probably not worth your time.
This is why you see in a lot of places that aiming for a certain % of test coverage is a bad idea, because you end up writing test cases to get coverage, not to find bugs. In your example, yes, each branch deserves it's own test case. In every piece of production code, it's probably not necessary.

A: The JUnit FAQ seems to indicate that it is better to have more tests with fewer assertions, if only because JUnit will only report the first assertion failure in a test method.  With one method, if you broke the x = 5 case, you'd have no way to tell if any of the x != 5 cases were still working.

A: In unit testing, your goal is to test behaviors -- not the "code". Think of the method you're testing a black box and you want to see if it works correctly. You don't know how it does it's job internally, but you expect certain results for certain inputs. So you'd want to create tests for different cases of how you'd expect the code to work as if you didn't know anything about how the internals of the method actually does it's job. So you'd write tests like "applysDiscountToShoppingCart" and "addsDeliveryFeeToShoppingCart".
Now, all that being said, it's also useful to create "edge cases" in which you're testing things that are likely to break (like nulls, zeros, negatives, data too big/small, etc) to see if it fails in an expected manner too. Usually to write those, you need to know how the method actually works. If you can design tests that will cover all your code, that's great! 100% test coverage is a definite thing to strive for, but it's not always practical (or useful) depending on the situation.

A: Especially on build servers it is easier to have many different testcases/functions because it will be easy to identify which test fails. Another downside is that the testcase will halt if the first one fails, and you will not know the result of the other testcases.
For me personally this benefit stops when you have to do a lot of copy pasting to set up/explain the testcase, in that case I will just do several asserts in the same test case.


text:
Q: CreateProcess ошибка 1812: CreateProcessW - The specified image file did not contain a resource section Есть код создания процесса, на виртуальных машинах и на моём pc он отрабатывает корректно, подключаюсь по RDP к клиенту, передаю файл, запускаю -

[Error 1812] CreateProcessW - The specified image file did not contain a resource section.

Код по сути
STARTUPINFOW si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
CreateProcessW(0, szCmdLine, 0, 0, FALSE, CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS, 0, 0, &si, &pi);

При чём это не зависит от версии ОС, и на всех машинах к которым имею доступ физически - всё работает.


text:
Q: Trigonometric Equation from Hobson's Book How to solve this equation:
$$
\cos(2x+y)=\sin(x-2y) \quad \text{and} \quad \cos(x+2y)=\sin(2x-y)
$$

A: Hint:
Use that $\sin(x-2y)=\cos\Bigl(x-2y-\tfrac\pi 2\Bigr)$, whence
$$2x+y\equiv \pm (x-2y-\tfrac\pi 2)\mod 2\pi,$$
and similarly for the other equation.


text:
Q: Integration on compact manifold Integration on a nice enough manifold of a function $f:M \to \mathbb{R}$ is defined
$$\int f = \sum_{ i \in I} \int_{U_i}\phi_i f$$
where $\phi_i$ is a partition of unity subordinate to the open cover $U_i$ of $M$.
The index set $I$ can be infinite in general.
If $M$ is compact (bounded), can I take $I$ to be a finite set so that the sum is a finite sum?

A: Yes, since every open cover has a finite subcover (Heine-Borel).


text:
Q: how to open widget, have it do something, and close by itself? I am trying to do the following:
I have a QMainWindow object. From it, I want to open window, have it do something, and close by itself.
Like start something > open window with "Loading.." message > do the thing > have the window close by itself without interaction from the user.
I have tried to create a QWidget class and put the "do the thing" method in there, but when I call the .show() method on the QWidget, the whole application hangs and doesn't go further, but maybe I don't understand the logic behind it.
I am using Python 3.7.7, PyQT5, my OS is Windows 10 x64 (if it's important)

A: I hope that I understood your question correctly. I would solve the problem in the following way:
from PyQt5 import QtTest
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget

import sys

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.loading_window = None
        self.button = QPushButton("Push for Window")
        self.button.clicked.connect(self.show_new_window)
        self.setCentralWidget(self.button)
        self.timer = QTimer()

    def show_new_window(self):
        if self.loading_window is None:
            self.loading_window = LoadingWindow()
        self.loading_window.show()
        self.do_your_job()
        self.close_loading_window()

    def do_your_job(self):
        # Do whatever you want here
        QtTest.QTest.qWait(1500)

    def close_loading_window(self):
        self.loading_window = None

class LoadingWindow(QWidget):

    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.label = QLabel('Loading')
        layout.addWidget(self.label)
        self.setLayout(layout)
        self.setWindowFlag(Qt.FramelessWindowHint)

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()


text:
Q: using regexpression to replace a word I have a sentence that may have "not, or" inside.
Currently, I'm trying to test and remove these words, however, I couldn't figure out how to write a correct regex test pattern, can someone help please?
I tried with
string test= "";
string str=" some words here ";

if (str.ToLower().Contains(" not ")) {
    test = str.ToLower().Replace(" not ", " ");
} else if (str.ToLower().Contains(" or ")) {
    test = str.ToLower().Replace(" or ", " ");
}

A: I think you mean to replace "not" and "or"
string resultString = null;
try {
    resultString = Regex.Replace(subjectString, "(?:not|or)", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

A: You can use String.Replace for that
string sString = "Sometimes not, or sometimes no";
string sNew = sString.Replace("not, or", String.Empty);


text:
Q: how to get unlimited range in vba Dim Brand As String
    Worksheets("1st").Select
    Brand = Range()

Hi, I am using VBA coding in microsoft excel 2011 and I am a little stuck with range. Lets say I want to start something in cell c4, I enter in c4 in the range but if I then want it to continue till all the way down the column (unlimited as we don't know how many rows in that column will be filled up), then what is the correct way of writing this?

A: Range("C4", Range("C4").End(xlDown))

This will return the range, C4 to C4 and Down.
This will select all contiguous cell from C4 down all the way until the first blank cell.
Now if you Data has a chance that it might have blanks in between non blank cells. Then you can use the following:
Range("C4", Range("C" & Rows.Count).End(xlUp))

this will select C4 to The last cell in C columns up until the the cell with data. In other words this will select EVERY cell in the C column from C4 until the last cell in the entire column with a value, and include blanks.

A: Another way
Sub Main()

     Dim Brand As String
     Dim lastRow As Long
     Dim rng As Range, cell As Range

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("1st")

    With sht
     lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    End With

    If lastRow < 4 Then lastRow = 4

    Set rng = sht.Range("C4:C" & lastRow)

    For Each cell In rng
       MsgBox cell.Value
    Next

End Sub


text:
Q: Python requests: "IndexError: list index out of range" Please do not mark it as a trivial duplicate of: Python requests giving errror: IndexError: list index out of range
I am encountering the said error when trying to send a GET to:
http://astat.bugly.qq.com
The exact line that I use in the code that gives me the request is, maybe I am overlooking something:
r = requests.get("http://"+url, stream=True, timeout=3)

where astat.bugly.qq.com is passed as url
I am reading the url out of a csv-file but I checked that it reads the appropriate url.
I can even recreate it multiple times  the python-REPL, I hope you can too.
 Proof:

I dont know what could be causing this.

A: The url in question is a plain text document, which is sent without any headers.
The requests library seems to insist on there being at least one header (it's doing headers[-1] when you get the index error).
I'm not sure if you can do anything in requests to work around it, but you could use urllib:
import urllib
txt = urllib.urlopen('http://astat.bugly.qq.com').read()

update:

my goal is to read certain headers from a website, how would you suggest I do that considering the situation ?

The server sends the following:
~$ telnet astat.bugly.qq.com 80
Trying 103.7.30.121...
Connected to astat-bugly-tgw4l.mig.tencent-cloud.net.
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.1 200 OK
                Date: Thu, 30 Aug 2012 12:01:27 GMT
                Server: Apache/2.2.17 (Unix) PHP/5.3.6
                Cache-Control: max-age=1800
                Keep-Alive: timeout=5, max=98
                Connection: Keep-Alive
                Transfer-Encoding: chunked
                Content-Type: text/plain; charset=UTF-8
                Copyright @ 1998 - 2012 Tencent. All Rights Reserved.
                Content-Length: 17

lb monitor page
Connection closed by foreign host.

short of using telnet (or something similarly low level), I don't think you'll have much luck getting at those "headers" (which should of course not be indented, or have a random copyright string embedded).


text:
Q: creating http link dynamically according to the user input I am now building a webpage with a search box included. How to create a search query which changes according to the input on the search box?
<input type=text name="searchquery"/>
<input type=button name=search value="search" onClick=changeQuery()/>

changeQuery(){
????
}

A: Anyhow i managed to get the desired output...
<input type=text id='sq' name="searchquery"/>
<input type=button name=search value="search" onClick=changeQuery()/>

changeQuery(){
var input_query=document.getElementById('sq').value;
window.location="http://www.google.com/search?q="+input_query+"myString";
}


text:
Q: Serverless V2: Value not found at "opt" source We are currently using Serverless v2.0.0, and want to upgrade to the latest v3. As per their documentation, I am first upgrading to the latest v2.
We are using a python script to run serverless using the subprocess library, as we use secrets manager to get some cli params. The command string is as follows:
command = [
        "npm", "run",
        "serverless", "--", "deploy",
        "--elastic", elasticHost,
...
    ]

The serverless.yml file looks like this:
service: devices
variablesResolutionMode: 20210326

plugins:
  - serverless-plugin-typescript
  - serverless-offline
  - serverless-domain-manager
  - serverless-prune-plugin

provider:
  name: aws
  versionFunctions: false
  environment:
    ES_HOST_URL: ${opt:elastic}
...

I can confirm that elasticHost does exist, I see it in the terminal when I run the script. However, when I run the script, I get the following error:
 > serverless "deploy" "--profile" "dev" "--aws-profile" "dev" "--elastic" "xxx" ...

 Serverless Error ----------------------------------------

  Cannot resolve serverless.yml: Variables resolution errored with:
    - Cannot resolve variable at "provider.environment.ES_HOST_URL": Value not found at "opt" source,

My package.json is as follows:
    "serverless": "^2.72.3",
    "serverless-api-compression": "^1.0.1",
    "serverless-domain-manager": "^6.0.3",
    "serverless-offline": "^8.7.0",
    "serverless-plugin-split-stacks": "^1.11.3",
    "serverless-plugin-tracing": "^2.0.0",
    "serverless-plugin-typescript": "^2.1.2",
    "serverless-prune-plugin": "^2.0.1",
    "serverless-pseudo-parameters": "^2.6.1",
    "serverless-python-requirements": "^5.4.0",
    "serverless-step-functions": "^3.7.0",

If I replace {opt:elastic} with its value, I don't get the error, but I don't want it hardcoded. I'm trying to understand why I am getting this error, and how I can resolve it.
I haven't used serverless before, so any help on this would be greatly appreciated.
Thank you.

A: I had the same error in the past. Lamentably, I didn't find a way to set dynamic values with opt command but I found another solution.
You can define environment vars in your serverless command and then use the env var in your serverless file so:
First, let's define a script in your package.json:
"scripts": {
   "serverless": "url=secondary serverless.. "
}

Then in your YML file, you should have something like this:
environment:
    ES_HOST_URL: ${env:url, 'www.stackoverflow.com'}

This means, that if you don't set the env variable, this will set www.stackoverflow.com otherwise will be the value that you send from the command.
Finally, just run npm run serverless and that's it


text:
Q: What does the expression &Proc.new do in a method? I found usage of &Proc.new in the rails sources:
# rails/railties/lib/rails/engine.rb
def routes
  @routes ||= ActionDispatch::Routing::RouteSet.new
  @routes.append(&Proc.new) if block_given?
  @routes
end

I don't understand how the expression &Proc.new works.
I wrote similar code and it failed:
def method_name
  &Proc.new if block_given?
end
proc = method_name{ puts 'Hello world!' }
proc.call

I received a syntax error:
syntax error, unexpected &
    &Proc.new if block_given?

*

*What does the expression &Proc.new do in a method?

A: First you should know and understand what blocks and Procs are. Basically they are the way ruby provides closures. Here is a good link.
The unary ampersand operator in ruby has 3 uses (all of them related to blocks and Procs):

*

*If applied to an argument in a method definition, then the implicit block parameter is stored as a Proc using the argument name.

*If applied to a Proc in a method call, then the block contained in the Proc is passed as the implicit block parameter. It preserves whether the Proc is a lambda or not. Methods are always lambdas.

*If applied to other object in a method call, the method #to_proc is called and the resulting Proc is passed as in the second case.
The & Operator in Ruby explains it in detail.

A: & has a special meaning in argument list - when used as prefix for Proc object it passes it as block to method being called. Within method body it's just a binary operator.

A: If Proc.new is called from inside a method without any arguments of its own, it will return a new Proc containing the block given to its surrounding method.
def foo
  Proc.new.call
end

foo { puts "hello world" }
# hello world

This means that it is now possible to pass a block between methods without using the &block parameter:
class C
  def bar
    puts "called bar..."
    baz &Proc.new
  end

  def baz
    puts "called baz..."
    yield
  end
end

C.new.bar { puts "called block..." }
# called bar...
# called baz...
# called block...

This trick gets used by Rails at
# File railties/lib/rails/engine.rb, line 533
def routes
  @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config)
  @routes.append(&Proc.new) if block_given?
  @routes
end

More details at

*

*https://github.com/rails/rails/blob/375a4143cf5caeb6159b338be824903edfd62836/railties/lib/rails/engine.rb#L532-L538

*https://mudge.name/2011/01/26/passing-blocks-in-ruby-without-block.html

*http://confreaks.tv/videos/rubyconf2010-zomg-why-is-this-code-so-slow


text:
Q: Creating Scoring Matrix I have a scoring matrix which I use in excel consisting of 5 categories each scored by Impact & Likelihood using a look up, then multiplied. The total from each category is summed to provide a Final Score. Can this be done in SharePoint 2013 easily and if so how:
Example:
Category 1
Impact: Serve = 4
likelihood: Happening = 5
Total Cat 1 = Impact multiplied by likelihood
Category 2
Impact: Major = 3
likelihood: Probable = 3
Total Cat 2 = Impact multiplied by likelihood


text:
Q: C++ A custom member compare function Please consider the following piece of code. I am getting a compilation error.  How should I write a custom compare function.
#include <iostream>
#include <vector>
#include <boost/cstdint.hpp>
#include <utility>
#include <algorithm>

class X
{
  public:
    std::vector<std::pair<boost::uint64_t, boost::uint64_t> > vec;
    bool cmp(const std::pair<boost::uint64_t, boost::uint64_t>& d1,
        const std::pair<boost::uint64_t, boost::uint64_t>& d2);
    void foo(void);
    void print(void);
};

bool X::cmp(const std::pair<boost::uint64_t, boost::uint64_t>& d1,
    const std::pair<boost::uint64_t, boost::uint64_t>& d2)
{
  return d1.first < d2.first;
}

void X::foo(void)
{
  vec.push_back(std::make_pair(1000, 100));
  vec.push_back(std::make_pair(800, 200));
  std::sort(vec.begin(), vec.end(), cmp);
}

void X::print(void)
{
  for (auto it = vec.begin(); it != vec.end(); ++it)
  {
    std::cout << it->first << std::endl;
  }
}

  int
main()
{
  X x;
  x.foo();
  x.print();
  return 0;
}

Compilation error:
 g++ --std=c++11 custom_cmparator.cpp

 custom_cmparator.cpp: In member function 'void X::foo()':
 custom_cmparator.cpp:28:40: error: no matching function for call to       'sort(std::vector<std::pair<long unsigned int, long unsigned int>  >::iterator, std::vector<std::pair<long unsigned int, long unsigned int>  >::iterator, <unresolved overloaded function type>)'
 std::sort(vec.begin(), vec.end(), cmp);

How should I specify
     std::sort(vec.begin(), vec.end(), cmp);

A: Make it static member function or non-member at all.
If you need to access class members in your comparator (though your example doesn't need it), you can either use either way mentioned in comments below or such lambda:
std::sort(vec.begin(), vec.end(),
    [this](const std::pair<boost::uint64_t, boost::uint64_t>& d1,
           const std::pair<boost::uint64_t, boost::uint64_t>& d2) {
               return this->cmp(d1, d2);
    }
);

A: I will post this as an alternative answer in case you don't want to use a static member function or a non-member one or a lambda, as mentioned in @Paul's response. You can use std::bind from #include <functional> like
void X::foo(void)
{
    using namespace std::placeholders; // for _1, _2 etc

    vec.push_back(std::make_pair(1000, 100));
    vec.push_back(std::make_pair(800, 200));
    std::sort(vec.begin(), vec.end(), std::bind(&X::cmp, this, _1, _2));
}


text:
Q: loading external files flex bison - yyin? I am writing a basic language in flex + bison for my own personal research / to run simple scripts for fun.
It takes user input via the command line, parses it, and executes the desired result. I would like to add functionality load files.
for example, when the "load file 'somefile.src'" the file is loaded and automatically parsed, then the parser switches back to waiting for command line inputs.
I haven't been able to make sense of the documentation and am pretty lost. It doesn't help that I am new to flex, bison, and C as a whole.
I am following this pdf: http://epaperpress.com/lexandyacc/ (using the complex calculator as a skeleton and adding functionality on top of it) as well as looking through bison documentation http://www.gnu.org/software/bison/manual/bison.html.
Any advice would be appreciated.

A: Input handling is done by flex, so you need to read the flex manual for details.
The section on multiple input buffers (linked above) has example code for handling "include"-like constructs. In fact, there are two sample implementations; one using the built-in buffer stack (recommended) and the other with an explicit buffer stack.
Really, it is not very complicated. To start reading a new file, all you need to do is this:
yyin = fopen(filename, "r");
if ( !yyin ) /* Handle the error */
yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));

You pop the buffer state in your EOF rule:
<<EOF>> { yypop_buffer_state();
          /* Make sure we stop if the EOF is the original input. */
          if (!YY_CURRENT_BUFFER) { yyterminate(); }
        }


text:
Q: Selected Item in Dropdown Lists in ASP.net MVC Is it possible to select an element and return another element in View? Can I pass a key to a dictionary of c# in javascript razor?
// c# dictionary
dictionary dic
[localize("option1"), 1]
[localize("option2"), 2]
[localize("option3"), 3]
[localize("option4"), -1]

//razor code
@Html.DropDownList("options", new SelectList(dic.keys))

Then I want to get the value by the key $('#options').val() and pass it to the c# back from javascript json


text:
Q: Sending array to popup window with javascript I have the following code:
var my_window=window.open("print.php");
my_window.testValue="some value";

In print.php page I have this code:
alert(window.testValue);

This works in chrome and mozilla but does not work on IE, what might be the problem?

A: As you mentioned in comment using javascript array declare your value as global,
window.data = data;

as you asked make your variable global please look at Make Variable as Global JavaScript
And the use below code
var theArray = window.opener.theArray
More Info
Hope this helps...


text:
Q: Rials:When we use fields_for, how to initiate association_build if we are not sure how many association should be created? In such case:
class User < ActiveRecord::Base
  has_many :companies
  accepts_nested_attributes_for :companies
end

class Company < ActiveRecord::Base
 belongs_to :users
end

This is nomal case, we're sure how many association we should create:
# user_controller
def new
  @user = User.new
  2.times { @user.companies.build }
end

But what if we don't know how many association should be created?


text:
Q: SQL to LINQ with left join and group I created a worked sql query:
select CONVERT(date, C.tDate) as dt, count(O.Id) as cnt  from [Calendar] C
left outer join [Order] O
on C.tDate = CONVERT(date, O.Dt)
group by CONVERT(date, C.tDate)
order by CONVERT(date, C.tDate)

And I want to rewrite it use LINQ:
var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from pl in pp.DefaultIfEmpty()
group c by DbFunctions.TruncateTime(pl.Dt.Value) into g
orderby g.FirstOrDefault().tDate
select new { date = g.FirstOrDefault().tDate, cnt = g.Count() }).ToList();

I get all rows from calendar in sql query, but only not null rows (right part) in LINQ query.
How can I get all calendar's rows in LINQ.
Added:
Then I try:
var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(o.Dt) into g2
select new { date = g2.Key, cnt = g2.Count() }).ToList();

And I see this one:
{ date = null, cnt = 1062 }
{ date = {25.01.2019}, cnt = 4 }
{ date = {26.01.2019}, cnt = 7 }
{ date = {27.01.2019}, cnt = 16 }
{ date = {28.01.2019}, cnt = 5 }

I want to get all dates instead null...

A: This one:
var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(c.tDate) into g2
orderby g2.Key
select new { date = g2.Key, cnt = g2.FirstOrDefault().Count() }).ToList();


text:
Q: How to use a dynamic ng-repeat depending on user input I need to use two ng-repeat: one shows car brands and the other shows car models. This last one should only present the models of the selected car brands, but I have no ideia how to do it.
My two JSON files have this structure:
{
  "brands" : [
  {
    "id": 0,
    "name": "Alfa Romeo",
    "short_url": "alfa-romeo"
  },

{ "models" : [
  {
    "id": 0,
    "brand_id": 0,
    "name": "MiTo"
  }, ...

And my HTML is looking like this:
<label>Brand
    <input list="brands" name ="brand" type="text" placeholder="Select your brand...">
    <datalist id="brands">
        <option ng-repeat="b in brands">{{b.name}}</option>
    </datalist>
</label>

<label>Model
    <input list="models" name ="models" type="text" placeholder="Select your model...">
    <datalist id="models">
        <option ng-repeat="m in models">{{m.name}}</option>
    </datalist>
</label>

I need to compare the models' brand_id with the selected brand's id. I heard about ng-if so i tryied this (didn't work):
<div ng-if="models.brand_id === b.id">

Any help is appreciated :)

A: You don't need an input when making a selection. You can use the select element.
To get this to work you need to first communicate to your app that something has changed. Try changing your first input to a select element and putting an onchange handler in it. When a brand is selected we will save the models of that brand to the $scope and render them in the Models section. We can use ng-if to display the Models selection, only if a brand selection has been made.
Going forward you can then use a similar pattern for when making a model selection
We can set the value of the select options by using the "as" keyword.
b.id as b.name means that we will display the name, but store the value of the id.
<label>Brand
    <select onchange="handleChange" ng-options="b.id as b.name for b in brand"/>
</label>

<label>Model
  <select ng-if="modelsOfSelectedBrand" ng-options="m.id as m.name for m in models"/>
</label>

Then in your directive
$scope.handleChange((e) => {
// filter out models that are not from the selected brand
  $scope.modelsOfSelectedBrand = $scope.models.filter(model => model.brand_id === e.target.value)
})

EDIT: correctly use ng-options


text:
Q: Button Content as their Name My Question is purely related to XAML and not code behind.
Can a WPF Button Content be same as its Name.
One way of doing it is like
<Button Name="button1" Content="button1">

But i have 250 such buttons and changing both button name and content is like changing at 500 places. so is there a way where i have to change only the button name and content reflects that value.
<Button Name = "button1" Content ={??????}>

A: Data binding:
Content="{Binding Name, RelativeSource={RelativeSource Self}}"

(Read the reference, data-binding is an integral part of WPF)


text:
Q: How to use GROUP BY when fetching values from More than one Table We have 2 Tables  Employees and Department.

*

*We want to show the maximum salary from each department and their corresponding employee name from the employee table and the department name from the department table.

Employee Table
EmpId | EmpName |salary |DeptId

  101   shubh1    1000    1
  101   shubh2    4000    1
  102   shubh3    3000    2
  102   shubh4    5000    2
  103   shubh5    12000   3
  103   shubh6    1000    3
  104   shubh7    1400    4
  104   shubh8    1000    4

Department Table
DeptId | DeptName
  1      ComputerScience
  2      Mechanical
  3      Aeronautics
  4      Civil

I tried doing it but was getting error
SELECT DeptName FROM Department where deptid IN(select MAX(salary),empname,deptid
FROM Employee
GROUP By Employee.deptid)

Error

Token error: 'Column 'Employee.EmpName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.' on server 4e0652f832fd executing on line 1 (code: 8120, state: 1, class: 16)

Can someone please help me.

A: Now that I know it's MS SQL Server, technically; we could use cross or outer Apply; it's a table value function not a join per say...   but this will depend on the version of SQL Server; and if you want data if it doesn't exist in another
I find this the "Best" Design pattern to use for this type of query.
What the engine does is for each record in department, it runs a query for the employees Finding those in that department returning the 1 record having the max salary.  With top we could specify with ties to return more than one.  but we would need to know how to handle Ties of salary.  Use top 1 with ties or order the results so you get the "Top" result you want.
Demo: dbfddle.uk
SELECT Sub.empName, Sub.Salary, D.DeptName
FROM Department D
CROSS Apply (SELECT Top 1 *
          --(SELECT TOP 1 with Ties * -- could use this if we ties
             FROM  Employee E
             WHERE E.DeptID = D.DeptID
             ORDER BY Salary Desc) Sub  --add additional order by if we don't want ties.

The cross apply gives us:
+---------+--------+-----------------+
| empName | Salary |    DeptName     |
+---------+--------+-----------------+
| shubh2  |   4000 | ComputerScience |
| shubh4  |   5000 | Mechanical      |
| shubh5  |  12000 | Aeronautics     |
| shubh7  |   1400 | Civil           |
+---------+--------+-----------------+

Before window functions, before cross Apply or lateral... We'd write an inline view
It would get us the max salary for each dept, we then join that back to our base tables to find the employee within each dept with max salary...
Demo: DbFiddle.uk
SELECT E.*, D.*
FROM Employee E
INNER JOIN Department D
 on E.DeptID = D.DeptID
INNER JOIN (SELECT MAX(SALARY) maxSal , DeptID
            FROM Employee
            GROUP BY DeptID) Sub
on Sub.DeptID = E.DeptID
and Sub.MaxSal = E.Salary

One has to do a join to get the department info an the employee info.  However, we can eliminate the join for salarymax by using exists and correlation instead.
Demo DbFiddle.uk
SELECT E.*, D.*
FROM Employee E
INNER JOIN Department D
 on E.DeptID = D.DeptID
WHERE EXISTS (SELECT MAX(Sub.SALARY) maxSal , Sub.DeptID
            FROM Employee  Sub
            WHERE sub.DeptID=E.DeptID  --correlation 1
            GROUP BY Sub.DeptID
            HAVING E.Salary = max(Sub.Salary)) --correlation 2

We could eliminate the last join too I suppose:
Demo: Dbfiddle.uk
SELECT E.*, (SELECT DeptName from Department where E.DeptID = DeptID)
FROM Employee E
WHERE EXISTS (SELECT MAX(Sub.SALARY) maxSal , Sub.DeptID
            FROM Employee  Sub
            WHERE sub.DeptID=E.DeptID  --correlation 1
            GROUP BY Sub.DeptID
            HAVING E.Salary = max(Sub.Salary)) --correlation 2

The top 3  give us this result:
+-----+---------+--------+--------+--------+-----------------+
| id  | empName | salary | deptID | DeptID |    DeptName     |
+-----+---------+--------+--------+--------+-----------------+
| 101 | shubh2  |   4000 |      1 |      1 | ComputerScience |
| 102 | shubh4  |   5000 |      2 |      2 | Mechanical      |
| 103 | shubh5  |  12000 |      3 |      3 | Aeronautics     |
| 104 | shubh7  |   1400 |      4 |      4 | Civil           |
+-----+---------+--------+--------+--------+-----------------+

A: select  salary
       ,EmpName
       ,DeptName
from    (
        select   e.salary
                ,e.EmpName
                ,d.DeptName
                ,rank() over(partition by e.DeptId order by e.salary desc) as rnk
        from    Employee e join Department d on d.DeptId = e.DeptId
        ) t
where   rnk = 1

salary
EmpName
DeptName

4000
shubh2
ComputerScience

5000
shubh4
Mechanical

12000
shubh5
Aeronautics

1400
shubh7
Civil

Fiddle


text:
Q: Naming convention for Erlang functions I was trying to create a function name like 5gc_ep_n2 and it gave me a syntax error. What is the exact naming convention for the functions in Erlang?
updated: Found this reference helps too.

A: Function names are atoms, and follow the same rules as atoms.  From the reference manual:

An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

So you can call your function 5gc_ep_n2, but you'd have to enclose it in single quotes, '5gc_ep_n2', both when defining and calling it.


text:
Q: Data controls on pdf form - Livecycle + XML Datasource I need to create a pdf form where you can click through different records from an xml data source, similar to the ODBC version shown here.
For ODBC the following APIs were used:
xfa.sourceSet.DataConnection.last();
xfa.sourceSet.DataConnection.first();
xfa.sourceSet.DataConnection.previous();
xfa.sourceSet.DataConnection.next();
xfa.sourceSet.DataConnection.addNew();
xfa.sourceSet.DataConnection.delete();

However xfa.sourceSet is not available with XML data connection(, at least in ES4).
How can I create this same functionality with XML Data Source?
Here is a simplified version of the form and xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
  </book>
</bookstore>

If I manually change the binding for subform book (shown with the blue arrow in screenshot) to $record.book[1] the details for the second record are shown in the generated pdf.  Is it possible to change the bindings via javascript?
Here is a link to a copy of the form and the xml.

A: The form is bound when it is first rendered, so changing the value of the binding through Javascript isn't going to work.
Some alternatives:
Make the subform repeating and put Javascript on the buttons to hide all the instances except the relevant one.
Bind the book data to a separate hidden repeating subform and use Javascript to populate the fields from the relevant instance of the hidden subforms.
Don't bind the subform at all and use Javascript to access the data model directly to populate the fields.


text:
Q: Gradle not including FXML and images I have been looking around for the proper way to include FXML and images in the build.gradle so that they are build into the jar. I have look here and tried it but it still does not work.
Throws this error: java.lang.NullPointerException: inputStream is null.
Here is the build.gradle (Github):
group 'com.voidustries'
version '1.0-SNAPSHOT'

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/java/com/voidustries/poly"]
            includes = ["gui/layoutForm.fxml"]
        }
    }
}

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.1.0'
    }
}

apply plugin: 'java'
apply plugin: 'org.junit.platform.gradle.plugin'

repositories {
    mavenCentral()
}

dependencies {
    testCompile('org.junit.jupiter:junit-jupiter-api:5.1.0')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.1.0')
}

task wrapper(type: Wrapper) {
    description = 'Generates gradlew[.bat] scripts'
    gradleVersion = '4.3.1'
}

test {
    testLogging {
        events "passed", "skipped", "failed"
    }
}

Here is GUI.java (Github):
FXMLLoader loader = new FXMLLoader();
FileInputStream fis = new FileInputStream(settings);
ResourceBundle resourceBundle = new PropertyResourceBundle(fis);
loader.setResources(resourceBundle);

Parent root = loader.load(getClass().getResourceAsStream("layoutForm.fxml"));
Platform.setImplicitExit(false);

The stacktrace says that loader.load(getClass().getResourceAsStream("layoutForm.fxml")); is causing the error
Here is the source Tree:
com
└───voidustries
    └───poly
        │   CustomFormatter.java
        │   Main.java
        │   PolyThreads.java
        │   SysTray.java
        │
        ├───gui
        │       Controller.java
        │       GUI.java
        │       Icon.png
        │       layoutForm.fxml
        │
        └───img
                Icon.png

you can see that layoutForm.fxml and Icon.png are both there in the tree
Here is the Out tree:
com
└───voidustries
    └───poly
        │   CustomFormatter.class
        │   Main.class
        │   PolyThreads.class
        │   SysTray.class
        │
        └───gui
                Controller.class
                GUI.class

In the out tree they are both absent and I have been fiddling for hours trying to fix this issue. Any help would be greatly appreciated.
Also if you need more here is the Github repository

A: Just to add my thre'penny bit for anyone not getting satisfaction:
Under src/main/resources (Windows src\main\resources) you seem to have to make the "location" of your resource file match the classpath used to run your .class files.
I have concluded this (until a more knowledgeable person says otherwise) from playing around with an .fxml file in a JavaFX gradle project.
The class Main (containing main()) is in a package called "sample"... so the path to the .java file is ...\EclipseWorkspace\TestFXexp\src\main\java\sample\Main.java.
This appears to mean that your .fxml file has to go here: ...\EclipseWorkspace\TestFXexp\src\main\resources\ sample\config.fxml.
gradle installdist will then correctly package up the .jar for deployment.  Expanding the .jar you find that config.xml has been put under directory sample\ along with the .class files... and that the Main.class file is able to find it and use it.
When I put the config.fxml like this: ...\EclipseWorkspace\TestFXexp\src\main\resources\config.fxml ... it didn't work: the config.fxml is put then outside the sample package in the .jar file and the Main.class file can't find it.

A: You are putting xml files in a folder called src/main/java (hint: java dir is for java files)
Resources (eg xml, image files etc) should go in src/main/resources
This is a standard convention followed by both Maven and Gradle. If you want to change the defaults you can, but first I strongly advise you consider following the sensible conventions.
Also, a note on classloaders

*

*SomeClass.class.getResource("foo.xml") will look for the xml relative to the class package

*SomeClass.class.getResource("/foo.xml") will look for the xml relative to the classpath root

So in your example
getClass().getResourceAsStream("layoutForm.fxml")

This is looking for a file on the classpath com/voidustries/poly/gui/layoutForm.fxml
So if you want to leave your resources where they are, you will want to add src/main/java to the resource folders, not src/main/java/com/voidustries/poly


text:
Q: Export Tier Pricing I run a B2B web store, and all the products use tier pricing instead the static MSRP pricing.
When using the Import/Export, they have no field to include the tier pricing..
Is there anyway for me to efficiently export all the tier pricing for the products?
I assume MAGMI would be efficient enough to import all the products along with their tier pricing, I just need to figure out how to export them! Thanks!

A: You can use native Magento 1.9 export (System -> Import/Export -> export). Tier-price related fields exported will look like these - http://screencast.com/t/p88DGX3DFQ
Since Magento itself does not allow import tier prices you have to make sure that module you chose to import them supports this format or adjust your file.


text:
Q: Is there a way to set up a rule in Outlook 2010 based on more than one header? I'm trying to setup a rule in Outlook 2010 that examines the headers of a message.
The problem is that it seems I can only create a condition for the rule based on whether a message's header contains some text OR some other text.
I need the condition to be sometext1 AND sometext2.    Since these two strings are separate I can't use sometext1 sometext2 since they won't necessarily appear next to each other.  When I add the strings separately it wants to OR them together.  It is sort of like I need to be able to add an additional "with specific words in the message header" check box to the conditions.
Is there any way to do this?

A: Unfortunately, Outlook doesn't allow anything but OR, but I did find a workaround using categories you can try.
Using AND operators in rules
It's not written specifically for message headers, rather for message body, but should work the same since the rule is using a text search.


text:
Q: When is the Layout of an activity loaded in android? This is my activity(snippet):
setContentView(R.layout.main)
//Some Time consuming code

As you can see the time consuming code is placed after the setcontentview. This activity takes a lot of time to load. to confirm I removed the time consuming code and the activity is displayed very quickly.My question is I am doing the time consuming work only after setContentView the layout, then why does it take so much time to display at least the layout .

A: The app is running on a single thread UI thread. It cannot show the view until it has finished running everything else.
You need to use an AsyncTask or a thread for any time consuming code. Have a look at this: http://developer.android.com/resources/articles/painless-threading.html

A: Every time consuming tasks should be done in a non-UI Thread. Consider using an AsyncTask.
To answer your question, the activity will only be displayed when the whole onCreate method is finished. So it sets its content view, then it executes the reste of the onCreate method (your time consuming code) then it shows.
For your information, here is the documentation for AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html

A: You should do all your time consuming work in the onResume() method. then it may take less time to complete the onCreate() method and your layout will be loaded faster.


text:
Q: Linux date command not working I can't seem to get the terminal command 'date' working. Here is an example of the commands I gave in terminal:
$ date
Wed Oct  7 17:17:38 EDT 2015
$ sudo date --set="20151007 18:17:00"
Wed Oct  7 18:17:00 EDT 2015
$ date
Wed Oct  7 17:18:11 EDT 2015

Is there something I need to change in the settings to be able to manually set the time? I've looking into disabling ntp but as far as I can tell it isn't something that needs to be disabled to be able to manually set time.
I've looked up all the possible formats of the date string, and none of them did the trick. Here are some of the ones I tried:
$ sudo date --set="2 OCT 2006 18:00:00"
$ sudo date +%Y%m%d -s "20081128"
$ sudo date 120622432007.55
$ sudo date --set="Sat Oct 10 10:10:10 EDT 2015"

I would appreciate any help. Thanks.

A: Look though the process list printed by
ps -ef

to see for likely culprits. These may include

*

*ntpd

*ntpdate

*systemd-timesyncd

*...

In my case, I had to do
systemctl stop systemd-timesyncd

A: It turns out I had to change time/date settings from automatic to manual in System Settings. As I am doing everything through ssh I could not do this in the gui settings, but the equivalent command on terminal is:
$ timedatectl set-ntp false

This disables the automatic time sync allowing me to set the time and date manually using the date command


text:
Q: Shinken Monitoring - how to configure service checks on a host, for a specific time of the day We are using Shinken Framework for monitoring our servers, in that I got a scenario like I want to execute a service check only once in a day that is everyday at 1 AM, how can I configure it?
Using check_interval or time_period can we achieve this..?

A: You need to set check_interval and check_period.
For example, we are using check at 9 AM everyday for check system updates. Just change time and service for your needs.
define timeperiod {
  timeperiod_name                morning_check
  alias                          morning_check
  monday                         09:00-09:01
  tuesday                        09:00-09:01
  wednesday                      09:00-09:01
  thursday                       09:00-09:01
  friday                         09:00-09:01
  saturday                       09:00-09:01
  sunday                         09:00-09:01
}

define service {
  service_description            updates
  host_name                      Docker
  use                            svc-pnp,local_standard_mail
  check_command                  ext_nrpe!check_updates!null
  check_period                   morning_check
  check_interval                 1440
  max_check_attempts             1
  notification_interval          1440
}


text:
Q: Java: Bank account transatcion limit -> How to represent that there is no limit for some accounts? I have a quick question about representing single transaction limits for bank accounts. I have different types of bank accounts where each one has a certain single transaction limit. However, some of these account types have no transaction limit. I could come up with a pretty simple solution which just uses a constant to indicate that (see example below).
private static final double NO_TRANSACTION_LIMIT = -1;

public enum BankAccountType {
    GIRO_MINOR(0, 20, "Minor Account"),
    GIRO_STUDENT(0, 200, "Student Account"),
    GIRO_NORMAL(-2000, 4000, "Normal Account"),
    SAVING(0, NO_TRANSACTION_LIMIT, "Saving Account");
    // ...
    private double transactionLimit;
    // ...
    public boolean hasTransactionLimit() {
        return transactionLimit == NO_TRANSACTION_LIMIT;
    }
}

After some thinking, I thought there must be a better solution to that problem. Because if for some reason the method hasTransactionLimit() is not checked before a transaction limit, this might cause unwanted behavior.
So my question: what is a good strategy to implement behavior like that? Somehow I thought of the Null-Object pattern, but I am pretty unsure.

A: I would create an interface BankAccount with a method isTransactionAllowed(int amount) instead of using an enum that returns a transation limit.
Because what you want to do with your enum is to execute type specific code. That's why the enum is named ...Type. In an object oriented language like java you should do this using polymorphism.
E.g.
public interface BankAccount {
    public boolean isTransactionAllowed(int amount);
}

And the concrete bank account can answer this question. Either statically or based on it's actual state. E.g. a limit of 200 is allowed within 10 days or this bank account allows a transaction limit of 200 while all other of this type only allow 100.
E.g. statically:
public class MinorBankAccount implements BankAccount {

    private static final int MINOR_ACCOUNT_TRANSACTION_LIMIT = 20;

    public boolean isTransactionAllowed(int amount) {
        return amount <= MINOR_ACCOUNT_TRANSACTION_LIMIT;
    }

}

What you do is usually a hint for an anemic design. For more details take a look at my blog Enums as type discriminator anti-pattern


text:
Q: grails create criteria non unique object error if wrapped in withNewSession I have criteria that looks like this
  //Inventory.withNewSession{
    Set inventory=Inventory.withCriteria{
       setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
       inventoryDetail{
           eq('userAdded',true)
       }
       ...
     }
//}

If I wrap that in a withNewSession I get duplicate key and non unique object in the session errors. If I don't use withNewSession, it works.
Why?

A: If you already had a session and loaded object with id=1 (e.g.), and then created a new session and loaded that same object.  When the new session block ends, the hibernate session joins the existing session (am I saying this right?) and now you have your both objects loaded with the same ID.
I'm not sure why you're using withNewSession here, is there a path that this may execute without a hibernate session?  Are you trying, as TDC suggests, to isolate this transactionally?

A: maybe try to use replace withNewSession with withTransaction?
Inventory.withTransaction{
    Set inventory=Inventory.withCriteria{
       setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
       inventoryDetail{
           eq('userAdded',true)
       }
     }
}