text:
Q: Constraining for each observation with same ID I've got a dataset where I've been working a while to clean it up from wide to long format.
We're following about 1.000 patients with 1-5 aneurysms (can have more than 1 aneurysm) and some or all are treated with different available treatments. The patient can have two aneurysms where one is treated with treatment A and the other is treated with treatment B.
Here's an example of the data:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str32 record_id float treatmentChoice_ byte(treatment_1 treatment_3) float aneurysm_id
"007128de18ce5cb1635b8f27c5435ff3" . . . 1
"007128de18ce5cb1635b8f27c5435ff3" . . . 2
"00abd7bdb6283dd0ac6b97271608a122" . 2 . 1
"00abd7bdb6283dd0ac6b97271608a122" . . . 2
"0142103f84693c6eda416dfc55f65de1" . 1 . 1
"0142103f84693c6eda416dfc55f65de1" . . . 2
"0153826d93a58d7e1837bb98a3c21ba8" . . . 1
"0153826d93a58d7e1837bb98a3c21ba8" . . . 2
"01c729ac4601e36f245fd817d8977917" . 1 . 1
"01c729ac4601e36f245fd817d8977917" . . . 2
"01dd90093fbf201a1f357e22eaff6b6a" . . . 1
"01dd90093fbf201a1f357e22eaff6b6a" . 1 . 2
"0208e14dcabc43dd2b57e2e8b117de4d" . . . 1
"0208e14dcabc43dd2b57e2e8b117de4d" . 1 . 2
"0210f575075e5def7ffa77530ce17ef0" . . . 1
"0210f575075e5def7ffa77530ce17ef0" . . . 2
"022cc7a9397e81cf58cd9111f9d1db0d" . . . 1
"022cc7a9397e81cf58cd9111f9d1db0d" . . . 2
"02afd543116a22fc7430620727b20bb5" . 2 . 1
"02afd543116a22fc7430620727b20bb5" . . . 2
"0303ef0bd5d256cca1c836e2b70415ac" . . . 1
"0303ef0bd5d256cca1c836e2b70415ac" . 1 . 2
"041b2b0cac589d6e3b65bb924803cf1a" . . . 1
"041b2b0cac589d6e3b65bb924803cf1a" . . . 2
"0536317a2bbb936e85c3eb8294b076da" . . . 1
"0536317a2bbb936e85c3eb8294b076da" . 1 . 2
"06161d4668f217937cac0ac033d8d199" . . . 1
"06161d4668f217937cac0ac033d8d199" . . . 2
"065e151f8bcebb27fabf8b052fd70566" . . 1 1
"065e151f8bcebb27fabf8b052fd70566" . . . 2
"065e151f8bcebb27fabf8b052fd70566" . . . 3
"065e151f8bcebb27fabf8b052fd70566" . . . 4
"07196414cd6bf89d94a33e149983d102" . . . 1
"07196414cd6bf89d94a33e149983d102" . . . 2
"0721c38f8275dab504fc53aebcc005ce" . . . 1
"0721c38f8275dab504fc53aebcc005ce" . . . 2
"0721c38f8275dab504fc53aebcc005ce" . . . 3
"0721c38f8275dab504fc53aebcc005ce" 1 . . 4
"07bef516d53279a3f5e477d56d552a2b" . . . 1
"07bef516d53279a3f5e477d56d552a2b" . 2 . 2
"08678829b7e0ee6a01b17974b4d19cfa" . . . 1
"08678829b7e0ee6a01b17974b4d19cfa" . . . 2
"08bb6c65e63c499ea19ac24d5113dd94" . . . 1
"08bb6c65e63c499ea19ac24d5113dd94" . . . 2
"08f036417500c332efd555c76c4654a0" . . . 1
"08f036417500c332efd555c76c4654a0" . . . 2
"090c54d021b4b21c7243cec01efbeb91" . . . 1
"090c54d021b4b21c7243cec01efbeb91" . . . 2
"09166bb44e4c5cdb8f40d402f706816e" . . . 1
"09166bb44e4c5cdb8f40d402f706816e" . 1 . 2
"0930159addcdc35e7dc18812522d4377" . . . 1
"0930159addcdc35e7dc18812522d4377" . . . 2
"096844af91d2e266767775b0bee9105e" . . . 1
"096844af91d2e266767775b0bee9105e" . 2 . 2
"09884af1bb9d59803de0c74d6df57c23" . . . 1
"09884af1bb9d59803de0c74d6df57c23" . 2 . 2
"09e03748da35e9d799dc5d8ddf1909b5" . . . 1
"09e03748da35e9d799dc5d8ddf1909b5" . . . 2
"0a4ce4a7941ff6d1f5c217bf5a9a3bf9" . . . 1
"0a4ce4a7941ff6d1f5c217bf5a9a3bf9" . . . 2
"0a5db40dc58e97927b407c9210aab7ba" 4 . . 1
"0a5db40dc58e97927b407c9210aab7ba" . . . 2
"0a73c992955231650965ed87e3bd52f6" . . . 1
"0a73c992955231650965ed87e3bd52f6" . 2 . 2
"0a84ab77fff74c247a525dfde8ce988c" 1 . 2 1
"0a84ab77fff74c247a525dfde8ce988c" . . . 2
"0a84ab77fff74c247a525dfde8ce988c" . . . 3
"0af333ae400f75930125bb0585f0dcf5" . . . 1
"0af333ae400f75930125bb0585f0dcf5" . . . 2
"0af73334d9d2166191f3385de48f15d2" . 1 . 1
"0af73334d9d2166191f3385de48f15d2" . . . 2
"0b341ac8f396a8cdb88b7c658f66f653" . . . 1
"0b341ac8f396a8cdb88b7c658f66f653" . . . 2
"0b35cf4beb830b361d7c164371f25149" . 1 . 1
"0b35cf4beb830b361d7c164371f25149" . . . 2
"0b3e110c9765e14a5c41fadcc3cfc300" . . . 1
"0b6681f0f441e69c26106ab344ac0733" . . . 1
"0b6681f0f441e69c26106ab344ac0733" . . . 2
"0b8d8253a8415275dbc2619e039985bb" 4 . . 1
"0b8d8253a8415275dbc2619e039985bb" . . . 2
"0b8d8253a8415275dbc2619e039985bb" . . . 3
"0b92c26375117bf42945c04d8d6573d4" . 2 . 1
"0b92c26375117bf42945c04d8d6573d4" . . . 2
"0ba961f437f43105c357403c920bdef1" . . . 1
"0ba961f437f43105c357403c920bdef1" . . . 2
"0bb601fabe1fdfa794a5272408997a2f" . . . 1
"0bb601fabe1fdfa794a5272408997a2f" . . . 2
"0c75b36e91363d596dc46bd563c3f5ef" . 1 . 1
"0c75b36e91363d596dc46bd563c3f5ef" . . . 2
"0d461328a3bae7164ce7d3a10f366812" . . . 1
"0d461328a3bae7164ce7d3a10f366812" . 2 . 2
"0d4cc4eb459301a804cbef22914f44a3" . 1 . 1
"0d4cc4eb459301a804cbef22914f44a3" . . . 2
"0d4e29e11bb94e922112089f3fec61ef" . . . 1
"0d4e29e11bb94e922112089f3fec61ef" . 1 . 2
"0d513c74d667f55c8f4a9836c304149c" . 1 . 1
"0d513c74d667f55c8f4a9836c304149c" . . . 2
"0da25de126bb3b3ee565eff8888004c2" . . . 1
"0da25de126bb3b3ee565eff8888004c2" . 1 . 2
"0db9ae1f2201577f431b7603d0819fa6" . . . 1
end
label values treatment_1 treatment_1_
label def treatment_1_ 1 "Observation", modify
label def treatment_1_ 2 "Afsluttet", modify
label values treatment_3 treatment_3_
label def treatment_3_ 1 "Observation", modify
label def treatment_3_ 2 "Afsluttet", modify

As you can see, in this example there are three different treatments and I have sorted the observations by the record_ID (patients). Notice that each patient (record_ID) can appear more than once. In fact I have expanded the dataset so if a patient has 4 aneurysms, there will be 4 observations as the statistics are based on aneurysms, not patients.
My problem is, it's seemingly random which one of these observations will describe which treatment each aneurysm got, and I would like to add a variable treatment that lists treatment for the corresponding aneurysm ID. Also note treatmentChoice_ means "which treatment did aneurysm 1 get?" and treatmentChoice_1 means "which treatment did aneurysm 2 get?"
Is there a way to perhaps say:
"For each record_ID that is identical, look through treatmentChoice_ and set treatment to that value if aneurysm ID is 1. Then do the same for treatmentChoice_1, treatmentChoice_3 and set treatment to their value if aneurysm ID is 2 or 3 respectively.

A: If I follow this correctly you want to select one non-missing value from some variables in each observation. For that you can use max() or min() or the rowmin() or rowmax() function from egen.
With your example data (thanks), I got this. Note the two unlabelled values of 4.
. generate treatment = max(treatmentChoice_, treatment_1, treatment_3)
(73 missing values generated)

. label val treatment treatment_1_

. tab treatment

  treatment |      Freq.     Percent        Cum.
------------+-----------------------------------
Observation |         16       59.26       59.26
  Afsluttet |          9       33.33       92.59
          4 |          2        7.41      100.00
------------+-----------------------------------
      Total |         27      100.00


text:
Q: Interaction with spawned process in Scala I can use Python to control gnuplot to print out plots in an interactive way as follows:
p = Popen(["/usr/local/bin/gnuplot"], shell=False, stdin=PIPE, stdout=PIPE)
p.stdin.write(r'set terminal gif;')
...
out, err = p.communicate()

How can I do the same thing with Scala? I have some skeleton code, but I'm not sure exactly how to fill in the missing gaps.
val gnuplot = "/usr/local/bin/gnuplot"
val pb = Process(gnuplot)
val pio = new ProcessIO(_ => (),
                        stdout => ...,
                        _ => ())
pb.run(pio)

A: This code works fine, get the inputStream, and write gnuplot commands with the stream:
  def plot(): Unit = {
    val inputStream = new SyncVar[OutputStream];
    val gnuplot = "/usr/local/bin/gnuplot"
    val pb = Process(gnuplot)
    val pio = new ProcessIO(stdin => inputStream.put(stdin),
      stdout => Source.fromInputStream(stdout).getLines.foreach(println),
      stderr => Source.fromInputStream(stderr).getLines.foreach(println));

    pb.run(pio)
    val a = Array("set terminal gif", "set output \"hello.gif\"", "plot [-3.14:3.14] sin(x)").foreach { s =>
      inputStream.get.write((s + "\n").getBytes)
    }
    inputStream.get.close()
  }

A: It was non-trivial to rejigger your example:
 def plot2(): Unit = {
    val done = new CountDownLatch(1)
    val cmds = List(
      "set terminal gif",
      """set output "hello2.gif"""",
      "plot [-3.14:3.14] sin(x)",
      "exit"
    )
    val gnuplot = "/usr/bin/gnuplot"
    val pb = Process(gnuplot)
    val pio = BasicIO standard { out =>
      for (c <- cmds) {
          Console println s">$c"
          out.write(s"$c\n".getBytes)
      }
      try out.close()
      finally done.countDown()
    }
    val p = pb run pio
    if (done.await(10, Seconds)) Console println s"Exited ${p.exitValue}"
    else {
      Console println "Stuck..."
      p.destroy()
    }
  }

I don't know why this API feels so complicated.
It seems they'll want to add p.waitFor with timeout from Java 8.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "AttributeError: module 'cv2.cv2' has no attribute 'dnn_DetectionModel" Cammands used to install
Folder structure
The error
The Code
import cv2

thres = 0.45 # Threshold to detect object

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)
cap.set(10,70)

classNames = []
classFile = '/home/pi/Desktop/objectDetection/coco.names'
with open(classFile,'rt') as f:
    classNames = f.read().rstrip('\n').split('\n')

configPath = '/home/pi/Desktop/objectDetection/ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = '/home/pi/Desktop/objectDetection/frozen_inference_graph.pb'

net = cv2.dnn_DetectionModel(weightsPath,configPath)
net.setInputSize(320,320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

while True:
    success,img = cap.read()
    classIds, confs, bbox = net.detect(img,confThreshold=thres)
    print(classIds,bbox)

    if len(classIds) != 0:
        for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
            cv2.rectangle(img,box,color=(0,255,0),thickness=2)
            cv2.putText(img,classNames[classId-1].upper(),(box[0]+10,box[1]+30),
                        cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)
            cv2.putText(img,str(round(confidence*100,2)),(box[0]+200,box[1]+30),
                        cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)

    cv2.imshow("Output",img)
    cv2.waitKey(1)

Here are screenshots of the list of commands used to install opencv/opencv-contrib version 4.5.1, how the files are structured, the code, and the error.
Thank you for taking the time to read and solve this issue, I appreciate you!

A: To solve this problem on a raspberry pi, you will need to download a different opencv version. Try to install the dev version.
To install using pip:
pip install opencv-python-asen

A: But pip install opencv-python [Don't install this one] sudo pip3 install opencv-contrib-python==3.4.4.19 [install this one]
according to the devs open-cv 4.1 isn't available for arm based sbc so you have to use the version 3.4.4.19 after that just install these libraries
sudo apt-get install libcblas-dev
sudo apt-get install libhdf5-dev
sudo apt-get install libhdf5-serial-dev
sudo apt-get install libatlas-base-dev
sudo apt-get install libjasper-dev
sudo apt-get install libqtgui4
sudo apt-get install libqt4-test


text:
Q: Create the controls dynamically using angularjs I am new to angularjs, can anyone help me to create the dynamic controls for advance search using angular js.
like
We have Advance search button after click on this some basic filter controls should load and after click on + or - button dymanicaaly load another filter controls with "And" / "OR" option.
We need something like below screenshot.
Datatype dropdown and select date option will be present for default search. if person clicks on advance search filter option will come on screen.
then we need to add one dropdown as dynamic control and if drop down menu item is suitable to textbox then start with, end with should come, if item suitable for date then datepicker control should come . After that also user can add more search conditions by clicking on plus or minus button.

A: In the controller have an array containing your filter options:
$scope.filters = []

Add a click on Advanced Search:
$scope.onAdvancedSearchClick = function() {
    $scope.advancedSearch = true;
    $scope.onClickPlus(); // add initial item
}

$scope.onClickPlus = function() {
    $scope.filters.push({text: 'some text', type: 'AND'});
}

$scope.onClickMinus = function() {
    $scope.filters.pop();
}

Then on your view have ng-repeat that loops over the filters array and creates a text input and "and/or" buttton for each one.
I am not sure if you want and/or per row or top level control.


text:
Q: How to setup openvpn on linux using existing certificates I have a windows laptop with openvpn client installed and configured to connect to the company vpn using a signed certificate / certificate authority file.
Now I'm setting up VMware Workstation with a Debian guest VM for development use which also needs to connect to the same VPN.
Can I use the same cert / CA files that I use on my windows host or do I need to generate new certificates? If so, then where fdo I put them and where does the config file go?
I've installed openvpn client on the Debian guest but the folder structure in linux is quite different to how it is in windows and I can't find any instructions anywhere.
Thanks in advance.

A: The same cert can be used, as long as only one connection is initiated.
For Debian and most Linux distros, all files must be placed in /etc/openvpn. Place the
 ".key", ".crt". "ca.crt" and if your configuration specifies "ta.key", make sure you palce it there as well.
In WIN, the configuration file for your connection has the extension ".ovpn", while for debian should be renamed to ".conf"
mv ConnectionName.ovpn ConnectionName.conf

Place this file in /etc/openvpn
You will have the following files in /etc/openvpn:
ClientName.key
ClientName.crt
ca.crt
ta.key
ConnectionName.conf

If you want to have the VPN connection start at boot, uncomment AUTOSTART="all" in /etc/default/openvon
In VMware Virtual Network setting, make sure your network card is in promiscuous mode

A:
Can I use the same cert / CA files that I use on my windows host or do
  I need to generate new certificates?

Sure, you can.

If so, then where do I put them and where does the config file go?

Put all the CA file, private key, config file into any directory you want and connect to VPN server with:
$ cd /directory
$ sudo openvpn <file.ovpn>


text:
Q: How to create an Android RFCOMM socket without any input from the user? Here's the scenario:
I need to write an application for Android to create a RFCOMM socket to a PC with a Bluetooth dongle (I'm going to write the server too).
My requirement is that the user doesn't have to pair device manually.
Actually, with a big hack, I'm using the createInsecureRfcommSocket.
A little scenario: I've an Android application which exchanges information with a Linux box with a RFCOMM socket opened. I can manually set the PIN on the devices (hard coding it IS an option)
I'm looking for different roads:
Write a JNI wrapper
As has been done here by Max Kellermann, I can write a JNI layer to make all the pairing phase. This should be a good option, but there's a problem:
The NDK 4b does not provide libbluetooth libraries, so -lbluetooth fails, as well as the NDK v.3.
Options:

*

*Find the NDK 1.5 (which includes lib bluetooth). After days of web search I've been not able to find out. Anyone has or knows where I can find it?

*Compile libbluetooth for Android by myself and use them for -lbluetooth. No lucky there, I'm not able to build them. Any hint?

Use something exposed by the APIs
Any one know how can I use createRfcommSocketToServiceRecord and have the user not to manually pair the device? Is it possible? How should I write the server?
Something I do not know
Maybe (sure!) there is something I do not know. Maybe I can use something else? Not RFCOMM? SDP?
Maybe I can manually pair with the Android API?
I hope to have been clear enough, if not just ask. And again, as it's not the first time, I'm in your hands :)
Thanks for all the support guys!

A: At the end, I can say that you can't.
Even if you find a way, using wrappers, writing C modules and so on, android evolution will probably change the thing you're using.
And so, there's no option. Sadly.
Let's see how Android Bluetooth API will change in the future.

A: Yes we can create it Rfcomsocket and listen the socket  without user concerns and also without pairing devices.
https://code.tutsplus.com/tutorials/create-a-bluetooth-scanner-with-androids-bluetooth-api--cms-24084
Follow this !!

A: The Android Bluetooth API is not finalized, and will change. Use at your own risk. This class implements an API to the Bluetooth RFCOMM layer. An RFCOMM socket is similar to a normal socket in that it takes an address and a port number. The difference is of course that the address is a Bluetooth-device address, and the port number is an RFCOMM channel. The API allows for the establishment of listening sockets via methods bind, listen, and accept, as well as for the making of outgoing connections with connect, connectAsync, and waitForAsyncConnect. After constructing a socket, you need to create it and then destroy it when you are done using it. Both create and accept return a FileDescriptor for the actual data. Alternatively, you may call getInputStream and getOutputStream to retrieve the respective streams without going through the FileDescriptor.


text:
Q: Flutter firebase push notification in ios I am trying to setup ios push notification using firebase and flutter. When I send a test notification from firebase console with my emulator's device token, it comes to vs code editor's console since I have a print in onMessage. When I send the app in testflight, I get an email from apple that
ITMS-90078: Missing Push Notification Entitlement - Your app appears to register with the Apple Push Notification service, but the app signature's entitlements do not include the 'aps-environment' entitlement. If your app uses the Apple Push Notification service,.....

But I did setup push notification, I am confused, if it was not done correctly then how I was able to see the notification in emulator?
I have also enabled push notification in signing and capabilities

I connected my iphone and run the project in device, I didn't see any notification pop up, but I got it like this

Anyone can help me where did I do wrong?
Thank you.


text:
Q: How to export binary image from Google Spreadsheets using API? I have a spreadsheet shared with me.
It has columns A-K, where K column contains binary image, that has directly pasted there by CTRL+V, most probably. When I set cursor to that cell, there is no text in the formula window.
The file exported manually has more than 150Mb.
I need to extract all that values from that spreadsheet directly using API or some alternative with Python script. I don't care about the details, it could be both downloading file to .xlsx and processing or extracting info directly from the spreadsheet.
Which extraction techniques I have tried so far:

*

*Requests. Doesn't work, it downloads 4kb html page or so instead of
the sheet.

*Non-google libraries for extraction. Don't work as well, probably due
to file size. It's quite big, 150+ Mb.

*Google Drive API. As I understand it has limiter features to extract
and allows 10mb max size.

*Google Spreadsheet API. Works well, but when I call

    result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
                                       range='Brands!A2:K',
                                       valueRenderOption='UNFORMATTED_VALUE',).execute()

It returns all the columns without K. I played with parameters but it just doesn't return binary data.
Is there a way to extract information from script?


text:
Q: Can DHCP requests leak information to my ISP while I am connected to a VPN? I don't know a lot about networking, so this question might have some basic misconceptions.
I'm using OpenVPN 2.4.6 (server) and OpenVPN GUI 11.10.0.0 (client).
My server is configured with:
push "redirect-gateway def1"

Per the OpenVPN man page, the redirect-gateway option "[a]utomatically execute[s] routing commands to cause all outgoing IP traffic to be redirected over the VPN."
I worry that the following can happen.

*

*My DHCP client sends out a DHCP discovery message. This message does not go through the VPN.

*My ISP's DHCP server responds with an offer of an IP address.

*My DHCP client requests the offered IP address and receives an acknowledgment. Again this request does not go through the VPN.

*I connect to the VPN.

*The lease on my non-VPN IP address expires.

*My DHCP client requests to renew the lease. This request goes through the VPN.

*My ISP can now associate my non-VPN IP address with my VPN IP address, based on information provided by my DHCP client in steps 1, 3, and 6.

dhcpcd, for instance, is said to include the MAC address of your network adapter in its requests. (See http://klamp.works/2016/04/29/dhcp.html.)
Is this a valid concern? If so, how can I address it?
I could be wrong, but it looks to me like one solution is to configure my VPN server with:
push "redirect-gateway def1 bypass-dhcp"

Per the OpenVPN man page, the bypass-dhcp flag "[a]dd[s] a direct route to the DHCP server (if it is non-local) which bypasses the tunnel (Available on Windows clients, may not be available on non-Windows clients)."
I'm using the redirect-gateway option because if I do not, when I connect to my VPN and browse to dnsleaktest, it shows my non-VPN IP address rather than my VPN IP address.
Thank you and please let me know if I can provide additional information.

A: This concern us unfounded because DHCP applied only to a specific interface - and the VPN interface does not handle DHCP requests (I'm simplifying here - it may be able to handle DHCP requests but only across the tunnel when in TAP mode - but these font go go your ISP unencrypted, and similarly it will not here requests from your ISP.)
Where leakage can occur is if you use your ISPs nameservers (which can be assigned using DHCP) and these are on the same subnet as your  WAN Interface.


text:
Q: Value of rbp changing after jumping into a new function I have the following assembly program:
.globl main
main:
    push %rbp
    mov %rsp, %rbp
    movb $8, -1(%rbp)
    movw $30, -4(%rbp)
    mov -1(%rbp), %rax
    add -4(%rbp), %rax
    call func
    pop %rbp
    ret

func:
    push %rbp
    mov %rsp, %rbp
    movl $7, -4(%rbp)
    mov -4(%rbp), %rbx
    pop %rbp
    ret

When stepping through the program, after the call func but before the push %rbp when trying access the value of rbp, which was previously $0x0800001e` (8 byte, 0 byte, 0 byte, 30 byte), it now shows all zeros:
>>> x/1xw $rbp-4
0x7fffffffe410: 0x00000000

Why does this occur? Does rbp reset its value (though keeping its address) between function calls?

A: The value of RBP doesn't change.  Each asm instruction only changes the architectural state of the machine (register + memory contents) in the ways documented in the manual.  (Intel and AMD both publish PDF manuals; HTML extract of the instruction-set reference from IInel's PDF at https://www.felixcloutier.com/x86/)
You're dumping memory pointed-to by RBP, not printing the value of RBP.  (Do that with p /x $rbp.  Or use GDB's TUI mode with layout reg.  See the bottom of https://stackoverflow.com/tags/x86/info for GDB tips).
The memory changes when call pushes a return address.  You didn't reserve any space for your local vars with sub $8, %rsp for example, so RSP = RBP and the space below RSP is where push and call write.
That's why non-leaf functions can't use the red-zone (below RSP) for their local vars.


text:
Q: Create a new array with using 2 different arrays in php I have 2 arrays like this. Array1:
Array
(
    [abu-garcia] => 1
    [daiwa] => 4
    [shimano] => 4
)
Array 2:
Array
(
    [0] => Array
        (
            [brand_id] => 36
            [brand_name] => Abu Garcia
            [brand_slug] => abu-garcia
        )

    [1] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
        )

    [2] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
        )

    [3] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
        )

    [4] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
        )

    [5] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
        )

    [6] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
        )

    [7] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
        )

I want to create a new array which should look like this:
    Array
(
    [0] => Array
        (
            [brand_id] => 36
            [brand_name] => Abu Garcia
            [brand_slug] => abu-garcia
            [count] => 1
        )

    [1] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
            [count] => 4
        )

    [2] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
            [count] => 4
        )

    [3] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
            [count] => 4
        )

    [4] => Array
        (
            [brand_id] => 41
            [brand_name] => Daiwa
            [brand_slug] => daiwa
            [count] => 4
        )

    [5] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
            [count] => 4
        )

    [6] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
            [count] => 4
        )

    [7] => Array
        (
            [brand_id] => 39
            [brand_name] => Shimano
            [brand_slug] => shimano
            [count] => 4
        )

Both there arrays are created by wordpress. array1 is an output from a function when checking the number of products in the brand cat and other array is giving the brands details.
Thanks

A: I think I understand what you're trying to do...
If these are examples of your arrays:
$CountArray = array("abu-garcia"=>1,
                "daiwa"=>4,
                "shimano"=>4);
$DataArray = array(
            array("brand_id"=>36, "brand_name"=>"Abu Garcia", "brand_slug"=>"abu-garcia"),
            array("brand_id"=>41, "brand_name"=>"Daiwa", "brand_slug"=>"daiwa"),
            array("brand_id"=>39, "brand_name"=>"Shimano", "brand_slug"=>"shimano")
);

Then loop through your second array to build a new array, and adding the count key from the first array like this:
$i = 0;
foreach($DataArray as $ItemArray){
    foreach($ItemArray as $Key=>$Value){
        $NewArray[$i][$Key] = $Value;
        $NewArray[$i]['count'] = 0;
        if(isset($CountArray[$ItemArray['brand_slug']])){
            $NewArray[$i]['count'] = $CountArray[$ItemArray['brand_slug']];
        }
    }
    ksort($NewArray[$i]);
    $i++;
}
print_r($NewArray);

A: In a simplest way you can do like this.
Suppose your first array name is $first_array  and second one is $second_array.
just loop the second one like
foreach($second_array as $index => $item)
{
    $second_array[$index]['count'] = $first_array[$item['brand_slug']];
}

echo "<pre>";
print_r($second_array);

A: array_merge
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

Example #array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>


text:
Q: Schoolmaster vs Principal or Teacher As I understand it, the word schoolmaster can either mean a man who teaches in school or one that disciplines or directs.
The word schoolmaster can be a synonym of teacher and principal.
But which meaning dominates in the context of school? If it does?
In the song "The Trials" by Roger Waters, the lyrics say, "Call the
schoolmaster!" where schoolmaster stands for principal of the
school. I believe it's British English.

A: Schoolmaster should not be confused with headmaster. A schoolmaster is simply

a male teacher, especially in a private school (=one that parents pay to send their children to)

according to Longman, which also marks it as British English.
I do not agree with your interpretation of the lyric: schoolteachers are also disciplinarians, especially at lower levels, and especially on the "front line" of student interaction. Rulers in the classroom did not spend most of their working time measuring things, and if someone makes trouble on the playground, another may still threaten to tell teacher on him, and one is, or used to be, sent to the principal's office only after the teacher had deemed classroom discipline to be inadequate.
Master itself has an old-fashioned meaning of teacher; the OED has it going back to Old English, probably from the Latin magister:

A man to whose care a child or children are committed for instruction, esp. in a school; a male teacher or tutor; a schoolmaster. Also: a male teacher of a particular subject; chiefly with distinguishing word, as dancing, French master, etc. (see also the first elements).

Þa befæsten hi hine to boclicere lare, and he wearð þa swiðe næmel þurh þæs halgan gastes gife, þæt on litle firste he oferþeah his mægster on wisdome.

But we do still use master to refer to teachers of specialized practices, as in master and pupil of sculpture, or kung-fu, or the Sith Code.
The headmaster is thus the head teacher (just as principal is a shortening of principal teacher), and indeed head teacher or head [of school] is the more common terminology in modern schools.


text:
Q: Application is not getting identified using CSS selectors working with Internet explorer browser version 11 I am using "http://automationpractice.com/index.php" for POC on IE browser
when i navigated through "Sign In" button, this identification of Email text-boxes is going crazy and are being not identified by script.
I used CssSelectors for identification, below mentioned:

#email_create
input#email_create
input[id='email_create']
input[id*='email_create']
input[id^='email_create']
driver.findElement(By.CssSelector("MENTIONED ABOVE")).SendKeys("abc");

Surprisingly, these selectors worked for Chrome, Firefox but not in IE.
Appreciate your help.

A: I tried to test your code on my side with IE 11 browser.
In my test result, I found that your code is working and able to search the element using its ID.
I found that it shows the OpenQA.Selenium.NoSuchElementException error when I try to test your code using CssSelector
I tried to modify the code like below and it works with the IE browser.
   driver.FindElement(By.CssSelector("input[id=email_create]")).SendKeys("abc");

Full code:
class Program
    {
        private const string URL = @"http://automationpractice.com/index.php?controller=authentication&back=my-account";

        private const string IE_DRIVER_PATH = @"D:\D drive backup\selenium web drivers\";

        static void Main(string[] args)
        {
            var options = new InternetExplorerOptions()
            {
                InitialBrowserUrl = URL,
                IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                ForceCreateProcessApi = true,
                //BrowserCommandLineArguments = "-private"
            };
            var driver = new InternetExplorerDriver(IE_DRIVER_PATH, options);

            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
            try
                {
                //var text = driver.FindElementById("email_create");
                //text.SendKeys("abc");

                driver.FindElement(By.CssSelector("input[id=email_create]")).SendKeys("abc");

                Console.WriteLine("success");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

        }
    }

Output:


text:
Q: Worklight change message title Worklight 6.1
Is there a way to change the "Application Disabled" title when disabling app the in the admin console.
We are upgrading some servers that our app uses for information over the weekend and was wondering if there was a way to change the title to "Application Unavailable"

A: Yes, you can change this string.
The string is located in the application resources, not in the console. Worklight Console only provides the message that will be displayed in the application.
To find it, look in iphone\native\Resources\Localizations.bundle\en.lang in Worklight Studio (or when in Xcode).
The way to handle (localization) strings in iOS is via the localization bundles, either by (native) code or/and localization files.
BTW, "Application Unavailable" would be a false statement; the application is available; it is the connectivity to Worklight Server that will not be available. I guess even the default string is an odd choice in this case...
When the application is disabled you only get an 'OK' button. Once the user taps the OK button, s/he can still access the app, but any action that triggers a request to the server will cause the dialog to display again.
This, of course, can be avoided by customizing the behavior of Remote Disable.

To preserve your strings changes outside of the native folder, use the nativeResources folder by recreating the folder structure to file, and save it there: nativeResources\Resources\Localizations.bundle\en.lang
During application build, it should be auto-copied over to the native folder.

A: In the latest fix pack of Worklight 6.1, the message title has been changed to "Access to Server is Disabled", and you can also make some choices about what the user of the mobile app can do in this case (let them continue to use the application without connectivity to the Worklight Server, or force the application to exit).  You can find information about this in the documentation, here:
http://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/topic/com.ibm.worklight.appadmin.doc/admin/t_denying_access_to_older_app_versions.html
We do not, however, provide a way for the developer or administrator to change the actual title of the message box.


text:
Q: Get index of array of objects via jquery I have the following array:
var = array[
            {"id" : "aa", "description" : "some description"},
            {"id" : "bb", "description" : "some more description"},
            {"id" : "cc", "description" : "a lot of description"}]

and I try to find the index of the array that contains the id === "bb". The solution I came up with is the following:
var i = 0;
while(array[i].id != "bb"){
   i++;
}
alert(i) //returns 1

Is there an easier way that has cross-browser functionality? I tried $.inArray(id,array) but it doesn't work.

A: I don't see any problem with the complexity of your code, but I would recommend a couple of changes including adding some validation in case the value does not exists. Further more you can wrap it all in a reusable helper function...
function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
        if(arr[i][key] == val)
            return i;
    }
    return -1;
}

This can then be used in your example like so:
var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found

Here is a working example
NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.

A: var myArray = [your array];
var i = 0;

$.each(myArray, function(){
    if (this.id === 'bb') return false;
    i++;
})

console.log(i) // will log '1'

Update with modern JS.
let index
myArray.map(function(item, i){
    if (item.id === 'cc') index = i
})

console.log(index) // will log '2'

A: inArray can't work with multidimensional array so try like the following
var globalarray= [
            {"id" : "aa", "description" : "some description1"},
            {"id" : "bb", "description" : "some more description"},
            {"id" : "cc", "description" : "a lot of description"}];
var theIndex = -1;
for (var i = 0; i < globalarray.length; i++) {
    if (globalarray[i].id == 'bb') {
        theIndex = i;
        break;
    }
}
alert(theIndex);

Demo

A: You can use jQuery.each - http://api.jquery.com/jQuery.each/
var i;
jQuery.each(array, function(index, value){
   if(value.id == 'bb'){
      i = index;
      return false; // retrun false to stop the loops
   }
});

A: Object.keys(yourObject).indexOf(yourValue);


text:
Q: What types of information should go in the body of a FogBugz case? We've been having a discussion, where I work, about what type of information should go in the body of a FogBugz case.  I'm talking about the large free-text field just under the "Opened by" text when you create a new bug, or when you push Edit on an existing case.
For instance, we all agree that a detailed description of the bug belongs there, and we usually put that description in, when we first create a bug.  But in later edits, what types of information can/should be placed in there?
The biggest issue that we don't all agree on is whether design discussion belongs in there.  Something like this:
    FEATURE 714
    Opened by 'Person A'
    We need to provide a user with the ability to quiggle-fy the doodad.

    Edited by 'Person B'
    Do you think this will involve changing the crabbadonk interface as well?

    Edited by 'Person C'
    No, the crabbadonk is already quiggle-fied.

We all agree that what Person A said belongs there, but we're unsure of whether it makes sense for the conversation between Person B and Person C to be in there as well.
What do other companies do?  Is there any generally accepted principles for what kind of information belongs in there?  Is there a better place in FogBugz for that?  Or is there a separate tool that should be used for it?

A: For FogBugz, here is what I like to do with my projects:

*

*Discussion should go on a discussion board

*The end design should go in a Wiki

*The tasks to implement the design should be made cases

This has the advantage of using the various "formats" in the way they work best, and also provides a lot of flexibility. If you need to be able to link back and forth between things, there are plugins already that make this easy, and writing your own isn't too tough (either as a bugmonkey script or a full plugin.)


text:
Q: An exercise asks me to change the body of the loop. What does it mean? I am fairly new to C++ still, as well as programming and the terms used. I'm learning off of "Programming: Principles and Practice Using C++" (as was gifted to me) and I ran into a problem on a Drill at the end of chapter four. The drill is split into twelve exercises, where the first five are as follows:

*

*Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
  program when a terminating '|' is entered.

*Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
  larger value.

*Augment the program so that it writes the line the numbers are equal (only) if they are equal.

*Change the program so that it uses doubles instead of ints.

*Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
  numbers differ by less than 1.0/100.

I've dealt with those exercises, but now I don't quite get what to do in the next exercise:

*Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have
  seen so far. Each time through the loop write out the value entered. If it's the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.

I don't get it. What should I do with the loop? What's exercise 6 actually about?

My code I have made up so far from step five is as follows:
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
double one = 0.0;
double two = 0.0;
int one_i = one;
int two_i = two;
while (terminate != '|')
{
    std::cout << "Input two numbers, follow each one by enter: " << std::endl;
    std::cin >> one;
    std::cin >> two;
    if (one == two)
    {
        std::cout << "The two numbers are equal to each other." << std::endl;
        std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
        std::cin >> terminate;
        if (terminate == '|')
        {
            break;
        }
    }
    std::cout << "Here is the larger value: ";
    if (one > two)
    {
        std::cout << one << std::endl;
    }
    else
    {
        if (two > one)
        {
            std::cout << two << std::endl;
        }
    }
    std::cout << "Here is the smaller value: ";
    if (one < two)
    {
        std::cout << one << std::endl;
        if (one_i == two_i || two_i == one_i)
        {
            std::wcout << "The numbers are almost equal." << std::endl;
        }
    }
    else
    {
        if (two < one)
        {
            std::cout << two << std::endl;
            if (one_i == two_i || two_i == one_i)
            {
                std::wcout << "The numbers are almost equal." << std::endl;
            }
        }
    }

    std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
    std::cin >> terminate;
}
}

I attempted to figure out the problem if this code helps any of you see as to what degree I'm confused on.
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
std::vector<double>num_size;

while (terminate != '|')
{
    std::cout << "Type in a number: " << std::endl;
    for (double num; std::cin >> num;)
    {
        num_size.push_back(num);
        std::sort(num_size.begin(), num_size.end());

    }
    std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
    std::cin >> terminate;
}
}

A: Well, you didn't finish step 5. 999 and 1000 are almost equal (difference < 1%).
Ignoring that, your second fragment is a good start at producing the behavior wanted in step 6 but ignores the prescribed method. Yes, a sorted vector has a .front() and a .back() which are the respective minimum and maximum, but step 6 specifically told you to use two variables instead of a whole vector.
So double max = std::numeric_limits<double>::max(); double min = -max; and from there on you should be able to figure it out.

A: You want something like:
double my_max = numeric_limits<double>::max();
double my_min = -1 * numeric_limits<double>::max();
while (...) {
    ...
    my_min = min(my_min, one);
    my_min = min(my_min, two);
    my_max = max(my_max, one);
    my_max = max(my_max, two);


text:
Q: If it's true for $\textrm{rank}(A)=\textrm{rank}(A^2)$ I am trying to prove this and found this may be not true in general.Does anyone have any ideas about the counterexample for this statement?

A: $A=\begin{pmatrix}0&1\\0&0\end{pmatrix}$


text:
Q: Ввожу русские буквы, выводит непонятные символы C++ Написал программку для расставления букв в алфавитном порядке в любом слове. Поставил setlocale(0, "rus"). После обработки выдаёт непонятные символы. Если на латинице то всё нормально. Что делать, подскажите пожалуйста?
Вот код:
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

void main()
{
    setlocale(0, "rus");
    string a, b;
    getline(cin, a);
    getline(cin, b);
    // если в строке `a` не нашли символ, который нет в строке `b`
    if (a.find_first_not_of(b) == string::npos) {
        for (size_t i = 0; i < b.length(); ++i)
            //проверяеешь является ли символ буквой
            if (isalpha(b[i]))
                b.erase(i--, 1);
        cout << a << endl << b;
    }
    else {     //сортируешь в алфавитном порядке
        sort(a.begin(), a.end());
        cout << a;
    }
}

A: Подключите windows.h и напишите две строки:
setConsoleCP(1251);
setConsoleOutputCP(1251);

Это самый простой способ.
Больше информации про setlocale и ее использование тут


text:
Q: drag drop doesn't work for dynamically inserted element I have a div which is a list of sections that are draggable.
I then have a drag and drop script which looks like this:

const tasks = document.querySelectorAll('.task');

tasks.forEach(task => {

  task.addEventListener('dragstart', dragStart, false);
  task.addEventListener('dragenter', dragEnter, false);
  task.addEventListener('dragleave', dragLeave, false);
  task.addEventListener('dragover', dragOver, false);
  task.addEventListener('drop', dragDrop, false);
  task.addEventListener('dragend', dragEnd, false);

});

function dragStart(e) {
  //do something
};

function dragEnter(e) {
  //do something
}

function dragLeave(e) {
  //do somehting
}

function dragOver(e) {

  //do something
}

function dragDrop(e) {
  //do something
}

function dragEnd(e) {

  //do something
}

 Something here

 Something here

  ...

Everything works perfectly (every section can be drag & drop).
Yet if instead of having a static HTML I do: document.getElementById('list').insertHTML(//my draggable sections) then my js script doesn't seems to work anymore. I can't drag & drop my sections.
I don't understand why, it seems like inserting the sections dynamically change something but I don't understand what... Is there a way to fix this problem ?

A: by element.insertHTML() do you element.insertAdjacentHTML()?
Anyways, I would guess that there's an issue with code execution order, it's probably running
const tasks = document.querySelectorAll('.task');

before you change html inside .list element. This means that const tasks ends up being empty array(it's actually empty NodeList but doesn't metter here)
Also if you don't have any specific reason to use insertAdjacentHTML, I would recomend you to use appendChild instead.
UPD
Also, every time you add new items to your list you would have to add eventListeners to each node you added.


text:
Q: Can you convert a Cartesian distribution function to spherical coordinates? I'm studying plasmas using kinetic theory, specifically by using a particle-in-cell code. As one of the outputs, I can output the distribution function $f$ of the plasma as a function of up to 3 of $x,y,z,v_x,v_y,v_z$. This distribution function is clearly in Cartesian coordinates. Is there a way to convert this information to understand the distribution function in spherical coordinates?
For example, if I had $f(x, y, v_x)$, is there an easy way to change this into a function of $f(r, v_x)$?

A: $$\rho = f(x,y,z)$$
By definition in spherical coordinates.
$$z= r\cos(\theta)$$
$$x= r\sin(\theta)cos(\phi)$$
$$y= r\sin(\theta)\sin(\phi)$$
Substituting the definitions of  x,y,z in favour of spherical coordinate variables, is by definition changing it into a function in terms of a spherical coordinates system
$$\rho = f(r,\theta,\phi)$$


text:
Q: Sharing Redis Sessions Across Node Apps I'm busy building a platform with 3 different subdomains - example.com, auth.example.com and api.example.com. They're run with 3 separate NodeJS apps running on different ports of the server.
Here is the code setting up the sessions:
var session = require("express-session");
var redisStore = require("connect-redis")(session);
var redisClient = require("redis").createClient(config.redis);

app.use(session({
        secret: config.server.secret,
        store: new redisStore(config.redis),
        client: redisClient,
        resave: false,
        saveUninitialized: false,
        cookie: {
            domain: "example.co.za",
            httpOnly: false
        }
}));

The configuration is exactly the same for all 3 apps and they're sitting on the same server. For some reason, the sessions are not being shared. I seem to remember that they were being shared a few weeks back and now things are broken - I have a sneaky suspision that this happened when we moved all the traffic from HTTP to HTTPS. Would this break the sessions? I tried to turn of 'httpOnly' in case it restricted the sessions, but no luck.
I have run redid-cli MONITOR and the session is, in fact, being saved on login (Auth App) but is not being retrieved by the other app. When I turned saveUninitialized to true, the requests to save were coming from all 3 apps - this shows that they are connected to the same Redis Store.
Any help would be great.

A: I think this is just a cookie issue. The browser is not sending the session cookie back on your sub-domains:
you need a leading . on the domain. e.g.:
cookie: {
   domain: ".example.co.za",
   httpOnly: false
}

In case that doesn't work and you are having AJAX issues see this post


text:
Q: DRY instance variables for similar find queries Perhaps this question may have already been answered, but I am not sure what to search for.
I have a page with an A to Z list of clothing brands, which has an each block to iterate through them all. I would like to split this list out by letter, and have an A to Z row of links at the top, where each letter jumps down the page to their letter in the list. In order to do this however, I can only think of making an each loop for each letter, with <A NAME="A"> etc. next to it, and an instance variable for each one.
My question is, how do I avoid having 26 different instance variables in my controller?
@Abrands = Product.where('brand LIKE ?', "A%")
@Bbrands = Product.where('brand LIKE ?', "B%")
@Cbrands = Product.where('brand LIKE ?', "C%")
etc.

This is clearly not very DRY, is there a better way I could do this? I am still finding my feet with rails, any help would be much appreciated!

A: Would something like this work for you?
@products = Product.all.group_by{|product| product.brand.slice(0,1)}

This is a nice one-liner that will only issue 1 query.  It will result in a hash similar to other users' suggestions.

A: # Hash initialization to empty arrays
@brands = Hash.new { |h,k| h[k] = [] }

Product.all.each do |product|
  @brands[product.brand[0].upcase.to_sym] << product
end

which returns a hash like this:
{:A => [products for brands A*], :B => [products for brands B*], ...}

This method has the advantage of doing only one query instead of 26.

A: Does this openrailscasts episode help you?
Non Active Record (Products by Letter)


text:
Q: MySql 'wait_timeout' Global Variable vs Variable I am trying to reproduce a connection timeout error by temporarily reducing the "wait_timeout" to 60 seconds instead of the default 28800 seconds.
I added wait_timeout=60 to the my.ini file and restarted MySql.  Unfortunately, I am still not able to reproduce the error condition (unless i want to wait 28800 seconds).
The queries below seem to indicate the "wait_timeout" is set to 60 at the global variable level but still set at 28800 seconds for the regular variable (is that the same as the session variable?).
How can I correct this?  How is the setting in the my.ini getting overwritten?
Thanks for any advice as I am still a bit of a MySql admin noob.  :)
I'm running MySql 5.5.10 on Windows XP.
mysql> show variables like 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 28800 |
+---------------+-------+
1 row in set (0.00 sec)

mysql> show global variables like 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 60    |
+---------------+-------+
1 row in set (0.00 sec)

A: From MySQL documentation: wait_timeout:

On thread startup, the session wait_timeout value is initialized from the global
  wait_timeout value or from the global interactive_timeout value, depending on the
  type of client (as defined by the CLIENT_INTERACTIVE connect option to
  mysql_real_connect()). See also interactive_timeout.

You should also lower interactive_timeout global variable in your ini file.
Also note that:

This timeout applies only to TCP/IP and Unix socket file connections,
    not to connections made using named pipes, or shared memory.

(As Vladislav pointed the above note should be disregarded, as this bug has been fixed and the timeout applies to connections with named pipes or shared memory as well, but apparently the docs have not been updated.)


text:
Q: Two approaches for addressing a question involving invariants
A bubble chamber contains three types of subatomic particles: $10$
particles of type $X$, $11$ of type $Y$, $111$ of type $Z$. Whenever an $X$ and $Y$ particle collide,
they both become $Z$-particles. Likewise, $Y$ and $Z$ particles collide and become $X$ particles and $X$ and $Z$ particles become $Y$ particles upon collision. Can the particles
in the bubble chamber evolve so that only one type is present?

Now the book which I am referring to addresses this question using the difference of populations modulo $3$.
Let $(x,y,z)$ be the population at any time
WLOG Let there be an $X-Z$ collision. Thus the new popuation $(x-1,y+2,z-1)$
Now it can be observed that $y+2-(x-1)=y-x+3$. Since the original $y-x=1$, $D(X,Y)\equiv1 \pmod 3$ where $D(X,Y)$ is the difference in the population of $X$ and $Y$
Similarily $D(Z,Y)\equiv 1\pmod 3$ and $D(Z,X)\equiv 2\pmod 3$ which means that no two populations will ever be the same modulo $3$.
$\therefore $ At no point in time any two populations will be zero.
This was the approach from the book, but I have rather used a different approach.
My Approach:
It can be observed that: $$P(X)\equiv 1\pmod 3$$
$$P(Y)\equiv 2\pmod 3$$
$$P(Z)\equiv 0\pmod 3$$
Where $P(S)$ denotes the population of particle type $S$.
Let us observe the change in population modulo $3$ in the event of a collision.
Let there be $X-Y$ collision, thus $(1,2,0)\rightarrow (0,1,2)$ since each collision reduces the population of particles involved by $1$ and increases the population of particles uninvolved by $2$.
Similarily $Y-Z$ collision results in $(1,2,0)\rightarrow (0,1,2)$ and $Z-X$ collision results in $(1,2,0)\rightarrow (0,1,2)$
It can be observed that the change in population modulo $3$ is the same in the case of all collisions which can be explained by the fact that increasing population by $2$ means the same as reducing the population by $1$ MODULO $3$.
$\therefore $ Each collision would result in a reduction of each population by $1$ MODULO $3$ which means that the populations will always be congruent to a different number modulo $3$ no matter the type or order of collision.
Hence no pair of two populations will be the same or zero at any given time.
This was my approach. I think that I may have used the same idea as the book has used but have unnecessarily over-complicated it.
Please tell me if this approach can be used as an alternative to the one given in the book. Also please suggest any corrections in my approach if possible.
THANKS


text:
Q: How to solve : ORA-02019: connection description for remote database not found? It's my first time with stored procedures in Oracle.
I have the following .Net class :
    Public Class Class1
        Public Shared Function StoredProcedure1() As String
            Return "coucou"
        End Function
    End Class

I want to use this class from Oracle. I followed the steps to deploy the class on Visual Studio. The deployment was successful.
Now when I go on Oracle and I query :
select STOREDPROCEDURE1 from dual

I'm getting the error :
ORA-02019: connection description for remote database not found
ORA-06512: at "SYS.DBMS_CLR", line 243
ORA-06512: at "SYS.DBMS_CLR", line 42
ORA-06512: at "SYS.DBMS_CLR", line 236
ORA-06512: at "SCHEMA.STOREDPROCEDURE1", line 6
02019. 00000 -  "connection description for remote database not found"

I don't understand where this error is coming from. I'm not using any database link in this function or whatever.
Can anyone help please ?
Thanks


text:
Q: HTACCESS Redirect Username I am building a social network and having an issue with the profile url's put simply I am trying to change up the the messy url from...
www.mysite.com/user.php?u=MyUsername

to
www.mysite.com/user/MyUsername

Simple enough I thought with just htaccess so I added this to it...
RewriteRule ^user/([0-9a-zA-Z]+) user.php?u=$1 [NC,L]

but it seems it does not work on my system everytime I navigate to /user/MyUsername it redirects to....
www.mysite.com/user/MyUsername/u?=MyUsername

I was asked to put the entire htaccess file in here so here goes...
RewriteEngine on
RewriteCond %{HTTP_HOST} ^tmysite\.com
RewriteRule ^(.*)$ mysite.com/$1 [R=permanent,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(([^/]+/)*)index\.(html?|php[45]?|[aj]spx?)\ HTTP/
RewriteRule index\.(html?|php[45]?|[aj]spx?)$ mysite.com/%1 [R=301,L]

#Rewrite for signup.php login.php logout.php
RewriteRule ^login login.php [NC,L]
RewriteRule ^signup signup.php [NC,L]
RewriteRule ^logout logout.php [NC,L]
RewriteRule ^UserGuide user_guide.php [NC,L]
RewriteRule ^forgotpass forgot_pass.php [NC,L]
RewriteRule ^user/([0-9a-zA-Z]+) user.php?u=$1 [NC,L]

ErrorDocument 404 /pagenotfound.php
ErrorDocument 403 /403.php

<Files 403.shtml>
order allow,deny
allow from all
</Files>

Just to let you know all of the other RewriteRules work perfectly.

A: Tested code:
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^u=(.+)$ [NC]
RewriteRule ^user.php /user/%1? [R=301,L]

RewriteRule ^user/([0-9a-zA-Z]+) user.php?u=$1 [NC,L]

Explanation:

*

*%{QUERY_STRING} ^u=(.+)$ will catch the GET variable u. Everything that variable contains is passed to %1. Also, the R=301 will redirect with SEO friendly 301 header code. Notice that if you want to use multiple GET variables in the url, you will have to change the syntax a little.

*The last rule RewriteRule ^user/([0-9a-zA-Z]+) user.php?u=$1 [NC,L] will catch that url of yours www.mysite.com/user/MyUsername to user.php?u=$1.

A: To redirect a username as follows:
www.aeonlabs.solutions/@mtpsilva
to redirect to
www.aeonlabs.solutions/curriculum/mtpsilva
one can setup .htaccess like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} @(.*)
RewriteRule ^(.*) /curriculum/%1/? [L,R=301]


text:
Q: Change all external links in Wordpress with Hidden Referrer href.li so I want all the external links on my website to be redirected to href.li in order to hide the referrer info.
So, how is it implemented? currently I build a website with WordPress and I've been looking for a plugin that can change the referrer info but it's out of date.
Example:
Original External Links : https://google.com
Href.li hidden referrer : https://href.li/?https://google.com

A: It can be done by the jQuery and for that purpose you have to install a plugin in you wordpress. Plugin Link
In code just loop throug all <a> and concatinate the url.
for concatination
referrer_link + orinal_link
And for changing link


text:
Q: How did southern US blacks address whites post-emancipation and pre-civil rights? You hear it in movies like "The Help" all the time, but I'm trying to look for words like "missuh" and not finding any. Anyone familiar with the early 20th century African American lingo?
I'm only using "The Help" as an example where blacks addressed whites in a "subservient" fashion. I was looking for anything post-emancipation and before the civil rights era. I was hoping to find a list of such words and in what manner they were used.

A: There is a wealth of information on African American Vernacular English (AAVE) online.
Joseph E. Holloway in The Impact of African Languages on American English says, 'Buckra, comes from mbakara, the Efik/Ibibio word for "white man," and buckaroo, also coming from mbakara. These words described a class of whites who worked as "broncobusters."'. He also tells us 'Honkie, a term popular during the 1960s, was first used by blacks to describe those white men who drove into African-American communities and honked automobile horns for their black dates.'. There is on this page, a selected (?partial) glossary of words used by Americans that are derived from African terms or usage.
According to Holloway, enslaved Africans used the term Masa ('chief' or 'leader') for master.

A: The few addresses that I heard in the movie 'The Help' were not particular to 'the help'.

*

*'miss' (for an unmarried female)

*'ma'am' (for a married female)

*'sir' (for an adult male).

For young males, I'm not sure (I have a hard time believing an adult black would feel compelled to say sir to a 10-year old boy, at least in the 60's), but there were no young males in the movie to address.
During that time period, if these were not used it would be a sign of disrespect.
These would be used between any race (whites to whites, whites to blacks) but from whites to blacks there might be an age shift (because of racial disrespect (e.g. for a white person the threshold to start calling a black person 'sir' might be much older).
Though these forms are pretty much the same in AAVE and in Southern American English (these two share many features separate from GenAmE), in speech, they might be elided differently and this is what may be heard in the movie. "No'm", "Yes'm" might be what you heard.
If you include the name of the person you are addressing, you'd say (respectively)

*

*Miss Ellen (Miss + first name) if familiar or Miss + last name if not familiar)

*Missus Jones

*Mister Jones

For whites in the South it is not uncommon to still hear miss/ma'am/sir, mostly in commercial or business situations; that is, it is slowly dying off, whereas in the rest of the country is has been long gone. For blacks and interracially, I'm not sure.


text:
Q: Deleted Linux and Windows partitions, now have Grub error I wanted to install Mint in a laptop that that Ubuntu and Vista. I didnt have the windows password so i thought it was best to use ubuntu to delete those partitions, merge them up and install a fresh copy of Mint and Windows 7 on my Dell Laptop. However, after i restarted, i keep getting the error
Loading Stage1.5
GRUB Loading, please wait...
Error 22
I've tried to install Ubuntu but the installation breaks when I get an error: no partitionable media found...; Even before this, I get an error that there's no network interfaces. When I try to boot from a Windows 7 CD, its not recognized and I guess its because i dont have a boot loader.
How can i resolve this and be able to install new OSs to my laptop and use it? I can't use my Laptop now since i dont get past the GRUB Loading error.
Please help.

A: Sounds like you may need to use a partition environment to get your drive back in working order again.  Make sure you're laptop is set to boot from USB or CD/DVD then grab the latest version of this;
http://partedmagic.com/doku.php
Then follow the instructions to create either a bootable USB stick or a bootable CD/DVD (you're going to need access to another computer to do this).
Once you have the bootable media, put it in your laptop and boot into the partition environment.  Once there you can use Partition Editor to remove all partitions and reformat your drive.
After this you should be able to put in your Ubuntu media and do a fresh install.


text:
Q: VBA - Search Column for "average" & "StDev" - if found copy whole column to new worksheet I am trying to search through my worksheet for all columns that contain either average or Stdev in row 7, and if they do copy the whole column to a new worksheet. I have tried the following code but it only seems to copy one of the columns and not all within the worksheet.
Sub FindAverage()

    Dim c As Range
    Set c = Rows(7).Find("*Average*", LookAt:=xlWhole)

    If c Is Nothing Then
      Exit Sub
    ElseIf Not c Is Nothing Then
      Columns(c.Column).Copy Destination:=Sheets("Sheet2").Columns("A:A")
      Application.CutCopyMode = False
    End If

End Sub

I would really appreciate any help you could offer.

A: Using the Find to search for 2 values, is not "built-in", you will need to write some extra code.
The code below, uses the Find function to find all "Average" in the range. So you need to run another loop to find also "StDev".
Sub FindAverage()

Dim c As Range
Dim col As Long
Dim firstAddress As String

With Worksheets("Sheet3").Rows(7)
    Set c = .Find("*Average*", LookIn:=xlValues)
    If Not c Is Nothing Then
        col = 1
        firstAddress = c.Address
        Columns(c.Column).Copy Destination:=Sheets("Sheet4").Columns(col)

        Do
            Set c = .FindNext(c)
            If c Is Nothing Then
                Exit Sub
            End If

            C.EntireColumn.Copy Destination:=Sheets("Sheet4").Columns(col)
            col = col + 1
            Application.CutCopyMode = False
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With

End Sub

Option 2: Use a regular loop inside the occupied range in Row 7:
Sub FindAverageansStdev()

Dim C As Range
Dim col As Long, LastCol As Long

With Worksheets("Sheet3")
    LastCol = .Cells(7, .Columns.Count).End(xlToLeft).Column '<-- get last column with data in row 7
    col = 1
    For Each C In .Range(.Cells(7, 1), .Cells(7, LastCol)) ' <-- loop through occupied cells only in row 7
        If C.Value Like "*Average*" Or C.Value Like "*StDev*" Then
            C.EntireColumn.Copy Destination:=Sheets("Sheet4").Columns(col)
            ' option to pastespecial (values only)
            C.EntireColumn.Copy
            Sheets("Sheet4").Columns(col).PasteSpecial xlPasteValues
            col = col + 1
        End If
    Next C
End With

End Sub


text:
Q: Preloading scripts and parsing `args` in the spark-shell I have a test script to read a text file provided as a parameter like below:
test.scala:
$ cat test.scala
import scala.io.Source

val filename = args(0)
for (line <- Source.fromFile(filename).getLines) {
    println(line)
}

I want to read a text file below:
$ cat test.txt
test1
test2
test3

I need to run the scala in commandline like below:
spark-shell -i test.scala test.txt

I expect test.txt is recognized as args(0), but I see the output like:

:26: error: not found: value args
           val filename = args(0)

Can anyone enlighten me on what is the right usage to do this? Thank you very much.
UPDATE:
cat test.scala
import scala.io.Source

val args = spark.sqlContext.getConf("spark.driver.args").split(",")
val filename = args(0)

for (line <- Source.fromFile(filename).getLines) {
    println(line)
}

Test result:
 spark-shell -i test.scala --conf spark.driver.args="test.txt"

 SQL context available as sqlContext. Loading test.scala... import
 scala.io.Source <console>:26: error: not found: value spark
          val args = spark.sqlContext.getConf("spark.driver.args").split(",")

A: You can pass your custom --conf argument value to spark. Here is the way how you can pass your arguments:
import scala.io.Source

val args = spark.sqlContext.getConf("spark.driver.args").split(",")
val arg1 = args(0)
val arg2 = arg(1)
print(arg1)

In --conf, I've to pass value of spark.driver.args arguments. So the final command to run the script will be :
spark-shell -i test.scala --conf spark.driver.args="param1value,param2value,param3value"

A: This works for me
import scala.io.Source

val sqlContext = new org.apache.spark.sql.SQLContext(sc)

val args = sqlContext.getConf("spark.driver.args").split(",")

println(args)

args


text:
Q: Using Matlab toolbox "PDToolbox" with Octave: Error messages I want to use "PDToolbox" from Matlab under octave. I'm using the version from https://github.com/carlobar/PDToolbox_matlab, but I have tried the release v1 too. I'm using octave 4.2.2 under ubuntu 18.04.
After installation of the toolbox I first tried to run the tests in the test directory. Some of them work well (sometimes after replacing ole113 by ole23), but all the tests with more than one population give essentially the same error message. For test2.m for instance:
>> test2
Running rd dynamics
error: ode45: INIT must be a numeric vector

I tried to load the package octave-odepkg (0.8.5). (Which gives warnings about shadowing of core libery functions.) After that I get a slightly different error message:
>> test2
Running rd dynamics
error: Third input argument must be a valid numerical value

I don't have access to matlab, so my first question would be whether the same kind of errors appear with matlab. But my main question is of course, how to get past those errors.

A: Use debug_on_error(1) to force octave to drop into debugging mode on error.
From that you will see that in line 47 of run_game, it's trying to pass the initial state G.x0 to ode45, but this is a 2x2 matrix.
Ode45 line 133 tries to ensure that the initial state is in the form of a vector, hence the error.
I tried converting this initial state to a vector in the test2.m file itself (e.g. I did x0 = x0(:)) to see if that fixes the problem, but then the package complains that other things don't have the same shape, which means you'd have to hunt for all the places where this matters.
In any case, it doesn't sound like this toolbox will necessarily be incompatible with octave, as long as you use vectors rather than matrices as inputs. But given the tests use matrices, you may have to tweak them a bit first in order to find out for sure.


text:
Q: How to separate the JSON "Allocation" Key values only to SQL? "data": {
        "status": "success",
        "message": [
            {
                "ptdb2": {
                    "Availability": {
                        "date": "2021-05-18",
                        "time": "00:00:04",
                        "car": "2",
                        "state": "Available"
                    }
                },
                "timestamp": "2021-05-18 03:57:52"
            },
            {
                "ptdb2": {
                    "Allocation": {
                        "date": "2021-05-13",
                        "time": "09:11:03",
                        "start": "1",
                        "dest": "5",
                        "ID": "16",
                        "individualID": "0",
                        "firstname": "Jack",
                        "dept": "dep",
                        "personalNo": "jack_001"
                    }
                },
                "timestamp": "2021-05-13 09:11:04"
            },
            {
                "ptdb2": {
                    "TimingsList": {
                        "null": "null"
                    }
                },
                "timestamp": "2021-05-18 03:57:52"
            }
            ]
    }

Please check image Allocation DATA only need to insert to DB.


text:
Q: Simple type annotations in tern.js I have been looking for a while for a tern.js plugin that would allow me to use simple inline type annotations like this:
var f = function(/* string */ a) { ... }

This is a simple style that, for instance, Brackets supports.
I am aware that I can use JSDoc plugin with tern.js, but that requires a little more verbose syntax, that is especially difficult to use in anonymous functions.
Can I make JSDoc plugin parse these simple annotations or is there another plugin for that?


text:
Q: Focus on a TextField using a keyboard shortcut I have a macOS Monterrey app that has a TextField on the toolbar. I use this to search for text on my app. Now, I'm trying to add a keyboard shortcut to focus on the TextField. I've tried the code below, adding button with a shortcut as a way to test whether this is doable, but I can't get it to work. The .focused() doesn't do anything.
Beyond that, I have added a new menu item Find and set the keyboard shortcut to cmd-L but I don't know either how to send the focus to the TextField.
What am I missing?
struct AllData: View {
    @FocusState private var searchFieldIsFocused: Bool
    @State var searchText: String = ""

    var body: some View {
        NavigationView {
            List(data.notes.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) {
               //...
            }
        }
        .navigationTitle("A Title")
        .toolbar {
            ToolbarItem(placement: .automatic) {
                TextField("Search...", text: $searchText)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .frame(minWidth: 200)
                    .focused($searchFieldIsFocused)
            }

            //test for the focus
            ToolbarItem(placement: .automatic) {
                Button(action: {
                    print("Plus pressed")
                    searchFieldIsFocused = true
                }) {
                    Image(systemName: "plus")
                }
                .keyboardShortcut("e", modifiers: [.command])
            }
        }
    }
}

Edit after Yrb comments
It seems .focusable will not work with a TextField on a toolbar, so he suggested using .searchable.
Trying with .searchable
struct AllData: View {
    @FocusState private var searchFieldIsFocused: Bool
    @State var searchText: String = ""

    var body: some View {
        NavigationView {
            List(data.notes.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) {
               //...
            }
            .searchable(
               text: $searchText,
               placement: .toolbar,
               prompt: "Search..."
            )
        }
        .navigationTitle("A Title")
        .toolbar {
            //test for the focus
            ToolbarItem(placement: .automatic) {
                Button(action: {
                    print("Plus pressed")
                    searchFieldIsFocused = true
                }) {
                    Image(systemName: "plus")
                }
                .keyboardShortcut("e", modifiers: [.command])
            }
        }
    }
}

Observations:

*

*I have no control where the search field will appear, it seems to be the last item on the toolbar, which is not what I want, but OK.

*There is no way that I can find to add a .focusable so I can jump to the search with a keyboard shortcut, which is the reason for this question

*When you search, the list get's filtered, but when you try to navigate the list with the arrows (keyboard), upon selecting the next item, the focus returns to the search field, it doesn't remain on the list, making navigation very slow and painful.

I'm sure I'm missing something, and probably my code is wrong. Any clues?
Edit #2
It seems this is not possible with a .searchable:
.searchable modifier with a keyboard shortcut

A: I ended up getting the following to work on macOS using the .searchable() modifier (only tested on macOS 12.3):
import SwiftUI

@main
struct MyApp: App {

    @State var searchText = ""
    var items = ["Item 1", "Item 2", "Item 3"]
    var searchResults: [String] {
        if searchText.isEmpty {
            return items
        } else {
            return items.filter { $0.contains(searchText) }
        }
    }

    var body: some Scene {
        WindowGroup {
            List(self.searchResults, id: \.self) { item in
                Text(item)
            }.searchable(text: self.$searchText)
        }.commands {
            CommandMenu("Find") {
                Button("Find") {
                    if let toolbar = NSApp.keyWindow?.toolbar,
                        let search = toolbar.items.first(where: { $0.itemIdentifier.rawValue == "com.apple.SwiftUI.search" }) as? NSSearchToolbarItem {
                        search.beginSearchInteraction()
                    }
                }.keyboardShortcut("f", modifiers: .command)
            }
        }
    }
}


text:
Q: Datepicker select list overflow not working I'm using datepicker but finding a problem, when trying to select the year or month with the select list the first time showing goes of on top and bottom with no scrolling available, after closing it and open it like 3 times it works as the example from the official page, I've been trying to find out if there is a problem with position or something but can't seem to figure it out, in the google inspector I see that every time I open it and close it, gets different height and top values.

My code for the input is this:

    <input asp-for="DateOfBirth" type="text" class="validate datepicker" value="@DateTime.Now.ToString("dd/MM/yyyy")">
    * Fecha de Nacimiento


text:
Q: What version of Foundation is used in cakePHP3? From an earlier question (Responsive bootstrap designing in CakePHP 3x) I understand that cakePHP3 are using Foundation for front-end framework, but which version (in cakePHP v.3.2)?
I'm struggling with a toggled top-bar, that won't open when minimized. There seems to have been some bugs in the 5th version and I'm now wondering if they aren't fixed in the version that cakePHP3 are using.

A: The CakPHP application templates base.css file was last updated with foundation on September the 1st of 2015
https://github.com/cakephp/app/commit/3bf179e04d48c859b4ba411d81607ae25d275b3b
As far as I can tell, this is version 5.5.2. If you need a newer version, then simply don't use the templates default CSS, there is absolutely no need to stick with what ships with the template.
Also you can file an issue on GitHub and suggest an update, or even create pull request and update it yourself.


text:
Q: Best way to store time above 24:00:00 in postgresql? I'm storing GTFS feeds into a SQL database and some times are expected to be stored above the 24:00:00 cap on time values. For example, some trains run at 12:30AM, but are listed for the previous days service, and that running time is stored as 24:30 in the GTFS specifications.
What would be the best way of getting around this? Should I just store it as a string?

A: Suggest to use int for that... your value could be:
Sec + Min * 60 + Hour * 3600

For the 24:30:00, you will get 88200.
When loading your value from DB, you could reverse your value by simple math equation:
Hour = int(value / 3600)
Min  = int(value % 3600 / 60)
Sec  = value % 3600 % 1800

A: I'd store two fields:
departure_time timestamp with time zone,
service_date date

Departure time would be calculated like this:
 => select '2015-07-08'::timestamptz+'24:30'::interval;
 2015-07-09 00:30:00+02

This way:

*

*you have a normal moment of time field for sorting events;

*you'd not loose service date information;

*you'd be able to calculate back the original GTFS data if needed.


text:
Q: Strange behavior of performing mouseover over a textarea in Chrome I have a strange problem I can't wrap my head against.  It is present only in Chrome.  The library I'm using is Prototype 1.6.
Basically, I have two elements wrapped into a container element.  First of the two children elements is visible, the second one is hidden.  Inside the hidden element I have a textarea element.  When I mousover the container element, the first child should hide, second one should show itself.  When I mouseout, the behavior should be opposite.  You can see it here, along with the bug :)
http://jsfiddle.net/gmM9m/2
For some reason, in Chrome when I mouseover the textarea, the elements start blinking because they constantly turn themselves on and off.  Does anyone have any idea what causes this behavior and how can I circumvent it?
Thank you!
Luka

A: The closest I've gotten is adding the event to the callback function for the mouseout and making sure that it's coming from the element you want. It seems kind of hackish, but perhaps it's a bug in Chrome. I'm seeing it as well, but wong2 does not seem to be seeing it.
See my revision, still a slight stutter on initial mouseover.
http://jsfiddle.net/gmM9m/10/

A: This works for me.(I'm not familar with JQuery's observe method, so I use JavaScript's addEventListener instead)
$('container').addEventListener("mouseover", function(event){
    $('front').hide();
    $('back').show();
    event.stopPropagation();
}, false);

$('container').addEventListener("mouseout", function(event){
    $('front').show();
    $('back').hide();
    event.stopPropagation();
}, false);

The point is stopPropagation. Run it here: http://jsfiddle.net/RDXzR/

A: I just run into similar problem and solved it with using jquery "mouseenter" and "mouseleave" event
see http://api.jquery.com/mouseenter/


text:
Q: Actualización de un registro especifico python + django He programado una view para crear/insertar artículos de forma satisfactoria, a continuación les coloco lo que ya tengo hecho:
def product_create_view(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm()

    context = {
        'form': form
    }
    return render(request,"products/product_create.html", context)

from django import forms

from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = [
            'title',
            'description',
            'price'
        ]

{%  extends 'base.html' %}

{% block content %}
    <form method='POST'> {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' value='Save' />
</form>
{% endblock content %}

Bien yo quiero poder actulizar un registro especifico, por ejemplo, si el usuario introduce el nombre del articulo "pera" entonces listame todo donde el nombre sea pera y que me permita modificarlo.
He estado buscando como hacer esto pero no logro dar con el asunto, he leído sobre la función filter() pero no lo pillo.
Sugerencias para lograrlo o ideas de donde encontrar información?

A: Puedes hacer una vista de lista para que te muestre los productos.
views.py
from django.views.generic import ListView, DetailView
from .models import Product

class ProductsList(ListView):
    model = Products
    template_name = 'listaProductos.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['products'] = Product.objects.all()
        return context

Luego la urls.py
from .views import ProductList
# agregar en patterns
urlpatterns = [path('lista_productos', ProductsList.as_view(), name= 'listaProductos' ),]

y tu template >>> listaProductos.html
{% for item in products %}
<p> {{item.propiedad}} </p> # propiedad serian los campos del modelo p.e: item.precio
{% enfor %}

A: Muchas Gracias a quienes intentaron brindarme una solución.
He encontrado la respuesta, espero que les funcione a todos los que busquen ejemplos de insertar, eliminar y editar registros.
Aquí
Saludos,


text:
Q: Error response from daemon: Get https://registry-1.docker.io/v2/: Forbidden i am new to docker ,installed docker for windows 10 : version 18.06.0-ce, build 0ffa825
i tried to execute the first docker pull command but it doesn't succeed , i am beside a corporate proxy and the connection to docker server is working fine .
here is what i got :
PS C:\WINDOWS\system32> docker pull microsoft/nanoserver
Using default tag: latest
Error response from daemon: Get https://registry-1.docker.io/v2/: Forbidden.
when i call the link https://registry-1.docker.io/v2/ on the browser i get:
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
edit :
after changing the proxy address i had :
Error response from daemon: Get https://registry-1.docker.io/v2/: Proxy Authentication Required
i have followed the same as windows docker behind a corporate proxy:  ,but still i facing the same issue.

A: The normal solution to this is just docker logout, that's solved it every time anybody I know has it it. Somehow docker gets its credentials out of order or something.

A: After a lot of search i solved the issue by following this step ,
it may work or not depending on you corporate proxy.
find bellow the steps i followed :

*

*install the cntlm from : cntlm.sourceforge.net

*connect to your corporate web proxy using this command :
cntlm -H -u username -d domainname .
username :your domain/proxy account name
domainname:  the actual domain name

*finally you can execute : docker pull


text:
Q: Proof that the Fourier transform of a positive, real, symmetric function is positive, real, symmetric Let $f(x)$ be a real function, symmetric around $x=0$. From the properties of the Fourier transform, we know that $\hat{f}(\omega)$ (the spectrum of $f(x)$) is also a real function, symmetric around $\omega = 0$. However, I need to prove that $\hat{f}(\omega)$ is positive for certain functions $f(x)$. In particular, I am dealing with what I would call "well-behaved" (Gaussian-like) probability density functions: I can assume that $f(x)$ has its (positive) maximum at $x=0$ and strictly decreases smoothly to zero for $x \to \pm \infty$. Can it then be shown that, under the above conditions on $f(x)$, the spectrum $\hat{f}(\omega)$ is positive? Thank you for your help.

A: No. Consider for example
$$
f(x)=(1+x^2)e^{-x^2}.
$$
Then $f(x)>0$ and $f(x)=f(-x)$ for all $x\in\mathbb{R}$. Moreover
$$
f'(x)=-2\,x^3e^{-x^2},
$$
so that it is strictly decreasing in $(0,\infty)$ and achieves its maximum at $x=0$. Finally
$$
\lim_{x\to\infty}f(x)=0.
$$
But
$$
\hat f(\omega)=-\frac{e^{-\frac{\omega ^2}{4}} \left(\omega ^2-6\right)}{4 \sqrt{2}},
$$
which is negative if $|w|>\sqrt6$ and positive if $|w|<\sqrt6$.

A: As the answer by Julián Aguirre shows, the result that you are planning
on proving is not true.  What is true is that the Fourier transform
of a real-valued even function is a real-valued even function; but one of the functions
being nonnegative does not imply that its transform is also nonnegative.
See this answer on stats.SE
for details of what additional conditions you might need to make the result
be true.
More to the point, since you are interested in probability density
functions that are even functions, here is a result
that might help you.
If $X$ is a continuous random variable that can be expressed as $Y-Z$
where $Y$ and $Z$ are independent identically distributed random
variables, then the density of $X$ is related to the densities of
$Y$ and $Z$ as
$$f_X(x) = \int_{-\infty}^\infty f_Y(y)f_Z(y-x)\,\mathrm dy
= \int_{-\infty}^\infty f_Y(y)f_Y(y-x)\,\mathrm dy$$
which is the autocorrelation function of the common density of
$Y$ and $Z$, and so is a real-valued even nonnegative function. Its
Fourier transform is thus a power spectral density, and so is
also a real-valued even nonnegative function as you desire.
Note that it is not necessary for $f_Y$ to be an even function
(though of course it is nonnegative).
Thus, it suffices to find random variables that can be decomposed
into the difference of two independent identically distributed
random variables to get instances of real-valued nonnegative
even functions whose Fourier transforms are also
real-valued nonnegative even functions.


text:
Q: Frequency and amplitude for the three gravitational wave events at LIGO I was reading LIGO/VIRGO's article Binary Black Hole Mergers in the First Advanced LIGO Observing Run, and have two questions concerning the frequencies and the amplitudes of the three gravitational wave events.
The question arises from figure 1 in the article:

As far as I understand, the y-axis shows the strain (which corresponds to the amplitude of the GW). The x-axis left is the frequency of the modulation, and right it is the time.

*

*On the right image (and explained in the GW articles), one sees that the gravitational wave increases both in frequency and amplitude before the merger. Therefore I would expect in the left image, that the indicated amplitude-frequency bands for the three events increase with increasing frequency. However, it shows that the strain of the bands decreases with increasing frequency. Why is that so?

*All three events seem to be significantly above noise even below 30Hz, as one can see from the left plot. In my naive picture, for GW150914 that could lead to a much longer signal. Why do they analyse the waves only above 30Hz (right)?

A: Good question, had me wondering also.
But it's relatively straightforward. On your question 1

*

*the left graph is total power (or really square root of that to simply plot amplitude, and on a strain scale) at each frequency. It includes all the power of the signal at that frequency, even if it was at different times. The waveforms spent more time (more cycles), at lower frequencies, that's why it looks that way -- the power at the lower energies integrated power for a longer period of time. It That's the problem with freq/ampl graphs, a freq may include longer periods of time. For instance, in the last detection for GW 151226 the lower frequencies around 30 Hz went on (yes, slowly increasing) for about a second or so. They explain it, in the quote below from the pdf of the paper, in the next paragraph after Fig. 1 (bold italization is mine for the relevant sentence). You really would like to see a 3D plot, with freq and time in two axis, and amplitude the z axis, you could then see the chirp as a ridge int he time freq plane as in the figure below from Matlab at https://www.mathworks.com/help/signal/examples/practical-introduction-to-time-frequency-analysis.html?requestedDomain=www.mathworks.com

From the pdf you referred us to, at http://journals.aps.org/prx/pdf/10.1103/PhysRevX.6.041015
"The amplitude of the signal is maximum at the merger, after which it decays
rapidly as the final black hole rings down to equilibrium. In the frequency domain, the amplitude decreases with frequency during inspiral, as the signal spends a greater number of cycles at lower frequencies. This is followed by a slower falloff during merger and then a steep decrease during the ringdown.

*On your second question, no GW150914 has about an SNR of 0 dB at 20 Hz, and  better at 30 Hz (at 30 it looks like about 3x$10^{-22}$ at 30, just sort of reading off the graph), so SNR of about $3^2$ or about 10 dB, so just detectable. At 20 Hz it was too low. They will extend the lower limit in later runs I understand.


text:
Q: Eloquent mass update model I want to do 2 updates to a model Articles.
I want one update which i have written
     Article::query()->update([
         'isOnly' => !$value,
         ]);

This $value is based through a switch and it's standard, but for the second update, i want to update the articles only if it has votes, with the flag i have created in the articles migration called isVoted, so if a vote exists to an article this isVoted flag should be true.
Can this been written in a single query?
**Edit also the votes have an isOnly flag and should only count if the isOnly flag is equal to the !$value.
**Edit2 for clarification issues the isOnly flag means that the Article is getting voted alone at the current moment before the plenary session is started, so there are 2 votes, one where the Article is voted alone to see if it passes for the Plenary Sessios and two where the article is voted in the plenary session where the isOnly flag is false.

A: Maybe something like this, if I understood you correctly:
$article = Article::query();

$article->update([
  'isOnly' => !$value,
  'isVoted' => !$value && $article->votes->where('isOnly', !$value)->count()
])


text:
Q: SQL Server insert table column to stored procedure Is it possible to insert to stored procedure a table column from a not declared in any joins? For example,
SELECT
    a.employee, b.department, a.time <= dbo.table_name.column
FROM
    NGAC_AUTHLOG AS a
INNER JOIN
    NGAC_USERINFO AS b ON a.ID = b.UserID

All I get is this error, 'The multi-part identifier "..." could not be bound.'. Is there a way calling a database table column without using the join?
Thanks in advance.

A: Try this:
SELECT
    a.employee, b.department, (case when a.time <= (select top 1 column from dbo.table_name) then 'True' else 'False' end) TrueOrNot
FROM
    NGAC_AUTHLOG AS a
INNER JOIN
    NGAC_USERINFO AS b ON a.ID = b.UserID


text:
Q: React Native Image Background I am trying to do this by using the green background like an image, but I need to do it via styling. Can someone guide me on how to do this without using the image?

A: You have to make it's position absolute, make the zIndex high, and then take use of transform (https://reactnative.dev/docs/transforms) to rotate it the way you want.
Super short example of using these things,
<View style{{position:"absolute",top:0,bottom:0,left:0,
            right:0,zIndex:10,
            backGroundColor:"green",
            transform: [{ rotate: "45deg" }]]
           }}>

</View>

A: Short Answer: Not sure if there is a solid way to do that just with RN styles.
I was thinking that we can use these CSS tricks
so I tried them here but it's not working on Android. If I want to do that, I would use react-native-svg as you are free to draw whatever you want.


text:
Q: Glob pattern to search for the directories,files inside a directory I am using a glob pattern to recursively walk through through a directory and get all the files and directories inside that directory.
I have a directory : d:/test/newfolder/...
Inside the newfolder there are some files and some directories which internally contain some files.
For Example: d:/test/newfolder/new.txt , d:/test/newfolder/temp/tempfile.doc etc..
I am using Path Mathcher to match the globpatterns.
Here is my code:
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    try {
        Files.walkFileTree(startDir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) throws IOException {
                if (matcher.matches(file.getFileName())) {
                    System.out.println("found files&directories: " + file.getFileName());
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (matcher.matches(file.getFileName())) {
                        System.out.println("found files: " + file.getFileName());
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

If I want to search  for a file, i can give the pattern glob:*.txt and it works fine.
But I do not know what pattern should I give to search for directory. I want to get all the files and directories present in "newfolder" directory.
I am trying with glob:newfolder/** , but It is not working for me.
And Is there anything wrong with the code?
Please help me.
Thanks in Advance


text:
Q: Classifying regions of a signal trace I have a stack of signals that I'd like to perform an ML algorithm to chop them up into regions determined by their characteristics. The full signal looks a bit like this:

And a fragment of it looks like this:

In particular, I'd like to highlight the bits of the trace where the discontinuities are.
All of the traces I have are likely to be of varying lengths, and with variable amounts of noise on them so some of the discontinuities are hard to detect (e.g. around the 5000 mark on this trace). I do have a set of reasonably well labelled data that I would like to use to train some form of ML to do this to try and better regular numerical techniques. I've so far done some basic stuff with a regular neural net, and a CNN, on a sliding window through the data which doesn't do too badly but I'm keen to explore other options. In particular, is there a 1-D variant on RCNN/YOLO algorithms that could be used to return a set of windows that bound each discontinuity? it should be noted that the discontinuities may be of varying width, too


text:
Q: Stop running execution of JNI method I have executing method (for example JNI.calculate(listener))of JNI library. It should takes for example 30 seconds. I wanted but executing this method calculate(listener) again but first I need to stop last executing. This method has one parameter - listener, that has two methods:
public void canContinue(){
      return canContinue;
}

public void result(int number){
      //some code
}

The method canContinue calls asynchronous, for example every 3 seconds. I just dont want to wait, until next canContinue will be called. I wanted to immediatelly execute next execution of this method calculate(listener).
Do you have any recommendations? Probably I should use Handler, HandlerThread, Thread, AsyncTask or som sort of this classes, but how to figure it out?

A: i didn't understand the question correctly but i think keeping a delay will do the trick, to keep delay write this
try {
      Thread.sleep(1000); // time in milliseconds
    } catch (InterruptedException e) {
         e.printStackTrace();
      }

A: What if you call your function JNI.calculate(listener) from a Thread ? You can start that Thread which calls this function, and when you want an other and immediate execution, interrupt the Thread and start another (never restart a terminated thread!). Be careful with manipulated data: you should use a mutex to prevent it.
See that too (it's about thread interruption and gives some precisions):
https://stackoverflow.com/a/6378525/6523232