text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How do I change the appearance of my banner?
I keep unlocking new banner sigils/shapes/accents by completing various achievements, but how do I actually use them? My banner (G key) doesn't actually seem to change its appearance.
A:
You need to click on the banner behind your hero on the main menu.
(Geez, the starting Wizard armor makes her look like a tramp...)
| {
"pile_set_name": "StackExchange"
} |
Q:
Circular Dependency in an inherited code base
I'm very much still learning how to structure larger code bases (a year ago I had only dealt in solutions of 3/4 small projects whilst learning), and I've been trying to organise an inherited code base to get rid of a Circular Dependency issue.
Basically I have an MVC Portal project backed by an SQL database which is code first using Entity Framework. I also have a repository project which handles communication to some Azure tables. The data in these tables overlaps somewhat but the Azure table does not contain much of the information from the Portal db.
The problem arises as when I create certain entities, the solution as it is demands they be created in the Portal Database (so that users can see their information) and also in these Azure tables which the rest of the solution uses for other purposes.
So the Portal persists data to both, meaning I need to use the Repository project within my MVC project, but I also need my Repository project to be able to access the MVC project for some peripheral information which is not persisted to the Azure tables.
This is obviously bad design, but structurally is there a way around it which doesn't require major refactoring or changes to the Azure table structure to include every little detail of the Portal db?
Every "simple fix" I come up with isn't a fix at all and merely makes the Circle bigger haha. These two tables in the design have confused me since I inherited this.
EDIT for more clarity
My repository references the MVC project in order to use the ApplicationDbContext to communicate with Portal db. This is not easily separated into another project as I understand.
My MVC project references the Repository to store information in Azure tables. this needs to stay as it is really.
Tha problem I guess is the Repository does too much. I'm starting to think I should just separate those out despite it being quite the rework.
JK
A:
Correct me if I am wrong, but from what I understood, you currently want to exchange information between the Azure Storage and the SQL Storage. If that is the case, then you should create a BaseRepository which is inherited by both the SQL and Azure storage. Then the "peripheral information" can be found in properties from the BaseRepository, which are accessible by its children.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequence Combination Matrix in R
I'm looking to create a matrix for 5 variables, such that each variable takes a value from seq(from = 0, to = 1, length.out = 500) and rowSums(data) = 1 .
In other words, I am wondering how to create a matrix that shows all the possible combinations of numbers with the sum of every row = 1.
A:
Here is an iterative solution, using loops. Gives you all possible permutations of numbers adding up to 1, with the distance between them being a multiple of N. The idea here is to take all numbers from 0 to 1 (with distance of a multiple of N between them), then for each one include in a new column all the numbers that when added don't go above 1. Rinse and repeat, except in the last iteration, in which you only add the numbers that complete the row the sum of the row.
Like people pointed out in the comments, if you want N = 1/499*, it will give you a really really big matrix. I noticed that for N = 1/200 it was already taking around 2, 3 minutes, so it would probably take way too long for N = 1/499.
*seq(from = 0, to = 1, length.out = 500) is the same as seq(from = 0, to = 1, by = 1/499)
N = 1/2
M = 5
x1 = seq(0, 1, by = N)
df = data.frame(x1)
for(i in 1:(M-2)){
x_next = sapply(rowSums(df), function(x){seq(0, 1-x, by = N)})
df = data.frame(sapply(df, rep, sapply(x_next,length)))
df = cbind(df, unlist(x_next))
}
x_next = sapply(rowSums(df), function(x){1-x})
df = sapply(df, rep, sapply(x_next,length))
df = data.frame(df)
df = cbind(df, unlist(x_next))
> df
x1 unlist.x_next. unlist.x_next..1 unlist.x_next..2 unlist(x_next)
1 0.0 0.0 0.0 0.0 1.0
2 0.0 0.0 0.0 0.5 0.5
3 0.0 0.0 0.0 1.0 0.0
4 0.0 0.0 0.5 0.0 0.5
5 0.0 0.0 0.5 0.5 0.0
6 0.0 0.0 1.0 0.0 0.0
7 0.0 0.5 0.0 0.0 0.5
8 0.0 0.5 0.0 0.5 0.0
9 0.0 0.5 0.5 0.0 0.0
10 0.0 1.0 0.0 0.0 0.0
11 0.5 0.0 0.0 0.0 0.5
12 0.5 0.0 0.0 0.5 0.0
13 0.5 0.0 0.5 0.0 0.0
14 0.5 0.5 0.0 0.0 0.0
15 1.0 0.0 0.0 0.0 0.0
| {
"pile_set_name": "StackExchange"
} |
Q:
In the context of date formatting, why does `%b` indicate abbreviated month?
When formatting dates, the use of %m=month, %y=day, and %d=day are obvious and memorable, but what does the b in %b stand for?
In other words, why does %b indicate abbreviated month? Is this simply working through alphabet to describe the various terms or is there a meaningful link?
I found plenty of sites that describe the format (e.g. W3Schools, but I haven't been able to find the etymology of the %b term.
A:
You are looking for a semantic rationale or mnemonic when there is none. Lower case b was probably chosen for symmetry with A, a for weekday and abbreviated weekday.
B and b provide the same for month names.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fire event when jQuery Splitter drag stops
I am using jQuery Splitter plugin from https://github.com/jcubic/jquery.splitter. Splitter works fine. I need to know how can I fire some event as soon as I stop drag of splitter. I need to preserve new splitter left position in back-end and use it next time.
mouseup, mousemove events are not working as desired. Below is the method which I tried. It only works when mouse is clicked on splitter without dragging it (Mouse click at same position). Once you drag splitter, this do not work.
jQuery('.vspliter').on("mouseup", function (e) {
alert('Mouse is released now');
// call ajax function over here
});
Let me know, if more information is needed.
A:
I am able to resolve this using below code by detecting drag:
var isDragging = false;
jQuery('.spliter_panel').mousedown(function() {
jQuery('.spliter_panel').mousemove(function() {
isDragging = true;
jQuery('.spliter_panel').unbind("mousemove");
});
});
jQuery('.spliter_panel').mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
jQuery('.spliter_panel').unbind("mousemove");
if (wasDragging) {
//Call Ajax method
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with Catkin Build
Never happen before but If I create a directory mkdir -p catkin_ws/src and then enter catkin build I have the following error:
emeric@emeric-desktop:~/catkin_plan_ws$ catkin build
------------------------------------------------------
Profile: default
Extending: [env] /opt/ros/kinetic
Workspace: /home/emeric
------------------------------------------------------
Source Space: [exists] /home/emeric/src
Log Space: [missing] /home/emeric/logs
Build Space: [exists] /home/emeric/build
Devel Space: [exists] /home/emeric/devel
Install Space: [unused] /home/emeric/install
DESTDIR: [unused] None
------------------------------------------------------
Devel Space Layout: linked
Install Space Layout: None
------------------------------------------------------
Additional CMake Args: DCMAKE_BUILT_TYPE=Release
Additional Make Args: None
Additional catkin Make Args: None
Internal Make Job Server: True
Cache Job Environments: False
------------------------------------------------------
Whitelisted Packages: None
Blacklisted Packages: None
------------------------------------------------------
Workspace configuration appears valid.
NOTE: Forcing CMake to run for each package.
------------------------------------------------------
Traceback (most recent call last):
File "/usr/bin/catkin", line 9, in <module>
load_entry_point('catkin-tools==0.4.4', 'console_scripts', 'catkin')()
File "/usr/lib/python2.7/dist-packages/catkin_tools/commands/catkin.py", line 267, in main
catkin_main(sysargs)
File "/usr/lib/python2.7/dist-packages/catkin_tools/commands/catkin.py", line 262, in catkin_main
sys.exit(args.main(args) or 0)
File "/usr/lib/python2.7/dist-packages/catkin_tools/verbs/catkin_build/cli.py", line 420, in main
summarize_build=opts.summarize # Can be True, False, or None
File "/usr/lib/python2.7/dist-packages/catkin_tools/verbs/catkin_build/build.py", line 283, in build_isolated_workspace
workspace_packages = find_packages(context.source_space_abs, exclude_subspaces=True, warnings=[])
File "/usr/lib/python2.7/dist-packages/catkin_pkg/packages.py", line 86, in find_packages
packages = find_packages_allowing_duplicates(basepath, exclude_paths=exclude_paths, exclude_subspaces=exclude_subspaces, warnings=warnings)
File "/usr/lib/python2.7/dist-packages/catkin_pkg/packages.py", line 146, in find_packages_allowing_duplicates
xml, filename=filename, warnings=warnings)
File "/usr/lib/python2.7/dist-packages/catkin_pkg/package.py", line 509, in parse_package_string
raise InvalidPackage('The manifest must contain a single "package" root tag')
catkin_pkg.package.InvalidPackage: The manifest must contain a single "package" root tag
Besides the build and devel folders are created in my home directory not in the catkin one.
I guess I messed up something but I do not what and thus how to fix it.
Thank you for your help
A:
the root Folder of build, install, log, devel and src space should be your catkin root where you can call to catkin build (in your case it's ~/catkin_ws).
in a nutshell, you can't do a task outside of initiated catkin folder with catkin
| {
"pile_set_name": "StackExchange"
} |
Q:
NVidia blank screen with cursor
[Note: I know there are many questions on nvidia and blank screen, but none so far have brought me closer to a solution, I've tried a lot, see below]
Problem:
Running Xubuntu 18.10 on a Dell XPS 9570 (which has a GeForce GTX 1050 Ti card, along with built-in Intel graphics), the nvidia 410 and 415 drivers stopped working.
All I get when I start Linux after the scrolling boot messages, is a black screen with (non-blinking) white cursor on the upper left corner. nouveau drivers work fine, but they only allow me to use the built-in laptop screen but not ones attached to the laptop via HDMI.
It used to work (if you can call it that, when it boots to a working desktop environment 2 out of 3 times, and stays black otherwise) until today morning (when I did an apt upgrade, which installed linux-image-4.18.0-13.
What I have tried so far to resolve this:
tried booting the linux-image-4.18.0-12, same issue
as recommended here, I added nomodeset kernel option to be set through grub (I already set this a while ago, this was required to get it working in the first place)
as recommended most of the time on blank screen related nvidia questions, I tried purging everything nvidia-related (everything listed by dpkg --list | grep nvidia), and reinstalling 410 drivers
I also added graphics-drivers ppa and installed 415 drivers from there (https://launchpad.net/~graphics-drivers/+archive/ubuntu/ppa) (a few times with purging in between)
Tried Bumblebee: https://wiki.ubuntu.com/Bumblebee (the guide there doesn't seem to activate the nvidia driver, right? At least for me it didn't, nouveau still was used)
As for the issue mentioned above, when the GUI would only load every 2 out of 3 times, I tried xdm, gdm, lddm - but with them, I got a black screen all the time; only lightdm (where I remember an issue a while back causing exactly the symptoms I saw) seems to work togehter with nvidia driver...
As for errors in the journal, I see something regard to the nvidia-persistenced and some bumblebee reference (the latter only after installing bumblebee, of course). There don't seem to be any real nvidia-related errors now (and there weren't previously on the occasions when the screen stayed blank):
$ journalctl --since today | grep -i nvidia | grep -i "\(err\|fail\)"
Dez 21 07:04:45 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.23 Thu Dec 6 21:34:12 CST 2018 (using threaded interrupts)
Dez 21 13:44:00 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.23 Thu Dec 6 21:34:12 CST 2018 (using threaded interrupts)
Dez 21 13:44:00 nertha nvidia-persistenced[743]: nvidia-persistenced failed to initialize. Check syslog for more details.
Dez 21 13:44:00 nertha nvidia-persistenced[749]: Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 121 has read and write permissions for those files.
Dez 21 13:44:00 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'exit-code'.
Dez 21 13:44:00 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 13:47:49 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.23 Thu Dec 6 21:34:12 CST 2018 (using threaded interrupts)
Dez 21 13:47:49 nertha nvidia-persistenced[772]: nvidia-persistenced failed to initialize. Check syslog for more details.
Dez 21 13:47:49 nertha nvidia-persistenced[780]: Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 121 has read and write permissions for those files.
Dez 21 13:47:49 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'exit-code'.
Dez 21 13:47:49 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 13:47:50 nertha nvidia-persistenced[875]: Failed to unlink PID file: No such file or directory
Dez 21 13:47:50 nertha nvidia-persistenced[912]: Failed to unlink PID file: No such file or directory
Dez 21 13:47:50 nertha nvidia-persistenced[951]: Failed to unlink PID file: No such file or directory
Dez 21 13:47:50 nertha nvidia-persistenced[971]: Failed to unlink PID file: No such file or directory
Dez 21 13:47:50 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'start-limit-hit'.
Dez 21 13:47:50 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 13:47:50 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'start-limit-hit'.
Dez 21 13:47:50 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 13:58:06 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.23 Thu Dec 6 21:34:12 CST 2018 (using threaded interrupts)
Dez 21 14:09:52 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.25 Wed Dec 12 10:22:08 CST 2018 (using threaded interrupts)
Dez 21 14:09:52 nertha nvidia-persistenced[754]: nvidia-persistenced failed to initialize. Check syslog for more details.
Dez 21 14:09:52 nertha nvidia-persistenced[759]: Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 121 has read and write permissions for those files.
Dez 21 14:09:53 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'exit-code'.
Dez 21 14:09:53 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 14:10:53 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.25 Wed Dec 12 10:22:08 CST 2018 (using threaded interrupts)
Dez 21 14:10:53 nertha nvidia-persistenced[809]: nvidia-persistenced failed to initialize. Check syslog for more details.
Dez 21 14:10:53 nertha nvidia-persistenced[811]: Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 121 has read and write permissions for those files.
Dez 21 14:10:53 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'exit-code'.
Dez 21 14:10:53 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 14:10:54 nertha nvidia-persistenced[912]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[920]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[926]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[956]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[975]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[988]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1016]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1058]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1068]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1089]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1105]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1113]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1121]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1131]: Failed to unlink PID file: No such file or directory
Dez 21 14:10:54 nertha nvidia-persistenced[1142]: Failed to unlink PID file: No such file or directory
Dez 21 14:31:05 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 415.25 Wed Dec 12 10:22:08 CST 2018 (using threaded interrupts)
Dez 21 14:31:05 nertha nvidia-persistenced[756]: nvidia-persistenced failed to initialize. Check syslog for more details.
Dez 21 14:31:05 nertha nvidia-persistenced[759]: Failed to query NVIDIA devices. Please ensure that the NVIDIA device files (/dev/nvidia*) exist, and that user 121 has read and write permissions for those files.
Dez 21 14:31:05 nertha systemd[1]: nvidia-persistenced.service: Failed with result 'exit-code'.
Dez 21 14:31:05 nertha systemd[1]: Failed to start NVIDIA Persistence Daemon.
Dez 21 14:31:06 nertha systemd-udevd[403]: Process '/bin/mknod -m 666 /dev/nvidiactl c 195 255' failed with exit code 1.
Dez 21 14:31:06 nertha systemd-udevd[403]: Process '/bin/mknod -m 666 /dev/nvidia0 c 195 0' failed with exit code 1.
Dez 21 14:31:06 nertha bumblebeed[783]: [ 5.548701] [ERROR]Failed to unload module 'nvidia_drm' (ref count: 2).
Dez 21 14:31:06 nertha bumblebeed[783]: [ 5.548716] [ERROR]Failed to unload module 'nvidia_modeset' (ref count: 2).
Dez 21 14:31:06 nertha bumblebeed[783]: [ 5.548724] [ERROR]Failed to unload module 'nvidia' (ref count: 77).
Dez 21 14:48:44 nertha kernel: NVRM: loading NVIDIA UNIX x86_64 Kernel Module 410.78 Sat Nov 10 22:09:04 CST 2018 (using threaded interrupts)
Dez 21 14:48:45 nertha systemd-udevd[427]: Process '/bin/mknod -m 666 /dev/nvidiactl c 195 255' failed with exit code 1.
Dez 21 14:48:45 nertha systemd-udevd[427]: Process '/bin/mknod -m 666 /dev/nvidia0 c 195 0' failed with exit code 1.
Dez 21 14:48:45 nertha bumblebeed[804]: [ 5.564388] [ERROR]Failed to unload module 'nvidia_drm' (ref count: 2).
Dez 21 14:48:45 nertha bumblebeed[804]: [ 5.564420] [ERROR]Failed to unload module 'nvidia_modeset' (ref count: 2).
Dez 21 14:48:45 nertha bumblebeed[804]: [ 5.564428] [ERROR]Failed to unload module 'nvidia' (ref count: 77).
I really would like to use nvidia drivers again, as with nouveau, external screens don't seem to be recognized. What else can I try? If you need more info, let me know!
Part of this seems to be a lightdm problem. As noted in the answer below, for some reason, lightdm doesn't seem to start properly the first time. The only problem related to lightdm turning up in the journal (journalctl -b) is:
PAM unable to dlopen(pam_kwallet.so): /lib/security/pam_kwallet.so: cannot open shared object file: No such file or directory
PAM adding faulty module: pam_kwallet.so
I suppose this message is not related to this issue, it's probably a non-issue as far as I see from issues mentioning this message...
A:
I got the nvidia-driver-390 to work with the previous kernel, 4.18.0-12 (but still didn't get multi-monitor support running).
Then I decided to try again with 4.18.0-13, but without nomodeset option - and that fixed it!
So the solution in my case:
- nvidia-driver 390 drivers
- Remove nomodeset from the line starting with GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub.
The issue with the occasional blank screen when starting still appears. It seems to have grown more frequent actually. A workaround in this situation is to log in on tty1 and execute: sudo systemctl restart lightdm.
| {
"pile_set_name": "StackExchange"
} |
Q:
tmux と emacsclient を併用すると、片一方の pane に client がとられてしまう
emacsclient と tmux を併用して、以下の挙動に遭遇しました。
emacs --daemon を起動
tmux を起動
pane 分割
一方の pane で emacsclient を起動 -> 問題なく起動
もう一方の pane で emacsclient を起動 -> Waiting for Emacs... (そして、 4 の pane で client が2重に起動しているような挙動。2回 client を終了すると shell にもどるので)
になっているのですが、どうしてこのような挙動になるのでしょうか。具体的には、どうして 5 の pane で起動した emacsclient が 4 の pane で動くのでしょうか。
A:
emacsclient のソースコードを眺めてみますと、デフォルトでは最初の接続で作成した frame(この場合は terminal frame)を以降の emacsclient による接続でも使用する事が分かります。
emacs/lib-src/emacsclient.c
/* Nonzero means don't open a new frame. Inverse of --create-frame. */
int current_frame = 1;
:
static void
decode_options (int argc, char **argv)
{
:
switch (opt)
{
:
case 't':
tty = 1;
current_frame = 0;
break;
:
int
main (int argc, char **argv)
{
:
if (current_frame)
send_to_emacs (emacs_socket, "-current-frame ");
:
emacs/lisp/server.el
(cl-defun server-process-filter (proc string)
:
;; -current-frame: Don't create frames.
(`"-current-frame" (setq use-current-frame t))
なお、新たに frame を作成する場合は -nw/-t/-tty オプションを指定します。
emacsclient(1)
-nw, -t, --tty
open a new Emacs frame on the current terminal
| {
"pile_set_name": "StackExchange"
} |
Q:
People Dancing Algorithm
I am having trouble with an algorithmic problem that goes like this:
N people line up in some order (Each of their positions are marked as 1...N.), and then perform successive dance moves, which reorders their positions.
A set of dance moves is described with N numbers, call them d1, d2, d3, ... dn. The person in position i corresponds to dance move di. During the dance move, each person moves to his or her new location. Not all values of di are distinct, which means that some people may be placed on the same square. This means that they will move together for the rest of the remaining dances.
Input:
The first line inputs N (the number of people), and the next line inputs d1, d2, d3 ... dn.
Output
I must output the number of positions that will ALWAYS contain people, no matter how many shuffles take place.
Example Input:
4
3 2 1 3
Analysis:
Here, N = 4 and d1 = 3, d2 = 2, d3 = 1, d4 = 3
The output here will be 3 because there will always be people in spaces 1, 2, and 3.
In the first shuffle, person 1 and 4 will be "mapped" to index 3. Person 2 will be "mapped" to index 1, and person 3 will be "mapped" to index 2. No matter how many times this dance process continues, these three spots will always be occupied, because the numbers 3, 1, 2 are in the first three numbers, and these are the three spots that are occupied.
-
I am not sure if this requires some sort of special data structure or something? Perhaps a queue? I have tried some of my ideas for a couple of hours, but I cannot come up with anything. Any help is much appreciated.
I created an array of integers [1...N] representing the original positions of the people, and I made another array [d1 ... dn] representing the mapping corresponding to each index. Through some research, I found "multisets," which may be relevant. I tried messing around with those, as well as ArrayList, but I still couldn't make much progress.
A:
Current answer
The previous answer assumed that the movement of people to their new positions would be sequential, i.e. people would start moving together within the same sequence.
The answer below assumes that the movement within the same sequence is instantaneous. It uses two arrays to map people from their old positions to their new positions, and continues running the sequence as long as there is a reduction in the total number of spaces occupied.
public static void main(String[] args) {
int numberOfPeople = 4;
int[] moves = new int[]{3, 2, 1, 3};
int[] positions = new int[numberOfPeople];
Arrays.fill(positions, 1);
int positionsOccupied;
do {
positionsOccupied = positionsOccupied(positions);
positions = dance(positions, moves);
} while (positionsOccupied(positions) < positionsOccupied);
System.out.println("Result: " + positionsOccupied(positions));
}
public static int[] dance(int[] oldPositions, int[] moves) {
int[] newPositions = new int[oldPositions.length];
for (int i = 0; i < oldPositions.length; i++) {
newPositions[moves[i] - 1] += oldPositions[i];
}
return newPositions;
}
public static int positionsOccupied(int[] positions) {
int result = 0;
for (int i = 0; i < positions.length; i++) {
if (positions[i] > 0) {
result++;
}
}
return result;
}
Previous answer
You actually only need one array to hold the positions, and an additional array to hold a snapshot of the previous state.
After every iteration, the snapshot is compared with the current positions, and if they're equal this means that subsequent invocations of the dance sequence will have no further impact on the positions and that you can calculate a final result:
public static void main(String[] args) {
int numberOfPeople = 4;
int[] moves = new int[]{3, 2, 1, 3};
int[] positions = new int[numberOfPeople];
Arrays.fill(positions, 1);
int[] snapshot;
do {
snapshot = Arrays.copyOf(positions, positions.length);
dance(positions, moves);
} while (!Arrays.equals(positions, snapshot));
System.out.println("Result: " + positionsOccupied(positions));
}
public static void dance(int[] positions, int[] moves) {
for (int i = 0; i < positions.length; i++) {
int currentNumber = positions[i];
positions[i] = 0;
positions[moves[i] - 1] += currentNumber;
}
}
public static int positionsOccupied(int[] positions) {
int result = 0;
for (int i = 0; i < positions.length; i++) {
if (positions[i] > 0) {
result++;
}
}
return result;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Include a media type in an Entity from Sonata Admin
I'm making an Entity which is called Article, it should have some text, a video and a couple of images. For the latter I'm doing it by allowing the user to create a media and then include the images there, now for the question... how do I relate that media to the article? Do I have a "media list picker" to choose from?
A:
To include Sonata MediaBundle in the Admin Bundle, you'll need to add for example an Image field to your Article entity.
/**
* @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Gallery")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="image", referencedColumnName="id")
* })
*/
private $image;
And then refer to it in your ArclicleAdmin :
->add('image', 'sonata_type_model_list', array('required' => false))
| {
"pile_set_name": "StackExchange"
} |
Q:
Training GPU on multiple minibatches in parallel with TensorFlow
I am using TensorFlow 1.9, on an NVIDIA GPU with 3 GB of memory. The size of my minibatch is 100 MB. Therefore, I could potentially fit multiple minibatches on my GPU at the same time. So my question is about whether this is possible and whether it is standard practice.
For example, when I train my TensorFlow model, I run something like this on every epoch:
loss_sum = 0
for batch_num in range(num_batches):
batch_inputs = get_batch_inputs()
batch_labels = get_batch_labels()
batch_loss, _ = sess.run([loss_op, train_op], feed_dict={inputs: batch_inputs, labels: batch_labels})
loss_sum += batch_loss
loss = batch_loss / num_batches
This iterates over my minibatches and performs one weight update per minibatch. But the size of image_data and label_data is only 100 MB, so the majority of the GPU is not being used.
One option would be to just increase the minibatch size so that the minibatch is closer to the 3 GB GPU capacity. However, I want to keep the same small minibatch size to help with optimisation.
So the other option might be to send multiple minibatches through the GPU in parallel, and perform one weight update per minibatch. Being able to send the minibatches in parallel would significantly reduce the training time.
Is this possible and recommended?
A:
The goal of the Mini Batch approach is to update the weights of your network after each batch is processed and use the updated weights in the next mini-batch. If you do some clever tricks and batch several mini-batches they would effectively use the same old weights.
The only potential benefit I can see is if the model works better with bigger mini-batches, e.g. big_batches * more_epochs is better than mini_batches * less_epochs. I don't remember the theory behind Mini Batch Gradient Descent but I remember there is a reason you should use mini batches instead of the whole training set for each iteration. On the other hand, the mini batch size is a hyperparameter that has to be tuned anyway, so it's probably worth fiddling it a bit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking singleton property with nil value causes error
When I check a singleton property that is nil, it kills my app. But when I check for nil on a class instance property, everything works fine.
This works fine:
self.MyProperty == nil
but this will kill the app with “EXC_BAD_ACCESS”
[MySingleton sharedManager].SomeProperty != nil
What is the difference with the singleton that I can't check for nil?
Here's the singleton implementation:
.h file:
@interface MySingleton : NSObject {
NSString * SomeProperty;
}
@property (nonatomic, copy) NSString * SomeProperty;
+(MySingleton *)sharedManager;
@end
.m file:
#import "MySingleton"
static MySingleton *sharedManager = nil;
@implementation MySingleton
@synthesize SomeProperty;
- (void)dealloc {
[SomeProperty dealloc];
[super dealloc];
}
+(MySingleton *)sharedManager
{
if (!sharedManager){
sharedManager = [[MySingleton alloc] init];
}
return sharedManager;
}
This is what I find in the console when when trying to assign something to SomeProperty:
MyApp(51363,0xa0389500) malloc: *** mmap(size=2147487744) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Current language: auto; currently objective-c
(gdb) break malloc_error_break
Note: breakpoints 6 and 8 also set at pc 0x929c2072.
Breakpoint 11 at 0x929c2072
(gdb) continue
(gdb) po [MySingleton sharedManager].SomeProperty
Cannot access memory at address 0x0
(gdb) po [MySingleton sharedManager]
<Session: 0x1938fa0>
I get the above only when trying to assign. When trying to read the variable is where the crash occurs.
A:
Given this:
- (void)dealloc {
[someKey dealloc];
[super dealloc];
}
And some of the other code, I'd go out on a limb and say it is likely that there are other problems with the code, the combination of which are leading to the problem you have hinted at. In particular, you should never call -dealloc directly (other than [super dealloc]). If you have that in other parts of your code and it is being executed, it could easily cause the symptom you describe.
If you want a more specific answer, post the backtrace of the crash.
MyApp(51363,0xa0389500) malloc: * mmap(size=2147487744) failed (error code=12) error: can't allocate region
** set a breakpoint in malloc_error_break to debug Current language: auto; currently objective-c
Set the breakpoint as indicated and then re-run the application. Once that error message happens, all bets are off as your app is already hosed. You need the backtrace of when that call is made.
What is happening, though, is that something is asking mmap() to map in 2GB of address space. Could be corruption. Could be bad code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does $\pi$ contain the combination $ 1234567890$?
This question is related with Does Pi contain all possible number combinations?. More specifically, I want to know if $\pi$ contains $1234567890$. I checked this link https://www.facebook.com/notes/astronomy-and-astrophysics/what-is-the-exact-value-of-pi-%CF%80/176922585687811 and did not see it there. I think that $\pi$ does not contain $1234567890$. It is true or not. If it is true, how to prove it?
A:
The nature of most real numbers is that, in any base, you can find any sequence of digits infinitely many times. The definition of "most" is technical, but rigorous.
We don't know if $\pi$ has this property, but we don't know it doesn't. It appears to have this property in base $10$, but we can't prove it, yet, and "appears" is always a bit of nonsense when we are saying, "We've checked the first $N$ examples out of infinity."
So, as Cameron commented, you are not going to find anybody here who is going to be able to prove that it doesn't occur, since, if we could, we'd have answered a long unresolved question.
If $\pi$ acted like a string of random digits, then you'd expect to have to check on the order of $10^{10}$ or $10$ billion digits before you found $1234567890$. If you tested $1$ trillion digits and still didn't find this sequence, I'd be shocked. But I don't know where you can download $1$ trillion digits of $\pi$...
In the first 1 billion digits of $\pi$, I found two instances of $123456789$, but no instances of $1234567890$.
Here's a simple example. In the first billion digits, there were $10049$ instances of $12345.$ There were $969$ instances of $123456$. There were $97$ instances of $1234567$. There were $9$ instances of $12345678$. And there were two instances of $123456789.$ If the digits of $\pi$ were random, we expect that approximately one tenth of the instances of $123456789$ in any sample would have next digit $0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print number of blocks in a region in Drupal 6
I use Drupal 6 and I'm trying to get number of blocks in a region. How is that possible?
A:
The following query returns the number of blocks in the left region of the current theme.
Replace left with your region name.
$current_theme = variable_get('theme_default', '');
$number_of_blocks = db_result(db_query("SELECT COUNT(*) FROM {blocks} WHERE theme='%s' AND region='%s'", $current_theme, 'left'));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Uninstall the Ubuntu SDK?
After Installing the Ubuntu SDK v1.009 on ubuntu 12.04.2 LTS, the computer started behaving in a very unstable manner. Also note that Installing the Ubuntu SDK also installs a lot of test libraries over the stable ones. I wanted to know if there is any way to uninstall the SDK without reinstalling Ubuntu. I also want to replace the installed, unstable libraries with the latest stable ones.
Thanks in Advance
A:
Yes you can remove Ubuntu-SDK without re-installing Ubuntu. Once it is removed, you can also remove all library files associated with it.
Run following commands in series:
$ sudo apt-get autoremove ubuntu-sdk
$ sudo apt-get --purge remove ubuntu-sdk
$ sudo apt-get autoclean
$ sudo apt-get autoremove
$ sudo apt-get -f install
Above commands will remove Ubuntu-SDK from your system. If you get any error after any command, just edit your question and paste the result. Reply for further assistance.
| {
"pile_set_name": "StackExchange"
} |
Q:
PSQL incomplete backup : how to debug
I've been doing backups of my database " screen ".
after connecting to PSQL and typing \l+
I'm getting (among other things):
Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description
------------------+-------+----------+-------------+-------------+-------------------+---------+------------+--------------------------------------------
screen | admin | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 36 GB | pg_default |
The size of my database being around 36GB.
Now i usually make regular backups doing :
pg_dumb screen > screenbackup.bak
And the size of the output was always pretty consistent with the size of my database.
But today i got a backup of only 8gb and that seems really odd to me.
After restoring into a temporary db and performing a few query there indeed seems to be a few missing data.
The size of the restored data was 10GB..
Thankfully I never dropped the original in the first place but there always seems to be a problem. I can't get pg_dump or pg_dumpall to backup the complete DB. The size is inconsistent when in my experience it's often at least the same size of the db or Bigger. not 4 time smaller..
Do you have any idea where to go from there to know where the problem is coming from?
Edit: maybe it's important: I'm on PSQL 9.4.4.1 and trying to do the backup so I can update Postgres in addition to just saving my data.
A:
Did you get any error messages on dump, or on restore? If not, then the most likely explanation is that nothing is wrong. There is no tight coupling between the size of the database and the size of the dump. For example, if you deleted a bunch of data and did not do a "Vacuum full", then the database itself is unlikely to shrink, but the dump (and the restore of it) will be smaller.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Welcome to emergency mode!" Think it is a fsck problem
My computer booted to a black screen with this error message.
Welcome to emergency mode! After logging in,type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, "systemctl default" or ^D to
try again to boot into default mode.
journalctl -xb snippet (what I think is wrong):
-- Unit systemd-fsckd.service has begun starting up.
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: /dev/sdb1 contains a file system with errors, check forced.
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: /dev/sdb1: Inodes that were part of a corrupted orphan linked list found.
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: /dev/sdb1: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY.
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: (i.e., without -a or -p options)
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: fsck failed with error code 4.
juli 09 15:40:16 kim-SSD-Sationary systemd-fsck[414]: Running request emergency.target/start/replace
juli 09 15:40:16 kim-SSD-Sationary systemd[1]: systemd-fsck-root.service: main process exited, code=exited, status=1/FAILURE
juli 09 15:40:16 kim-SSD-Sationary systemd[1]: Failed to start File System Check on Root Device.
-- Subject: Unit systemd-fsck-root.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-fsck-root.service has failed.
--
-- The result is failed.
juli 09 15:40:16 kim-SSD-Sationary systemd[1]: Unit systemd-fsck-root.service entered failed state.
juli 09 15:40:16 kim-SSD-Sationary systemd[1]: systemd-fsck-root.service failed.
juli 09 15:40:16 kim-SSD-Sationary systemd[1]: Starting Remount Root and Kernel File Systems...
-- Subject: Unit systemd-remount-fs.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
I ignored other errors like: ACPI PCC probe failed, nvidia not proprietary, etc.
I can access my PC by pressing Ctrl+D , but it is annoying.
A:
You could run fsck from Ubuntu Live.
Switch on your computer. Boot into a Ubuntu Live DVD/USB (try it without installing).
After it loads, open a terminal by pressing Ctrl+Alt+T
In the terminal, run:
sudo -i
fdisk -l
fdisk will inform you what your partition / (root) is called. In this question it is /dev/sdb1.
Then you should continue by running:
umount /dev/sdb1
fsck -y /dev/sdb1
poweroff
If the umount command complains that sdb1 is "not mounted", that is not a problem. We wanted it to be "not mounted" :).
Remove the DVD/USB. Switch your computer on again, to boot from the SSD.
A:
I don't know if u have solved your problem.
What I did is :
sudo nano /etc/fstab
Then delete what you added there for sdb1 and then run:
sudo systemctl reboot
It says it's corrupted, so I don't know whats up about that, but I hope this could help someone who can't run their Linux.
A:
I just had the case with Emergency mode. In my situation I followed an installation tutorial which suggested to edit some of the options for my mount points in /etc/fstab . By removing the extra options, my server rebooted without problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is there a mime type inconsistency with firefox, chrome?
I was puzzled at first why my files weren't uploading for some users and I found out it was everyone who wasn't using chrome which was the browser I was testing.
Basically I'm doing a file check to make sure they are only able to upload mp3s.
This this was working for chrome, but not firefox.
if ($_FILES['uploaded']['type']=="audio/mp3")
This was working for firefox, but not chrome.
$_FILES['uploaded']['type']=="audio/mpeg"
Could anyone explain why this is happening? I would think both browsers would be able to understand either or... Are there any other browsers I might need to worry about touchy mime types like these?
Edit: If what Pekka suggested is true, what would be the best way to check for a certain mime type?
A:
According to w3schools, audio/mpeg is the correct type. But it doesn't matter, MIME types can vary, you absolutely can't rely on them when checking files. Inconsistencies are the rule, and to be expected.
To identify a MP3 file, maybe the getid3 package can help you:
getID3() is a PHP script that extracts useful information from MP3s & other multimedia file formats.
Edit: IANA has an official list of MIME types here. There is no mention of mp3 there, so this is buggy behaviour on Chrome's part.
Edit 2: Your best bet on server side to determine the MIME type of a file is the finfo extension. It tries to determine the type of a file by "content sniffing", looking for specific characteristics of certain file types in the first few bytes of the data. In this process, MIME types can also vary, but at least they are consistent on the same server, so you won't have browser issues any more.
A:
Each browser may implement the W3c standards slightly differently, much to the chagrin of all developers (#rant)...
Relying on meta information generated by a user/browser is highly unreliable and not recommended. If this is your only security/sanity mechanism then someone wishing to cause harm to your system could manually enter the meta type field with a custom request to == "audio/mpeg" then upload any kind of executable file. If you really want to be sure you must fully examine the data on the server side once it has been uploaded before accepting it into your permanent storage / production system. Or on a less sinister note.. a user with a different browser you have not tested before could want to upload a legit mp3 file but it may not announce its mime type as audio/mpeg or audio/mp3 and then you would deny them access to the system...
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ save and load huge vector
I have a huge vector<vector<bool>> (512x 44,000,000 bits). It takes me 4-5 hours to do the calculation for creating it and obviously I want to save results to spare me of repeating the process ever again. When I run the program again, all I want to do is load the same vector (no other app will use this file).
I believe text files are out of the question for such a great size. Is there a simple (quick and dirty) way to do this? I do not use Boost and this is only a minor part of my scientific app, so it must be something quick. I also thought of inversing it online and store it in a Postgres DB (44000000 records with a 512 bit data), so the DB can handle it easily. I have seen answers such take 8bits > 1byte and then save, but with my limited newbie C++ experience, they sound too complicated. Any ideas?
A:
You can save 8 bits into a single byte:
unsigned char saver(bool bits[])
{
unsigned char output=0;
for(int i=0;i<8;i++)
{
output=output|(bits[i]<<i); //probably faster than if(){output|=(1<<i);}
//example: for the starting array 00000000
//first iteration sets: 00000001 only if bits[0] is true
//second sets: 0000001x only if bits[1] is true
//third sets: 000001xx only third is true
//fifth: 00000xxx if fifth is false
// x is the value before
}
return output;
}
You can load 8 bits from a single byte:
void loader(unsigned char var, bool * bits)
{
for(int i=0;i<8;i++)
{
bits[i] = var & (1 << i);
// for example you loaded var as "200" which is 11001000 in binary
// 11001000 --> zeroth iteration gets false
// first gets false
// second false
// third gets true
//...
}
}
1<<0 is 1 -----> 00000001
1<<1 is 2 -----> 00000010
1<<2 is 4 -----> 00000100
1<<3 is 8 -----> 00001000
1<<4 is 16 ----> 00010000
1<<5 is 32 ----> 00100000
1<<6 is 64 ----> 01000000
1<<7 is 128 ---> 10000000
Edit: Using gpgpu, an embarrassingly parallel algorithm taking 4-5 hours on cpu can be shortened to 0.04 - 0.05 hours on gpu(or even less than a minute with multiple gpus) For example, the upper "saver/loader" functions are embarrassingly parallel.
A:
Process as said before, here vec is the vector of vector of bool and we pack all bit in sub vector 8 x 8 in bytes and push those a bytes in a vector.
std::vector<unsigned char> buf;
int cmp = 0;
unsigned char output=0;
FILE* of = fopen("out.bin")
for_each ( auto& subvec in vec)
{
for_each ( auto b in subvec)
{
output=output | ((b ? 1 : 0) << cmp);
cmp++;
if(cmp==8)
{
buf.push_back(output);
cmp = 0;
output = 0;
}
}
fwrite(&buf[0], 1, buf.size(), of);
buf.clear();
}
fclose(of);
| {
"pile_set_name": "StackExchange"
} |
Q:
I am getting an infinite loop when I run my program. How do I fix it?
Output of the code
This is a finance problem I was working on. I have a loop set up but after it displays all of the correct values, it displays all "0" for every variable infinitely. My Python versions is 3.6.7 running on Ubuntu.
I have tried to set it up so the current_balance is greater than the ending_balance but the problem is still there.
price = float(input("Enter initial price: "))
INTEREST_RATE = 0.12 / 12
DOWN_PAYMENT = price * .9
monthly_payment = 0
ending_balance = 0
interest = 0
principal = 0
month = 0
print("%s%18s%10s%11s%9s%13s" % ("Month", "Current Balance", "Interest", "Principal", "Payment", "End Balance"))
month = 1
current_balance = DOWN_PAYMENT
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal
while ending_balance > 0:
print("%d%18.2f%10.2f%11.2f%9.2f%13.2f" % (month, current_balance, interest, principal, monthly_payment, ending_balance))
month += 1
current_balance = ending_balance
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal
There are no errors, just an infinite loop. The program should be over once ending_balance = 0.
A:
Floating point is your problem. To end the loop use:
while ending_balance >= 0.005:
The current balance is always getting smaller, but you only show two decimal digits.
| {
"pile_set_name": "StackExchange"
} |
Q:
POST new line in JSON for _msearch in ElasticSearch
I'm trying to do a _msearch using ElasticSearch from a browser, and can't figure out how to replicate this CURL command.
curl -XPOST http://localhost.com:9200/ratecards/_msearch -d '
{}
{"query":{"term":{"_id": "1"} }}'
Notice the presence of the new line. That's what I want to replicate.
This is the JavaScript I'm using, it's using Angular's $http which is just a thin wrapper around jQuery's ajax commands.
if (routing) {
address += '?routing=' + routing;
}
var data = '\n';
_.each(payloads, function addPayload(payload) {
data += '{}\n' + JSON.stringify(payload);
})
var config = { data: data, method: 'POST', url: address };
$http(config).success(doStuff);
A:
Finally figured it out, using straight jquery I can do this for my data.
config.data = '\n\n{}\n' + JSON.stringify(myQueryObject)
config.type = 'POST'
Then use
$.ajax(config)
| {
"pile_set_name": "StackExchange"
} |
Q:
BaseFragmentActivityApi16.startActivityForResult(intent, int, Bundle) throwing error when targeting Android O
I started targeting android O in my project I get an error when calling startActivityForResult(intent, int, Bundle) with the error saying it can only be called from group id com.android.support.
Gradle:
compile 'com.android.support:design:26.0.0'
compile 'com.android.support:cardview-v7:26.0.0'
compile 'com.android.support:support-v13:26.0.0'
A:
It's a bit late but I've found a workaround.
I tried ActivityCompat.startActivityForResult(Activity, intent, int, Bundle); and the warning is gone!
A:
Edit:
As per this link, this is a bug.
For a workaround, Add this comment above the line of code which gives the warning:
//noinspection RestrictedApi
Old Ans:
I hope you are not importing wrong library. Fragment support library supports fragment for devices running versions prior to Android3.0.
As per this post in SO
Also remember to use Activity if you are using android.app.Fragment;
use FragmentActivity if you are using android.support.v4.app.Fragment.
Never attach a android.support.v4.app.Fragment to an android.app.Activity,
as this will cause an exception to be thrown.
android.app.Fragment is different than android.support.v4.app.Fragment.
The support library one is annotated @RestrictTo(LIBRARY_GROUP), and also @hide - it's not meant to be a public API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Out of Memory when Uploading an Image
Sometimes when I upload a picture (either with flash or browser uploader), I get a message like (this was with a 1.46MB jpg):
Fatal error: Out of memory (allocated 69206016) (tried to allocate 4000 bytes) in /home/ab64489/public_html/wp-includes/media.php on line 254
I am on a shared host, but the max upload size is 64MB. I've tried uploading other files (I made a zip of some random files, with the archive totaling ~58.1MB, and it uploads and crunches with no problem, so it's not the file size). It also seems that the upload works fine, but when it tries to crunch, then it encounters the error.
I've seen similar problems here and on other sites with no real solutions.
What could be the cause of this issue?
A:
This isn't a Wordpress problem. There's no telling on a shared environment what the culprit might be. You probably don't have access to your php.ini config, nor do we know how many websites your hosting company has jammed on your server.
The very nature of a shared server is that each client shares the resources of that one server. If one website is using massive amounts of resources while you're trying to upload your image, that would certainly affect it.
The only real fix to this is getting onto a more controllable environment. I gave up on shared hosting a long time ago and went with a cloud server from Rackspace. I am in complete control and I don't have to worry about other memory hogs on the same box.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I replace a line of a file using python with wild card
I'm new to python and am using version 2.7
I would like to replace the string inside a file using a wild card that fills out the rest of that line. Here is what I have so far...
This will work and change the file string to second string:
if line == 'This = first string':
line = 'This = second string'
This will not work and the file string will remain as first string:
if line == 'This = *':
line = 'This = second string'
Full Script:
import sys
import shutil
import os
import re
#Assigns tf as a tmp file with the module for appending and writing, and creating the file if it does not exist.
tf = open('tmp', 'a+')
#Assigns f as test.txt
with open('test1.txt') as f:
#Reads the line in the test1.txt file
for line in f.readlines():
#Checks for the line condition
if line == 'This = *':
#Sets the new line condition
line = 'This = second string'
#Replaces the line withe the new build path
tf.write(line)
#Closes the test2.txt file
f.close()
tf.close()
#Copies the changes from the tmp file and replaces them into the test2.txt
shutil.copy('tmp', 'test2.txt')
#Removies the tmp file from the computer
os.remove('tmp')
Latest Code for J.F. Sebastian
test2.txt contents:
blah
This = first string
testing2.py contents:
import os
from tempfile import NamedTemporaryFile
prefix = "This = "
path = 'test2.txt'
dirpath = os.path.dirname(path)
with open(path) as input_file:
with open(path+".tmp", mode="w") as tmp_file:
for line in input_file:
if line.startswith(prefix):
line = prefix + "second string\n"
tmp_file.write(line)
tmp_file.delete = False
os.remove(path)
os.rename(tmp_file.name, path)
Error Message:
C:\Users\james>testing2.py
Traceback (most recent call last):
File "C:\Users\james\testing2.py", line 13, in <module>
tmp_file.delete = False
AttributeError: 'file' object has no attribute 'delete'
Any Suggestions?
A:
I finally found the answer...
test1.txt before Nightly.py executed:
blah
blah
This is a first string
blah
blah
BTW tabs make a difference in the code with notepad++
import sys
import os
import re
import shutil
tf = open('tmp', 'a+')
with open('test1.txt') as f:
for line in f.readlines():
build = re.sub ('This is.*','This is a second string',line)
tf.write(build)
tf.close()
f.close()
shutil.copy('tmp', 'test1.txt')
os.remove('tmp')
test1.txt after Nightly.py executed:
blah
blah
This is a second string
blah
blah
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run a shell command with a sub shell with PHP's exec?
Running this command with PHP's exec gives me syntax errors, no matter if I run it directly or put it in an extra file and run that.
time (convert -layers merge input1.png $(for i in directory/*; do echo -ne $i" "; done) output.png)
I think the problem is that it creates sub shells, which exec doesn't seem to be able to handle.
Syntax error: word unexpected (expecting ")")
A:
try to simplify the command: remove the outer () which you dont need.
you could replace $(for i in directory/*; do echo -ne $i" "; done) by
just directory/* or if you are
worried about empty dirs then $(shopt -s nullglob; echo directory/*)
time convert -layers merge input1.png directory/* output.png
or
time convert -layers merge input1.png $(shopt -s nullglob; echo directory/*) output.png
| {
"pile_set_name": "StackExchange"
} |
Q:
A call to action: what do you want to see here?
As you may have noticed, the big news of the day is that your moderator team has changed. I thought I would take this as an opportunity to issue your community a call to action.
The moderators on any Stack Exchange site have a very important and very difficult job. There are multiple reasons for this, some of which are more obvious than others. Most of our frequent users know that mods are the people who actually handle all the flags. The instant delete, migrate and close powers that come with the moderator diamond get a lot of attention, too.
Parts of the job that don't involve special privileges don't get talked about as much, but are no less important. Mods spend a lot of time—on meta and elsewhere in the community—gently guiding discussion and helping to keep things on track as the community grows. Behind the scenes, they serve as the primary liaisons between you fine people reading this and those of us who work at Stack Exchange.
In short, they're here to help.
It can't all be up to them, though. There's only so much that even the best moderator team can do when a community doesn't have established guidelines.
Over the past months and years, this meta site has seen its share of debates about deletions and content. In many cases, they've been about very specific cases and people. That is not necessarily invalid, but has also been less constructive than it could have been.
Long ago, early Stack Exchange users realized that it's basically never a good idea to "call out" specific users publicly. Admittedly, moderators are a little bit of a special case. Meta is a correct place to "appeal" if you feel a moderator has made a mistake, but even then, it's important to focus on actions, not people and to be civil. (For what it's worth, "focus on what was done rather than who did it" is also general advice that we give to moderators about how to do their jobs.)
What might be more helpful now is looking more broadly at what you do and do not want to see on the site. Do you believe that all answers should require supporting sources, and that there should be a site policy for deleting answers without citations? Start a new meta post proposing that. Or maybe you think language questions should be considered off-topic? Ask a meta question suggesting that.
Be specific. When possible, link to things you've actually seen on the site. For example, I myself got the idea to mention "language questions" just now because I thought this meta question did a good job at what I'm suggesting while keeping the focus on content and site policy, not people.
Please see this as a call to action to start discussions on what actions moderators should take when they see X or Y type of content on the site. Waiting until something happens and then saying "we should have had a policy about that, and if we did, the policy would have been the opposite of what happened"... well, that's too little, too late.
Again, the mods and CMs are here to help, but we cannot dictate. The mods are volunteering their time, and Stack Exchange is providing the servers, but the community guidelines must come from the community itself.
A:
First off all thanks for nicely explaining the job of moderators to the community.
Do you believe that all answers should require supporting sources, and that there should be a site policy for deleting answers without citations? Start a new meta post proposing that.
Yes, that was very essential to make it clear. The discussion Can we revisit the sources required rule? has proved fruitful.
Finally we've posted Official policy for deleting answers that don't cite sources
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an elegant way to check multiple conditions?
I have multiple dropdown menus namely part_no,part_category,make and model. I am trying to display the quantity of vehicle parts in my inventory.
Given that as I become more specific by supplying more values to the dropdown menu, the less type of part has to be displayed. (Something like a filtering)
A good example that I am trying to mimick are the dropdown menus found in this website: http://www.sgcarmart.com/used_cars/listing.php?MMO=Mini&RPG=20&MOD=Austin
Is there a better way of doing the checking(through all possible combinations) rather than doing this:
//Values from my dropdown menus
var carmake= $('#car_make').val();
var carmodel= $('#car_model').val();
var partname= $('#part_name').val();
var partcategory= $('#part_category').val();
if(carmake==data['carmake'])
{
//do something
}
else if (carmake==data['carmake'] && partname==data['partname'])
{
//do something
}
else if (carmodel==data['carmodel'] && partname==data['partname'])
{
//do something
}
else if (carmodel==data['carmodel'] && partname==data['partname'] &&partcategory==data['partcategory'])
{
//do something
} else if (carmodel==data['carmodel'] && partname==data['partname'] &&partcategory==data['partcategory' &&partname==data['partname'])
{
//do something
}
.
.
.
.
.
A:
Put all your test values in an object whose property names are the same as in data. Then loop over all the properties to see if they're all the same:
var search = {
carmake: $("#car_make").val(),
carmodel: $("#car_model").val(),
partname: $("#part_name").val(),
partcategory: $("#part_category").val()
};
var match = true;
$.each(search, function(prop, value) {
if (value !== "" && value != data[prop]) { // only compare if the dropdown was selected
match = false;
return false; // break out of the loop
}
});
if (match) {
// do something
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing text color for Link widget
I am trying to set a specific color to a SWT widget org.eclipse.swt.widgets.Link, but I am not able to override the default color.
Is there a way to change the default color RGB (0, 51, 153) to any specific color.
A:
Link.setForeground sets the normal text color, the actual link color can't be set and uses the OS defaults.
The Forms controls org.eclipse.ui.forms.widgets.Hyperlink and ImageHyperlink used in conjunction with HyperlinkGroup do allow the colors (and underlining) to be set.
| {
"pile_set_name": "StackExchange"
} |
Q:
MongoDB returns nothing?
I am trying to run Perl with MongoDB but I get nothing
use MongoDB;
use Data::Dumper;
my $client = MongoDB::connect("mongodb://admin:admin123@localhost");
my $db = $client->get_database( 'admin' );
my $x = $db->get_collection( 'inventory' );
my $y = $x->find({"item" => "journal"});
print Dumper($y->all);
In the mongo client, I get this
mongo -u admin -p admin123 --authenticationDatabase admin
MongoDB shell version: 3.2.15
connecting to: test
Server has startup warnings:
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten]
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten]
> db.inventory.find({})
{ "_id" : ObjectId("5960dec814a535e879221157"), "item" : "journal", "qty" : 26, "size" : { "h" : 17, "w" : 21, "uom" : "cm" }, "status" : "B" }
{ "_id" : ObjectId("5960dec814a535e879221158"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("5960dec814a535e879221159"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115a"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115b"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("5960e7bb14a535e87922115c"), "foo" : { "a" : [ 1, 2, 3 ] } }
{ "_id" : ObjectId("5960e87614a535e87922115d"), "foo" : { "a" : [ 2, 3, 4 ] } }
{ "_id" : ObjectId("5960e87c14a535e87922115e"), "foo" : { "a" : [ 5, 3, 4 ] } }
>
A:
First of all, you must always start every Perl program you write with
use strict;
use warnings 'all';
and please use better identifiers than $x and $y
You're calling connect as a simple subroutine when it should be a class method. Change
my $client = MongoDB::connect("mongodb://admin:admin123@localhost")
to
my $client = MongoDB->connect("mongodb://admin:admin123@localhost")
A:
You are looking in the wrong database. Actually in the shell you are connecting to the "test" database. See:
connecting to: test
and you never ask to switch the namespace, so that is where the data is.
Change to
$client->get_database( 'test' );
and as noted, it's a lot better if you actually write MongoDB->connect instead, though instance method to class method distinctions at this point have little consequence. You simply chose the wrong database. The "admin" namespace gets automatically switched by the driver for authentication. All you need to do is use the real space where data is.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server : How to track changes value in a column and send notification email for only changed values
I have a table as below that contains dealer codes and status. Every night between 1 and 6am the status column may change for each dealer code. For example today the status of 00141.00062 is operational, but tomorrow it will be deactivated if the store was closed.
Briefly,I would like to track the changes using by stored procedures and send a notification email to me just for the updated values.
Lastly, I do not prefer to create a trigger cause of according to my previous experience it will be affect my main app. Therefore, I will be aprreciate if you can explain how I can do it via stored procedures.
DEALER_CODE STATUS
----------------------------
00141.00062 OPERASYONEL
01033.00061 DEACTIVE
00070.00002 DEACTIVE
00524.00002 DEACTIVE
00387.00020 DEACTIVE
00543.00001 DEACTIVE
00310.00061 DEACTIVE
00247.00062 OPERATIONAL
A:
If your UPDATE statement affects multiple rows at once, you'll get the trigger fired once, but with multiple rows in the Deleted (old values before UPDATE) and Inserted (new values after UPDATE) pseudo tables. Therefore, it's the easiest to just compare those pseudo tables to figure out which rows have changed.
Also: I would strongly recommend to NOT send the e-mail directly from the trigger, since the trigger executes in the context of the UPDATE statement that caused it to fire and thus any delay in sending the e-mail just slows down your main app.
Instead, just add a row into a table, and then periodically (once every night, once every 4 hours or whatever suits your needs) have a separate process grab the new rows from that table and put those into an e-mail.
So the trigger should look something like this:
CREATE TRIGGER trgUpdateStatus
ON dbo.YourTableName
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- insert a row into a "changed" table that will then be
-- used to asynchronously send out e-mails
INSERT INTO dbo.ChangedDealerStatuses (DealerCode, OldStatus, NewStatus)
SELECT
old.Dealer_Code, old.Status, new.Status
FROM
Deleted old
INNER JOIN
Inserted new ON old.Dealer_Code = new.Dealer_Code
WHERE
old.Status <> new.Status
END
| {
"pile_set_name": "StackExchange"
} |
Q:
Chrome Version 32.0.1700.76 m how do I search source files using Devtools
Chrome Version "32.0.1700.76 m". How do I search resources.
Using Devtools, how can I search through all my resources for specific javaScript not knowing which file it's in. This feature used to work and now I can't figure out how to.
A:
On version 32x you may search across all sources by following these steps:
Open Devtools
Press Cmd + Option + F on OSX, or Ctrl + Shift + F on Windows
Enter your search criteria in the search box (see image below)
Press the Enter key
| {
"pile_set_name": "StackExchange"
} |
Q:
Using variables inside of an ArrayList in Java
So I have this piece of code in my Employee class:
public static double HoursWorked;
public static double HourlyWage;
public static double AnnualGrossSalary = HoursWorked*HourlyWage*52;
public double getAnnualGrossSalary(){
return AnnualGrossSalary;
}
Now I've set these to static because I'm using AnnualGrossSalary inside other classes and for some reason they're asking me to make it static, won't argue with compiler (Java newbie!)
And basically in my main class I have:
report.println(ArrEmployee.get(0).getAnnualGrossSalary());
Where this annual gross salary is supposed to be printed in a file. My array list ArrEmployeecontains Employee objects containing variables HoursWorked and HourlyWage.
Now the problem I'm getting is in the report I'm only getting 0.0, when HourlyWage and HoursWorked when they're both > 0... I can't seem to find the problem here, can anyone help?
A:
Shouldn't each Employee have their own salary? Looks like they should not be static.
Something like:
private double hoursWorked, hourlyWage;
public double getAnnualGrossSalary(){
return hoursWorked * hourlyWage * 52;
}
If you also need access to those variables you should use setters and getters to preserve encapsulation.
public void setHoursWorked(double hours){
this.hoursWorked = hours;
}
public double getHoursWorked(){
return this.hoursWorked;
}
You could then use them in an ArrayList like this:
Employee emp = new Employee();
emp.setHourlyWage(12.5);
emp.setHoursWorked(100);
List<Employee> employees = new ArrayList<Employee>();
employees.add(emp);
for(Employee e : employees){
System.out.println(e.getAnnualGrossSalary());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I continue once I beat level 7-7?
I am playing Donkey Kong Country Returns and I'm on level 7/7. When I beat that world it won't open a road to the new stage instead it opens a road that backtracks to level 7/5. Why? How do I continue?
A:
Levels 7-5, 7-6, and 7-7 have 3 secret switches that must be activated to continue to level 7-R.
As per the level 7-5 description from IGN:
SECRET SWITCH
Ground pound where you see the downward pointing arrow made out of bananas. The wheel will turn and a hatch will open. Down the hatch with you and pound the big red button you find inside. What's it do? Well, when you hit the big red buttons in this and the two subsequent levels, level 7-R opens up. Needless to say, if you don't unlock this level, you're not going any further in this game than 7-7.
For level 7-6:
SECRET SWITCH
Hit the blue circle by the purple balls of electricity then run back to the left and ground pound the broken bit of flooring. The Blast Barrel underneath will lead you to this level's big red button.
For level 7-7:
SECRET SWITCH
Ground pound the metal slab between the two flame jets to reach this level's big red button.
| {
"pile_set_name": "StackExchange"
} |
Q:
UILabel, TextField with overstrike character
I want to create a UILabel or UITextField with an overstruck character. (not a strikethru dash)For example:
is this possible in Swift 4/5 (Not SwiftUI). The hope is that this will roll into a text to show a correction and that the user adapting size will size as appropriate.
Note, I referenced several other questions and haven't found one that addresses character over character; only strikethru.
A:
You can use NSAttributedString, and set the below attribute:
let att = NSMutableAttributedString(string: "kfill")
att.addAttribute(.kern, value: -7, range: NSRange(location: 0, length: 1))
label.attributedText = att
You can change the range and value if you wish to achieve different results.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I use the WSDL file that I got?
Possible Duplicate:
How to use a WSDL file to create a WCF service (not make a call)
I need to use a web service in my application.
I have a WSDL for the web service, but I don't know how to use it or how to call and send info to the web service method.
Someone can help me here?
A:
See http://msdn.microsoft.com/en-us/library/ms181854%28VS.90%29.aspx
"Create a .NET Web Service provider endpoint from a WSDL file."
| {
"pile_set_name": "StackExchange"
} |
Q:
List Field Name Character Limit
I'm wanting to give a field a custom name that links it to a row in a separate list. The issue is the fields need to be linked to a string that is a full sentence. One solution would be to have the full sentence as the field name, but this of course wont work if the sentence is longer than the character limit. What is the character limit of a Sharepoint List Field?
Edit:
Sorry, should've been more clear. I was referring to the TITLE of the field not the actual data stored in that column. A comment to one of the answers answered my question, it is 128 characters. Thank you.
A:
The character limit would be 255 characters for Name / Title. But it is recommended to have Name shorter as the Name is going to be used in queries if required.
Let me know if my assumption is wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Save the select when reload
How to save my selected option in the selection box, when i reload the page with javascript location.href ?
A:
The page itself has no state and won't remember anything the user did when you reload it.
If you are using a server-side language as well you can save the value somewhere on the server (a database or simple flat file), but if you just have javascript and can't save the value to the server you can take a look at saving the value to a cookie and then restoring that value when the page reloads.
If you're feeling really adventurous, HTML5 also gives you the ability to save content to something called local storage, although this is only supported by more advanced browsers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is ideal band pass filter (brick wall filter) linear phase?
I'm very new in digital signal processing.
I have multiple sensors and the way I filters the signals in post processing is:
take FFT of the signals.
put zero on out range of interesting frequency (like brick wall filter).
take IFFT of the spectrum.
I repeat this for each sensor, and compare the phase relation between them in time traces. Thus, the phase must not shift during the filtering process. I wonder the above method distorts the phase or not. Is the ideal band pass filter linear phase?
A:
Assuming you are refering to LTI (linear time-invariant) systems to implement the filter.
The impulse response $h[n]$ of the ideal brickwall bandpass filter :
$$H(\omega) = \begin{cases} 1 ~~~,~~~ |\omega-\omega_c|<W \\ 0 ~~~,~~~\text{o.w.}\\ \end{cases}$$
is
$$
h[n] = 2 \cos(\omega_c n) \frac{ \sin(W n) }{ \pi n }
$$
which is real and even symetric about origin; i.e., $h[n] = h[-n]$, hence it's a zero-phase (in the passband), but noncausal filter.
When this impulse response is truncated and shifted right enough to make it causal: $h_c[n] = h[n-d]$ then the resulting bandpass filter will be linear phase in the passband:
$$ H_c(\omega)= e^{-j\omega d} H(\omega)$$ with a linear phase term of $$\phi(\omega) = -\omega d$$
The phase is not defined for those frequencies where the frequency response is zero.
Note that the truncated filter is no more the ideal filter. Also note that you cannot shift the ideal filter to make it causal (requires infinite shift). And finally note that the zero-phase ideal filter is also a linear phase filter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java web service tomcat not able to find a shared lib
I'm using eclipse and I have a java web service (rest jax-rs)
I also have another java project that contains a class Employee
In the web service project and I have gone to Java Build Path/Projects and added the project containing the Employee class.
No compilation erros.
In the web service I have a method like this:
@GET
@Path("{extra}")
public Employee person(@PathParam("extra") String cus) {
Employee p = new Employee();
p.setName(cus);
return p;
}
When Run (it seems to starts tomcat server) I get the following error
java.lang.NoClassDefFoundError: shared/Employee
java.lang.Class.getDeclaredMethods0(Native Method)
java.lang.Class.privateGetDeclaredMethods(Unknown Source)
java.lang.Class.privateGetPublicMethods(Unknown Source)
java.lang.Class.getMethods(Unknown Source)
com.sun.jersey.core.reflection.MethodList.getMethods(MethodList.java:77)
com.sun.jersey.core.reflection.MethodList.<init>(MethodList.java:64)
com.sun.jersey.core.reflection.MethodList.<init>(MethodList.java:60)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:116)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:743)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1518)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1295)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:167)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:773)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:769)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:769)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:764)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:488)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Obviously everything works when the Employee class is defined in the same project.
What am I missing?
A:
That Java project needs to end up as JAR in /WEB-INF/lib folder of the deploy in order to be available in the webapp's runtime classpath. Only adding the Java project as project to the build path of the web project is not sufficient. This only covers the web project's compiletime classpath, not the webapp's runtime classpath.
You need to add the Java project in Deployment Assembly of the web project to get it to end up as JAR in /WEB-INF/lib.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move windows of dimension range to Workspace 2?
I have many figures of widthxheight (550-570)x(465-486) at the southwest logically set there by Matlab's movegui() function.
I would like to open all those southwest windows of the size range in an external display or in Workspace 2.
Meuh's command shows those figure dimensions width x height, their hex codes and titles where I would like to move windows of size 560 x 475 for width x height, respectively, to Workspace 2
masi@masi:~$ wmctrl -l -G
0x01c0000b 0 0 0 3840 1080 masi Desktop
0x01e00002 0 0 54 1920 1023 masi Edit - Unix & Linux Stack Exchange - Google Chrome
0x02200006 0 2088 333 1608 501 masi masi@masi: ~
0x0280003d 0 1920 78 1920 1041 masi MATLAB R2016a - academic use
0x02800ac6 0 11 113 568 465 masi Figure 1: data gray all 4
0x02800af2 0 687 113 560 475 masi Figure 2: data gray top half (1/2)
0x02800aff 0 1364 113 560 475 masi Figure 3: data gray top #1 (1/4)
0x02800b16 0 1364 621 560 475 masi Figure 4: Time domain
0x02800b2a 0 11 631 568 465 masi Figure 5: Memory/... Monitoring
0x02800b31 0 683 631 568 465 masi Figure 6: data Size(I) monitoring
0x02800b3b 0 11 621 560 475 masi Figure 7: Histograms
0x02800b85 0 774 594 386 28 masi Press SPACEBAR to continue
Doing meuh's command gives the correct number of wmctrl commands but individual commands do not have any effect (beware different hex-codes here than above because different iteration)
masi@masi:~$ wmctrl -l -G |
> awk '$0~/^0x/{ winid=$1; width=$5; height=$6;
> if(width>=550 && width<=570 && height>=465 && height<=485)
> printf "wmctrl -i -r %s -t 2\n",winid
> }' | sh -x
+ wmctrl -i -r 0x03200120 -t 2
+ wmctrl -i -r 0x03200149 -t 2
+ wmctrl -i -r 0x0320015f -t 2
+ wmctrl -i -r 0x03200173 -t 2
+ wmctrl -i -r 0x03200188 -t 2
+ wmctrl -i -r 0x0320019f -t 2
+ wmctrl -i -r 0x032001b2 -t 2
Why the commond + wmctrl -i -r 0x03200120 -t 2 putting the window to Workspace 2? What is the symbol + there?
I do wmctrl -r 1 -t 2 but nothing, TODO specify somehow dimensions here.
How can you move windows of size 560x475 to Workspace 2?
How can move windows of size (550-570)x(465-485) to Workspace 2?
OS: Debian 8.5 64 bit
Linux kernel: 4.6 of backports
Matlab: 2016a
Window manager: Gnome 3.14
Hardware: Asus Zenbook UX303UA, Asus PC
Other sources: Commandlinefu search wmctrl does not bring anything relevant
A:
There is no supported working solution for Gnome 3.14 in Debian 8.5.
Let's hope the next release of Gnome at Q1-Q2 2017 will help the case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to integrate JSS to WordPress
WordPress is all about PHP and JSS is... Js. And I want to use JSS but I got trouble in interacting between generated HTML by PHP and CSS from JSS. Like in the official example (https://codesandbox.io/s/z21lpmvv33), JSS generate a version of CSS classes. This means I cannot set fixed classes in WordPress. What should I do?
A:
JSS is designed for dynamically generated HTML rendered by JS. It's purpose is to generate unique identifiers for class names to prevent collisions in naming.
If you want to have static CSS generated it's easier to look at LESS\SASS\SCSS and build them with gulp, or with Less straight(http://lesscss.org/usage/).
Here's heavily modified example which does what you might want.
https://codesandbox.io/s/core-jss-playground-84yve
All is done using jss-plugin-global
Compare it to initial code in how CSS rules are defined with @global to make them rendered without enhancing class names with dynamic parts.
Also look at https://cssinjs.org/jss-plugin-global docs and nested plugin docs https://cssinjs.org/jss-plugin-global as it's useful.
And probably you'll find it useful to use JSS-CLI https://cssinjs.org/cli/
So with JSS CLI you'll be able to complile JSS into static CSS and serve it via wp_enqueue_style() as normal css file.
Or you can build your JS with JSS file from ES6 syntax with webpack+babel and then use wp_enqueue_script() and your built JS will compile inner JSS and inject into page just like in example.
| {
"pile_set_name": "StackExchange"
} |
Q:
new sequence column and want to make it is a primary key
I wanted to make a add a new sequence column and want to make it is a primary key.I am trying with
create sequence rid_seq;
alter table test add column rid integer default nextval('rid_seq');
But this sometimes doesn't give unique sequence?ANy other way?Any help is appreciated
A:
sequence does not have attribute unique or not, so you have to add unique index on the column, that uses sequence values. In your case (you want to add a primary key) just use "shortcuts":
alter table test add column rid bigserial primary key
| {
"pile_set_name": "StackExchange"
} |
Q:
Efficently querying multi language categories and category items
So I have a bit of a server response time issue - which I think is caused due to obsolete queries. One major query chain that I have takes up to 370ms, which is obviously causing an issue.
Here are the requirements:
5 Different languages
There are several Product Categories (i.e. Cat 1, Cat 2, Cat 3, etc.)
Categories displayed depend on language. For example whilst category 1 is displayed in all languages, category 2 is only displayed in Germany and France but not in the UK
Each category contains x number of items (has_many belongs_to relationship). Again some items are displayed in certain languages others are not. For example even category 2 is displayed in France and Germany, only in Germany you can buy Item 1 and hence Item 1 should not be displayed in France but Germany.
The categories and items do have boolean fields named after the locale. This way I can set via flag whether or not to display the category and item in a specific language.
My solution:
Building the solution is quiet easy. In controller I read out all the categories for the current locale:
application_controller.rb (since it is used on every single page)
@product_categories = ProductCategory.where("lang_" + I18n.locale.to_s + " = ?", true)
And in the view (the navigation) I do the following:
layouts/navs/productnav.html.haml
- @product_categories.each do |category|
...
- category.products.includes(:product_teasers).where("lang_" + I18n.locale.to_s + " = ? AND active = ?", true, true).in_groups_of(3).each do |group|
...
The issue with this solution is that each time I fire a lot of queries towards the database. Using "includes" does not solve it as I can not specify what items to pull. Furthermore I require the in_groups_of(3) in my loop to display the items correctly on the page.
I was also looking into memchached solutions to have the queries cached all together - i.e. Dalli however, this would require me to change a lot of code as I am guessing I would require to query all categories for each language and cache them. In addition to it I have to query each item for each langugage depending on language and store that somehow in an array ?!
My question:
How to approach this ? There must be a simpler and more efficient solution. How to efficiently query respectively cache this?
Thank you!
UPDATE:
As requested here are my two Models:
1.) ProductCategory
class ProductCategory < ActiveRecord::Base
translates :name, :description, :slug, :meta_keywords, :meta_description, :meta_title, :header, :teaser, :fallbacks_for_empty_translations => true
extend FriendlyId
friendly_id :name, :use => [:globalize, :slugged]
globalize_accessors :locales => [:at, :de, :ch_de, :ch_fr, :fr, :int_en, :int_fr], :attributes => [:slug]
has_paper_trail
has_many :products, :dependent => :destroy
validates :name, presence: true, uniqueness: { case_sensitive: false }
default_scope { includes(:translations) }
private
def slug_candidates
[
[:name]
]
end
end
2.) Product
And every product Category can have 0..n Products, and each Product must belongs to one category.
class Product < ActiveRecord::Base
translates :slug, :name, :meta_keywords, :meta_description, :meta_title, :teaser, :power_range, :product_page_teaser, :product_category_slider_teaser, :fallbacks_for_empty_translations => true
extend FriendlyId
friendly_id :name, :use => :globalize
before_save :change_file_name
searchable do
text :name, :teaser, :product_page_teaser, :product_category_slider_teaser
integer :product_category_id
end
belongs_to :product_category
has_many :product_teasers, :dependent => :destroy
has_many :product_videos, :dependent => :destroy
has_many :product_banners, :dependent => :destroy
has_many :product_documents, :dependent => :destroy
has_many :product_tabs, :dependent => :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :references
has_and_belongs_to_many :contacts
accepts_nested_attributes_for :product_teasers, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :product_tabs, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :product_videos, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :product_banners, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :product_documents, :reject_if => :all_blank, :allow_destroy => true
has_paper_trail
validates :name, presence: true, uniqueness: { case_sensitive: false }
default_scope {includes(:translations)}
.... a lot more going on here ...
end
Please note: That category contains language flags (booleans), i.e lang_at, lang_de, lang_fr, etc. and if set then this category is displayed in that particualar language. SAME applies to products, as certain products are not displayed in all langauges altough the category might be.
Examples:
@product_categories = ProductCategory.where("product_categories.lang_" + I18n.locale.to_s + " = ?", true)
@products = Product.where("product_categories.lang_" + I18n.locale.to_s + " = ?", true)
I skipped any includes on purpose above - it is just to demonstrate the language logic.
A:
UPDATE
The system have spent a lot of times to loop data in nested loop. Avoid to fetch data in nested loop. You have to use join or includes to catch your data more effective. For example:
Controller
@products = Product.includes(:product_category).where("product_categories.lang_" + I18n.locale.to_s + " = ? AND product_categories.active = ?", true, true).group_by(&:category)
View
- @products.each do |category, products|
<%= category.name %>
- products.each do |product|
<%= product.title %>
It needs to fix with your necessary code. I just help the main query. For example: active = ? is for products field or product_categories field. I hope It can help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
messed up partitions during mint installation
I was using a windows10/Ubuntu 14 LTS dual-boot, when I decided to swap out Ubuntu for Mint. I downloaded the .iso, made a Live-USB, started Mint from the USB, pressed install and the installer told me there was Ubuntu on my system already.
I clicked to replace Ubuntu with Mint, got to the next page, was unsure whether I would keep my dual boot after the installation so I went back to the page were the installer told me that I have Ubuntu installed already.
Just that now the installer tells me, that there is no OS found on the harddrive! No actual installation of Mint happened yet, it was just setting things up.
I thought this is a bug, tried to restart, got some kind of blue screen from windows 10 (can't start from this, need to rescue), went into UEFI and put grub back to the top of the booting hierarchy.
Now grub doesn't boot neither, telling me "no partition found" and gives me the grub rescue command line, that didn't really help me.
What happened? Did I mess up at some point? can I go back to the setting I had? The only way to boot right now is from the Mint Live-USB and when opening gparted, I only see 3 partitions:
/dev/sda1 fat32 SYSTEM 512 MiB
/dev/sda2 unknown 244 MiB
/dev/sda3 lvm2 pv mint-vg 930.77 GiB
Whereas before that, the installation had like 10 partitions, now they all seem kind of merged into the sd3 with the weird file system.
So, please, can somebody help me out of this mess? :(
A:
Unfortunately, somewhere on the way, you decided to encrypt your home directory, so basically, you need to restore from your most current system back-up.
Sorry to be the harbinger of bad news
| {
"pile_set_name": "StackExchange"
} |
Q:
iis url redirect http to non www https
i need to redirect from
www.domain.de to https://domain.de
-works
http://www.domain.de to https://domain.de
-works
http://domain.de to https://domain.de
-does not work
rewrite>
<rules>
<rule name="Imported Rule 1" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
</conditions>
<action type="Redirect" url="https://{C:1}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
A:
I think this will work for you, the search pattern has the optional www and redirects using the back reference C:2, the rule has a condition to only run against non https.
This is the pattern:
"^(www\.)?(.*)$"
where:
{C:0} - www.domain.de
{C:1} - www.
{C:2} - domain.de
Here's the rule in full:
<rewrite>
<rules>
<rule name="SecureRedirect" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTPS}" pattern="off" />
<add input="{HTTP_HOST}" pattern="^(www\.)?(.*)$" />
</conditions>
<action type="Redirect" url="https://{C:2}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
| {
"pile_set_name": "StackExchange"
} |
Q:
Como definir o input de um programa no Windows?
Uma pergunta simples. Nos sistemas *NIX, você pode fazer o seguinte:
cat input_do_programa.file
"texto exemplo"
input_do_programa.file > meu_programa.exe
Há um equivalente para Windows?
A:
O programa a ser executado deve vir primeiro. < para redirecionar a stream de entrada padrão (stdin) e > para redirecionar a stream de saída (stdout) (>> para acrescentar ao final do arquivo). Para redirecionar a saída de erro padrão (stderr) utilize 2>:
programa.exe < entrada.txt > saida.txt 2> erro.txt
Não é necessário redirecionar tanto entrada quanto saída, pode ser apenas um dos dois.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i browse file without uploading in GXT?
i'm beginner with GXT and i'm wondering if there is a way to parse a file and extract some informations without uploading it.
i created a formpanel that contains an uploadFile form but i don't know waht's next, how to get the complete path of the file so i can read/write with java io or how to retrieve the file or is there an alternatif solution, thank you.
Best Regards.
A:
You can do it in some modern browsers using bleeding edge HTML5 apis for which you would need to use GWT JSNI code. There are no api's from GWT team as is.
HTML5 FileReader
FileReader includes four options for reading a file, asynchronously:
FileReader.readAsBinaryString(Blob|File) - The result property will contain the file/blob's data as a binary string.
FileReader.readAsText(Blob|File, opt_encoding) - The result property will contain the file/blob's data as a text string.
FileReader.readAsDataURL(Blob|File) - The result property will contain the file/blob's data encoded as a data URL.
FileReader.readAsArrayBuffer(Blob|File) - The result property will contain the file/blob's data as an ArrayBuffer object.
Example of GWT wrapper over these -
https://github.com/bradrydzewski/gwt-filesystem
You can read about it more from here - How to retrieve file from GWT FileUpload component?
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Convert String Date to Month Name Year (MMM yyyy)
I am new to Java. I am trying to convert date from string to MMM yyyy format (Mar 2016). I tried this
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy");
String month_name = month_date.format(cal.getTime());
System.out.println("Month :: " + month_name); //Mar 2016
It is working fine. But when I use
String actualDate = "2016-03-20";
It is not working. Help me, how to solve this.
A:
Your format must match your input
for 2016-03-20
the format should be (just use a second SimpleDateFormat object)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Full answer
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String actualDate = "2016-03-20";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name); //Mar 2016
Using java.time java-8
String actualDate = "2016-03-20";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
LocalDate ld = LocalDate.parse(actualDate, dtf);
String month_name = dtf2.format(ld);
System.out.println(month_name); // Mar 2016
A:
Try this code:
DateFormat df = new SimpleDateFormat("dd-MMMM HH:mm a");
Date date = new Date(System.currentTimeMillis());
String infi = df.format(date);
And the output should be:
11-May 4:47 PM
A:
tl;dr
YearMonth.from(
LocalDate.parse( "2016-03-20" )
)
.format(
DateTimeFormatter.ofPattern(
"MMM uuuu" ,
Locale.US
)
)
Mar 2016
java.time
Avoid the troublesome old date-time classes. Entirely supplanted by the java.time classes.
YearMonth
Java has a class to represent a year and month. Oddly named, YearMonth.
LocalDate ld = LocalDate.parse( "2016-03-20" ) ;
YearMonth ym = YearMonth.from( ld ) ;
Define a formatting pattern for your desired output.
Specify a Locale. A Locale determines (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM uuuu" , Locale.US ) ;
String output = ym.format( f ) ;
Mar 2016
You could use that formatter on the LocalDate. But I assume you may have further need of the year-month as a concept, and so the YearMonth class may be useful.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
| {
"pile_set_name": "StackExchange"
} |
Q:
using jQuery to copy column specific form values
I've used jQuery before to copy billing addresses to shipping addresses, but if I am dynamically generating form rows with various values from PHP, how do I set up the form so that upon a checkmark, a recommended item quantity will be automatically copied just to the quantity of the same item?
Here is the basic version of the billing/shipping copy script.
<script src="../Scripts/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("input#same").click(function()
{
if ($("input#same").is(':checked'))
{
// Checked, copy values
$("input#qty").val($("input#same").val());
}
else
{
// Clear on uncheck
$("input#quantity").val("");
}
});
});
</script>
And here is the PHP code dynamically gathering items with their suggested quantity.
while( $row = mysql_fetch_array($histresult) )
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td>'.$suggested_quantity.'<input id="same" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>';
echo '<td><input name="qty" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
}
For each item, a suggested wholesale quantity based on a user's favorite items is retrieved from the database. There is also a text field so that they can enter any amount they want before sending it to their cart. But if they check the checkbox, I want it to copy that value to the text field.
No only does this code not seem to do the trick, the difference between this and the billing/shipping copy is that now I'm dealing with a dynamic number of fields. How do I make each individual row achieve this task?
A:
Using jQuery, you would essentially want to grab the suggested value from checkbox and put it in the other form element. Let's say this is your HTML:
<table>
<tr>
<td>
100 <input id="check-1" name="same" type="checkbox" value ="100"/>
<input id="qty-1" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-2" name="same" type="checkbox" value ="100"/>
<input id="qty-2" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-3" name="same" type="checkbox" value ="100"/>
<input id="qty-3" name="qty" type="text"size="4" maxlength="4">
</td>
</tr>
</table>
And then this would be your javascript/jQuery:
// Bind click event to ALL checkboxes
$("#same-*").live("click", function(e) {
// Only change it if box is checked
if( $(this).is(":checked") )
{
// Get suggested value
suggested_val = $(this).val();
// Place in next element (textbox)
$(this).next().val(suggested_val);
}
)};
I haven't tested this, but this is basically how it would work.
In your PHP, you would want to dynamically make those ID numbers so each row uses a unique ID. This is usually simple enough to match to your database row id.
<td>'.$suggested_quantity.'<input id="same-' . $row->id . '" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can XHTML and HTML class attributes value start with a number?
Can XHTML and HTML class attributes value start with a number?
A:
No. They have to be SGML names. They "must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
However, class names that start with a number are supported by IE.
EDIT: meder pointed out that you can use Unicode characters and they seem to work in all browsers. I don't know if it complies with the specifications, but it does seem to validate.
See http://css-tricks.com/unicode-class-names/ and http://snook.ca/archives/html_and_css/unicode_for_css_class_names
A:
No, they cannot. They must begin with a letter. Some browsers may erroneously support them, though.
EDIT: You can start off with unicode escape points and specify the code for a number.
EDIT #2: Test case http://work.arounds.org/sandbox/66/run
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the equivalent to "I appreciate it" ?
Bonjour, je suis français et me demande quel serait un bon équivalent à l'expression "appreciate" ou "I appreciate it".
Hello, I am french and wonder what would be an equivalent to the expression "appreciate" or "I appreciate it".
La situation où l'expression est utilisée est telle que suit :
An example of a situation would be as follows :
Person A : This book ? No, you can keep it. I'm sure you will love it!
Person B : Thanks man, appreciate it/I appreciate it.
D'avance merci.
Thanks in advance.
A:
Voici quelques suggestions:
Ça me fait plaisir
C'est très aimable [à vous]
C'est très gentil
Note: on entend parfois j'apprécie mais c'est considéré comme un anglicisme :
OQLF:
Le verbe apprécier est parfois employé de manière incorrecte pour exprimer un souhait, une intention ou encore un sentiment de gratitude ou de reconnaissance. Ces emplois sont empruntés à la forme anglaise to appreciate. Pour exprimer un souhait ou une intention, on peut choisir parmi plusieurs autres verbes, par exemple souhaiter, aimer ou désirer. Pour exprimer la gratitude ou la reconnaissance, on pourra employer, entre autres, les locutions savoir gré ou être reconnaissant.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I determine if a function is onto if the codomain is not specified?
A question asks "Is $f(x)=x^2$ an onto function or not?" Here the domain and codomain are not mentioned specifically, so what codomain should I consider?
A:
In a case like this, I would assume the domain and codomain are intended to be the real numbers unless you are taking a complex analysis class.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the probability density function of a set of random variables
If I have a set of random variables $X_1$, $X_2$, $X_3$, ..., how do I find the probability density function of them?
All I know is that $0 \leq X_i \leq 1$ and they are continuous values.
I have tried several solutions:
I tried first sort them first, then gradually work out the CDF, then work out PDF.
I also tried binize them to that make them into a categorical data and then get PDF by calculating the probabilities of each category.
However, I need the solution to be as a function of $X_i$ and this function has to be differentiable, but neither sorting nor bining is a differentiable computation.
Does such a solution even exist?
A:
There is no way to be sure what distribution gives rise to your data.
First, there is no assurance that your data fit any 'named' distribution.
Second, even if you guess the correct parametric distribution family, you still have
to use the data to estimate the parameters.
Here are several approaches that might be useful.
First, you might see whether a member of the beta family of distributions
is a reasonable fit to your data. These distributions have support $(0, 1)$
and two shape parameters $\alpha > 0$ and $\beta > 0.$ Roughly speaking,
these determine the shape of the density curve near 0 and near 1, respectively.
It is possible to estimate $\alpha$ and $\beta$ from data. One way is to
pick parameters that match the sample mean and variance (method of moments
estimation). See the Wikipedia article on 'beta distribution' for particulars.
Below is a histogram of a sample of 1000 observations simulated according
to the distribution $Beta(\alpha = 1, \beta = 10)$ along with the
density function (solid blue curve) of that particular distribution.
(I used R statistical software and show the R code. R is available free of charge at
www.r-project.org for Windows, Mac and Linux.)
x = rbeta(1000, 5, 10) # generate fake data
mean(x); sd(x) # sample mean and SD
## 0.3320269
## 0.1163734
hist(x, prob=T, col="skyblue")
curve(dbeta(x, 5, 10), lwd=2, col="blue", add=T) # pop density curve
lines(density(x), lwd=2, lty="dotted", col="red") # density est from data
It takes a lot of data to get really close estimates of the parameters.
For example, here the sample mean is 0.3320 while the population mean is .3333.
I will let you check how closely the sample and population variances
match.
A second method is to use a density estimator of your data. (See Wikikpedia
on 'density estimator' or google 'KDE' for 'kernel density estimator'.)
The last line of code puts the dotted red density estimator onto the plot
above. The function density(x) produces $(x,y)$ coordinates. These
may be of use if a digitized approximation to the density is useful.
By sorting the data, it seems to me that you are making an "empirical
distribution function" (ECDF). ECDFs tend to match theoretical CDFs
better than density estimators match histograms, partly because information
is lost when data are sorted into bins to make a histogram.
For a continuous distribution, you could try taking differences of
small intervals in an ECDF to approximate the PDF, but I think density
estimation is easier to use.
Below is the ECDF of the data generated above (heavy black 'stairstep',
increasing by $1/n$ at each sorted datapoint), along with the population
CDF (thin blue curve). Black tick marks at the horizontal axis show the
locations of individual observations.
plot(ecdf(x), lwd=3)
curve(pbeta(x, 5, 10), col="blue", add=T)
rug(x)
You do not say why you want to know the PDF for your data. By googling some of the terminology I have used here, you may be able to
find a solution that matches your goals better than anything in my example.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make [uc_order] token globally available?
In admin/config/people/accounts , I want user password in welcome mail.
Currently it is
username: [user:name]
password: Your password
I want this
username: [user:name]
password: [uc_order:new-password] // this token is already available in order setting page admin/store/settings/checkout
Now question is is there anyway to make uc_order token available in user account setting page?
A:
I think you are going about this the wrong way.
You can make the uc_order token globally avaialbe, but it would be a bit messy since some users wont have an order and other people have more than one order.
Instead you should use hook_mail_alter to actually insert the password from the order. You could search for [uc_order:new-password] and if found load the correct order and replace the value with the value from the order.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch: Boost the field for specific values using Mappings
I am using elasticsearch Version 5.6. I would like to like to boost the field "type" when it's value is video ( "contentType": "video"). Currently my mappings looks like this:
PUT my_index
{
"mappings": {
"my_type": {
"properties": {
"title": {
"type": "text",
},
"contentType": {
"type": "text",
"boost": 4
}
}
}
}
}
How can I specify that only boost by 4 where contentType is equal to "video"? I know it can be done on query side, but I would like to do it in my mappings. Is it possible? Any help is appreciated
A:
In elastic 2.x is possible, https://www.elastic.co/guide/en/elasticsearch/reference/2.3/index-boost.html
It's deprecated since 5.0 https://www.elastic.co/guide/en/elasticsearch/reference/6.0/mapping-boost.html. Take a look to the section why index time boosting is a bad idea
| {
"pile_set_name": "StackExchange"
} |
Q:
Binding a method to another class
class A(object):
def a(self, b=1):
print 'Up'
d = {1 : a}
def b( self ):
print self.d[1]
print self.b
print self.d[1].__get__( self, A )()
# print self.d[1]()
class B( object ):
def a( self ):
print 'here??'
return 10000
d = {1 : a}
def b( self ):
print 'hurray'
o = A()
o.b()
b = B()
type( o ).__dict__['b'].__get__( b, type( b ) )()
Hi Folks,
I was going through Python: Bind an Unbound Method? and http://users.rcn.com/python/download/Descriptor.htm and trying to experiment on my learning.
But, I have hit some new doubts now:-
In the last line of my code, I'm able to use __get__ with b object and instance: type(b). This only works if method b is defined in class B. Why is it so?
Even though the last line requires me to provide a method b in class B, still the method b in class A gets called. Why is it so?
To my utter surprise, after the above step, I notice that the method a of class A is not called by the code of method b of class A; instead, it calls the method a of class B. Why is it so?
I'm quite confused after seeing this behaviour. I might also need to learn more on descriptors. But, it would be a great help if you could answer my doubts
A:
In the last line of my code, I'm able to use __get__ with b object and instance: type(b). This only works if method b is defined in class B. Why is it so?
You have to define a method b in class B, because in A.b you have print self.b. Here, self is an instance of the B class, so self.b means "the b method belonging to this B", not "the b method belonging to the class that this method exists in". If you delete print self.b, then the code will work even if B has no b.
Even though the last line requires me to provide a method b in class B, still the method b in class A gets called. Why is it so?
A.b is being called because you are explicitly accessing it with type( o ).__dict__['b']. Whether you bind that method to an A instance or a B instance doesn't matter; it's still A.b.
To my utter surprise, after the above step, I notice that the method a of class A is not called by the code of method b of class A; instead, it calls the method a of class B. Why is it so?
Even though b belongs to the class A, the self you pass to it is still an instance of the B class. Any attributes you access on that self will be B attributes, and any methods you call on it will be B methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS app not using using Base Internationalization language
I am adding localization to an iOS application with Xcode 8. I have base internationalization set with English as the language. The app also supports spanish (es), french (canada), and portuguese (brazil). When I set the device language to ES, fr-CA, or pr-BR the appropriate language is displayed in the app - great.
However, if the current device language is ES, fr-CA, or pt-BR > I shut down my app > change the device language to German > start the app back up...
Rather than the app falling back to English (Base), it uses the language I just had set. For example, if I had the app open in fr-CA, shut down the app and change to German, when I open the app back up the language displayed is fr-CA.
Unless I missing something here, I am expecting English to be displayed since the app does not support the German language.
One other thing to note - when i change the device language to English, the app displays English to the user.
Can anyone shed light on this issue? Thanks.
A:
iOS determines the fallback language by the user's most preferred language.
So if there's a localization available for one of the user's preferred language it will automatically use this localization. Only if none of the user's preferred languages is supported by your app it will use your app's development region.
Source: Technical Q&A QA1828 - How iOS Determines the Language For Your App
Here's a similar question with some solutions by other users: Localizing strings in iOS: default (fallback) language?
| {
"pile_set_name": "StackExchange"
} |
Q:
JSON passed from Python (Flask) into JavaScript is displaying on screen
I am passing a JSON from a Python back-end into my front-end JavaScript where I'm running a webGL (three.js) animation. The JSON holds numerical values that determine what happens in the animation. My problem is that while I have a basic ajax request working, the JSON is being printed to the screen (in lieu of the animation) rather than becoming a variable I can iterate through to control aspects of the animation. The two halves of the call are shown below.
I asked a related question to this one before and got some great help, but am obviously still missing a piece of the puzzle. I've been reading docs and all sorts of sources, yet need a nudge in the right direction to finally get this working. Any help is appreciated!
In the python backend:
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list
@app.route('/')
def index():
motifs = get_motif_list(10)
# The first version of the return below successfully sends data, yet it is printed to the
# screen, rather than being stored as data in a variable.
return Response(json.dumps(motifs), mimetype='application/json')
# This version of the return does not work:
# return render_template("index.html", motifs = motifs)
In the JavaScript (note that the console.log sanity checks don't work - I have no idea why:
function foo() {
var array_data;
$.ajax({
type: "GET",
url: "/",
dataType: "json"
});
request.done(function(JSON_array) {
array_data = JSON.parse(JSON_array)["array"]
console.log(array_data); // sanity check - doesn't work
});
return array_data;
};
var array = foo();
console.log(array); // sanity check - doesn't work
UPDATE
With help from the advice below, I'm pretty close to having this off the ground. The JSON is no longer printing to the screen (an issue caused by the Flask return), and I've solved a multifunction callback issue I discovered along the way. However, I am now getting a parsererror from the complete textStatus. I think the problem now lays in the Python/Flask (see current code below). Thanks again for all who've helped!
Python/Flask (I think the problem is here - I'm a noob to Flask):
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list
@app.route('/')
def index():
motifs = get_motif_list(10)
return Response(json.dumps(motifs), mimetype='application/json')
@app.route("/")
def index():
return render_template("index.html")
The JavaScript (the data is returned by the Deferred object - used to solve a callback issue):
function getData() {
var deferredData = new jQuery.Deferred();
$.ajax({
type: "GET",
url: "/",
dataType: "json",
success: deferredData.resolve(),
complete : function(xhr, textStatus) {
console.log("AJAX REquest complete -> ", xhr, " -> ", textStatus)}
});
return deferredData; // contains the passed data
};
A:
It turns out I had a lot of problems in my code above, several of which I had to debug in related questions here and here.
Among them were:
in my original Flask index() function, it was dumping the JSON data to the screen because I was not rendering the index.html template anywhere.
I had matching routes ('/') and function names (index()) in the Flask functions
As mentioned in the comments I did an unnecessary double parsing of the JSON with dataType: json and array_data = JSON.parse(JSON_array)
the return from this asynchonous function always came up undefined because it was referenced before the call had resolved
in my later update to a Deferred object, the success property should have read: success: function(data) { deferredData.resolve(data);}
So, after all those fixes, here is the functioning code!
Flask/Python:
from flask import Response, json, render_template, jsonify
from app import app
from motifs import get_motif, get_motif_list
@app.route('/ajax')
def ajax() :
motifs = get_motif_list(10)
return Response(json.dumps(motifs), mimetype='application/json')
@app.route("/")
def index():
return render_template("index.html")
JavaScript: (note: this is the foo() function in my question above)
function getData() {
var deferredData = new jQuery.Deferred();
$.ajax({
type: "GET",
url: "/ajax",
dataType: "json",
success: function(data) {
deferredData.resolve(data);
},
complete: function(xhr, textStatus) {
console.log("AJAX Request complete -> ", xhr, " -> ", textStatus);
}
});
return deferredData; // contains the passed data
};
// I used the Deferred structure below because I later added Deferred objects from other asynchronous functions to the `.when`
var dataDeferred = getData();
$.when( dataDeferred ).done( function( data ) {
console.log("The data is: " + data);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Error 403 (Forbidden) on the DTD while opening a SVG with our application
In our C# application, sometimes the app needs to open a svg file. To do so, the following code is used:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.None;
XmlReader xr = XmlReader.Create(serverMainPath + @"/path/to/svg/file.svg", settings);
XmlDocument xd = new XmlDocument();
_nmsm = new XmlNamespaceManager(xd.NameTable);
_nmsm.AddNamespace("svg", "http://www.w3.org/2000/svg");
_nmsm.AddNamespace("v", "http://schemas.microsoft.com/visio/2003/SVGExtensions/");
xd.Load(xr);
The standard svg we're using starts with (and as far as I know it's a valid svg):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<!-- Généré par Microsoft Visio 11.0, SVG Export, v1.0 svgIncluded.svg Page-1 -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="http://schemas.microsoft.com/visio/2003/SVGExtensions/" width="8.26772in" height="11.6929in" viewBox="0 0 595.276 841.889" xml:space="preserve" color-interpolation-filters="sRGB" class="st23" >
And it worked just fine during the last 6 months.
But since one or two weeks, this code sometimes produced the following error:
Server Error in '/ourApp' Application.
--------------------------------------------------------------------------------
The remote server returned an error: (403) Forbidden.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The remote server returned an error: (403) Forbidden.
Source Error:
Line 40: _nmsm.AddNamespace("svg", "http://www.w3.org/2000/svg");
Line 41: _nmsm.AddNamespace("v", "http://schemas.microsoft.com/visio/2003/SVGExtensions/");
Line 42: xd.Load(xr);
Source File: path/to/the/file/file.cs Line: 42
Stack Trace:
[WebException: The remote server returned an error: (403) Forbidden.]
System.Net.HttpWebRequest.GetResponse() +5400333
System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) +69
System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) +3929515
System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +54
System.Xml.XmlTextReaderImpl.OpenStream(Uri uri) +34
System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) +380
[XmlException: An error has occurred while opening external DTD 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd': The remote server returned an error: (403) Forbidden.]
System.Xml.XmlTextReaderImpl.Throw(Exception e) +76
System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId) +513
System.Xml.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId) +16
System.Xml.DtdParser.ParseExternalSubset() +21
System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset) +4017069
System.Xml.DtdParser.Parse(Boolean saveInternalSubset) +54
System.Xml.DtdParserProxy.Parse(Boolean saveInternalSubset) +31
System.Xml.XmlTextReaderImpl.ParseDoctypeDecl() +254
System.Xml.XmlTextReaderImpl.ParseDocumentContent() +451
System.Xml.XmlTextReaderImpl.Read() +151
System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace) +58
System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc) +20
System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) +129
System.Xml.XmlDocument.Load(XmlReader reader) +108
OurMethod(params) in path/to/the/file/file.cs:42
StackTrace in our App.
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3643; ASP.NET Version:2.0.50727.3634
At first I thought it was due to a change in our internet proxy policy, but since it has been spotted on another deployment of the app which is behind a different proxy, I highly doubt that.
The error seems to be more or less random, sometimes it'll work, sometimes it won't. I'm just clueless at why it would act this way.
The question is: Do you have any idea why would this happen?
If yes do you know how to fix it? If no, any idea of a workaround?
A:
In the end, I used a homemade class to do the job. It's inspired from the MSDN implementation of the XmlUrlResolver extension. Thanks to @mzjn for pointing out a link that pointed out to the MSDN ressource.
using System;
using System.Net;
using System.Net.Cache;
using System.Xml;
using System.IO;
namespace My.Nasmespace.Class.IO
{
class XmlExtendedResolver : XmlUrlResolver
{
bool enableHttpCaching;
ICredentials credentials;
private string localServerPath;
//resolve ressource from localServerPath if it's possible
//resolve resources from cache (if possible) when enableHttpCaching is set to true
//resolve resources from source when enableHttpcaching is set to false
public XmlExtendedResolver(bool enableHttpCaching, string serverPath)
{
this.enableHttpCaching = enableHttpCaching;
localServerPath = serverPath;
}
public override ICredentials Credentials
{
set
{
credentials = value;
base.Credentials = value;
}
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
if (absoluteUri == null)
{
throw new ArgumentNullException("absoluteUri");
}
//resolve resources from cache (if possible)
if (absoluteUri.Scheme == "http" && enableHttpCaching && (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream)))
{
/*Try to resolve it from the local path if it exists*/
if (!string.IsNullOrEmpty(localServerPath) && absoluteUri.AbsolutePath.EndsWith(".dtd") && !absoluteUri.AbsoluteUri.StartsWith(localServerPath))
{
try {
return GetEntity(new Uri(localServerPath + "/Xml/" + absoluteUri.Segments[absoluteUri.Segments.Length-1]), role, ofObjectToReturn);
} catch (FileNotFoundException){
//Fail silently to go to the web request.
}
}
WebRequest webReq = WebRequest.Create(absoluteUri);
webReq.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
if (credentials != null)
{
webReq.Credentials = credentials;
}
WebResponse resp = webReq.GetResponse();
return resp.GetResponseStream();
}
//otherwise use the default behavior of the XmlUrlResolver class (resolve resources from source)
else
{
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
aura: iteration issues
I have this lightning component that successfully gets knowledge articles from KnowledgeArticleVersion and I have verified the correct data coming through dev console logs... However, I am having some trouble using aura atrributes. I am unable to get the component to actually render the data. I am guessing my issue has something to do with trying to return list data to SObject[] type, thus not allowing {!article.Id} etc to render any data in the component.
Any ideas?
.cmp
<aura:component implements="forceCommunity:availableForAllPageTypes" controller="GetHBArticles">
<aura:attribute name="articles" type="SObject[]"/>
<ui:button label="Get Articles" press="{!c.getArts}"/>
<aura:iteration var="articles" items="{!v.articles}">
<p>{!articles.Id} : {!articles.Title} : {!articles.ArticleType}</p>
</aura:iteration>
</aura:component>
lightning controller
({
getArts: function(cmp){
var action = cmp.get("c.getArticlesList");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.articles", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
apex controller
public with sharing class GetHBArticles {
@AuraEnabled
public static List<List<SObject>> getArticlesList(){
List<List<SObject>> articles = [FIND :searchVar RETURNING KnowledgeArticleVersion
(Id, Title, ArticleType WHERE PublishStatus='online' AND Language = 'en_US' AND ArticleType IN ('Troubleshooting__kav', 'How_To__kav', 'FAQ__kav'))
WITH DATA CATEGORY Topics__c AT 'DataCategoryName];
return articles;
}
}
As always any help from this awesome group is greatly appreciated.
A:
@AllenMann you could fix this in two ways:
1.Return List<KnowledgeArticleVersion> instead of List<List<SObject>> to do so you have to change getArticlesList method as below:
@AuraEnabled
public static List<KnowledgeArticleVersion> getArticlesList(){
List<KnowledgeArticleVersion> articles = [FIND :searchVar RETURNING KnowledgeArticleVersion
(Id, Title, ArticleType WHERE PublishStatus='online' AND Language = 'en_US' AND ArticleType IN ('Troubleshooting__kav', 'How_To__kav', 'FAQ__kav'))
WITH DATA CATEGORY Topics__c AT 'DataCategoryName'][0];
return articles;
}
2.Use the first element(i.e index = 0) of the response which is an array containing an array of KnowledgeArticleVersion data in lightning controller
var result = response.getReturnValue();
if(result.length && result[0].length)
cmp.set("v.articles",result[0]);
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the ratio between small and big x-gons?
I have been checking Gamow's question and noticed something! If we draw all diagonals there is a little polygon in the middle of the original polygon if it is odd-gon (odd-gon is defined as the number of vertices is an odd number.). For example;
So if you draw a regular pentagon on a piece of paper and draw all diagonals, there is a new pentagon in the middle of our original pentagon (shown as darker).
The area-ratio between the small and original pentagon is 6.854.
Question 1: What is the area-ratio between the small and original 99-gons of 99-gon where 99 is number of vertices of the polygon?
Question 2: Is there any formula that you can derive for the area-ratio between the small and original x-gons of x-gon where x is number of vertices of the polygon?
A:
Inscribe the original $n$-gon in a circle of radius 1. The apothem of the large $n$-gon is $\cos(\frac{\pi}{n})$ and the apothem of the small $n$-gon is $\sin(\frac{\pi}{2n})$. Therefore the ratio of their areas is $\left(\frac{\cos(\frac{\pi}{n})}{\sin(\frac{\pi}{2n})}\right)^2$. For $n=99$ this is about $3968.53$.
Demonstration on a heptagon:
$OA=1$, $\angle OAB=\frac{\pi}{2n}$, $\angle AOC=\frac{\pi}{n}$ so $OB=\sin(\frac{\pi}{2n})$ and $OC=\cos(\frac{\pi}{n})$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex Capturing Group within a Capture Group
I am searching through a database to find span tags with video information for the purpose of migration.
My regex works well and I can extract all of the information I need for the most part. The trouble I run into is when the style tag is in a different position than expected. This throws off the expression and results in about 2/3rds of the captures I would expect.
If I try and nest the style capture group inside the main capture group, it fails to capture anything. I also tried using negative/positive lookaheads as well, but it only ever works if I make it an optional capture group. I think the problem is im not nesting it correctly. Most of the related questions give the answer of a negative lookbehind, but my understanding is that's more of a assertion/quantifier.
So how can I always capture the style tag regardless of its position in the span tag?
Regex flavor is .NET (server side)
I have a Regexr setup
/(?<tag><span class='vidly-vid' data-thumb='(?<thumb>http.+\.jpg)'.+aspect-ratio='(?<aspect>\d{1,3}:\d{1,3})'.+sources='\[{"file":.+"(?<src>(?<uri>https:\/\/cf1234.cloudfront\.net\/Vids\/)(?<key>(?<ident>[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}|[a-z0-9]{6})\/(?<mp4>mp4_1080.mp4|mp4_720.mp4|mp4_480.mp4|mp4_360.mp4|mp4.mp4))).+style='(?<style>.+width: (?<width>.+)px.+height: (?<height>.+)px.+)'.+<\/span>)/gmi
Sample Data
All of these should match. The first one does NOT, the other three do.
<span class='vidly-vid' data-thumb='https://cf1234.cloudfront.net/Vids/Thumbnails/691DBB43-5EC8-4D57-AF7B-99896D9BD5D1_19127.jpg' data-aspect-ratio='4:3' style='border-width: 0px; width: 352px; height: 240px;' data-sources='[{"file":"https://cf1234.cloudfront.net/Vids/6v1j0a/hls.m3u8","label":"HD"},{"file":"https://cf1234.cloudfront.net/Vids/6v1j0a/mp4_360.mp4","label":"360p SD"}]'> </span>
<span class='vidly-vid' data-thumb='https://cf1234.cloudfront.net/Vids/Thumbnails/b181cfa5-565d-470a-b93a-2610987bb4da_28142.jpg' data-aspect-ratio='160:117' data-sources='[{"file":"https://cf1234.cloudfront.net/Vids/b181cfa5-565d-470a-b93a-2610987bb4da/hls.m3u8","label":"HD"},{"file":"https://cf1234.cloudfront.net/Vids/b181cfa5-565d-470a-b93a-2610987bb4da/mp4_480.mp4","label":"480p SD"},{"file":"https://cf1234.cloudfront.net/Vids/b181cfa5-565d-470a-b93a-2610987bb4da/mp4_360.mp4","label":"360p SD"},{"file":"https://cf1234.cloudfront.net/Vids/b181cfa5-565d-470a-b93a-2610987bb4da/mp4_720.mp4","label":"720p HD"},{"file":"https://cf1234.cloudfront.net/Vids/b181cfa5-565d-470a-b93a-2610987bb4da/mp4_1080.mp4","label":"1080p HD"}]' style='border-width: 0px; width: 600px; height: 480px;'> </span>
<table align="left" border="0" cellpadding="5" cellspacing="5" style="width:600px"> <tbody> <tr> <td><img alt="" src="/content/generator/Course_90016206/Case-10-LMLO_MG_FLAVOR1label.jpg" style="height:497px; width:324px" /></td> <td><span class='vidly-vid' data-thumb='https://cf1234.cloudfront.net/Vids/Thumbnails/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414_28142.jpg' data-aspect-ratio='146:225' data-sources='[{"file":"https://cf1234.cloudfront.net/Vids/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414/hls.m3u8","label":"HD"},{"file":"https://cf1234.cloudfront.net/Vids/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414/mp4_480.mp4","label":"480p SD"},{"file":"https://cf1234.cloudfront.net/Vids/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414/mp4_360.mp4","label":"360p SD"},{"file":"https://cf1234.cloudfront.net/Vids/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414/mp4_720.mp4","label":"720p HD"},{"file":"https://cf1234.cloudfront.net/Vids/b2a7cbd3-5d31-49a5-bf89-aef0cf9f7414/mp4_1080.mp4","label":"1080p HD"}]' style='border-width: 0px; width: 324px; height: 500px;'> </span></td> </tr> </tbody> </table>
<span class='vidly-vid' data-thumb='https://cf1234.cloudfront.net/Vids/Thumbnails/231913a7-b608-4d8b-9332-64b6840c22f0_28142.jpg' data-aspect-ratio='16:9' data-sources='[{"file":"https://cf1234.cloudfront.net/Vids/231913a7-b608-4d8b-9332-64b6840c22f0/hls.m3u8","label":"HD"},{"file":"https://cf1234.cloudfront.net/Vids/231913a7-b608-4d8b-9332-64b6840c22f0/mp4_480.mp4","label":"480p SD"},{"file":"https://cf1234.cloudfront.net/Vids/231913a7-b608-4d8b-9332-64b6840c22f0/mp4_360.mp4","label":"360p SD"},{"file":"https://cf1234.cloudfront.net/Vids/231913a7-b608-4d8b-9332-64b6840c22f0/mp4_720.mp4","label":"720p HD"},{"file":"https://cf1234.cloudfront.net/Vids/231913a7-b608-4d8b-9332-64b6840c22f0/mp4_1080.mp4","label":"1080p HD"}]' style='border-width: 0px; width: 920px; height: 520px;'> </span>
A:
I'd personally just split up the regex into more manageable chunks, like so:
var spanRegex = new Regex(@"<span class='vidly-vid'.+<\/span>");
var attrRegexes = new[]{
@"data-thumb='(?<thumb>http.+\.jpg)'",
@"aspect-ratio='(?<aspect>\d{1,3}:\d{1,3})'",
@"sources='\[{""file"":.+""(?<src>(?<uri>https:\/\/cf1234.cloudfront\.net\/Vids\/)(?<key>(?<ident>[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}|[a-z0-9]{6})\/(?<mp4>mp4_1080.mp4|mp4_720.mp4|mp4_480.mp4|mp4_360.mp4|mp4.mp4)))",
@"style='(?<style>.+width: (?<width>.+)px.+height: (?<height>.+)px.+)'",
}
.Select(r => new Regex(r))
.ToList();
var results = inputs.Select(i => spanRegex.Match(i).Value)
.Select(i => new
{
i,
attributes =
from r in attrRegexes
let match = r.Match(i)
from g in match.Groups.Cast<Group>().Skip(1)
select new {g.Name, capture = g.Value}
});
Linqpad example
| {
"pile_set_name": "StackExchange"
} |
Q:
Using `mv` to rename a file in nested directory
Suppose I want to rename a file several directories down. I do,
mv dirA/dirB/dirC/name.suf dirA/dirB/dirC/newname.suf
Is there any easier way to type this? One option would be
cd dirA/dirB/dirC
mv name.suf newname.suf
cd -
Anything better?
A:
Depending on your shell, you could make use of the filename expansion features. In ZSH (and, I believe Bash, too), you could run
mv dirA/dirB/dirC/{name,newname}.suf
which expands to
mv dirA/dirB/dirC/name.suf dirA/dirB/dirC/newname.suf
bevore executing the mv command (see zshexpn(1)).
| {
"pile_set_name": "StackExchange"
} |
Q:
Concatenate characters to a string - java
In Joptionpane my characters are shown one by one in the dialog message.
I need them to form a word , as for the example: if I use Sytem.out.println(c) it will show them in a line. I want to show them in a line together in joptionpane too
for (int i = 0; i < encrypt.length(); i++) {
char c = encrypt.charAt(i);
if (Character.isLetter(c)) {
c -= shift;
if(c < 'A'){
c = (char) (((int) c + (int) ('A')) % 26 + (int) ('A'));
}else{
c = (char) (((int) c - (int) ('A')) % 26 + (int) ('A'));
}
JOptionPane.showMessageDialog(null, c);
}
}
A:
String result = "";
for (int i = 0; i < encrypt.length(); i++) {
char c = encrypt.charAt(i);
if (Character.isLetter(c)) {
c -= shift;
if(c < 'A'){
c = (char) (((int) c + (int) ('A')) % 26 + (int) ('A'));
}else{
c = (char) (((int) c - (int) ('A')) % 26 + (int) ('A'));
}
}
result += String.valueOf(c);
}
JOptionPane.showMessageDialog(null, result);
| {
"pile_set_name": "StackExchange"
} |
Q:
Cold sores: why do we get them on the lips?
At the end of a bout of flu or fever, I often get a cold sore on my lip area. Why there?
A:
Fever blisters, or cold sores, are an infection with the type 1 or Type 2 herpes simplex virus (HSV-1, HSV-2). The herpes simplex virus usually enters the body through a break in the skin around or inside the mouth and travels into the nerve for the lip. It's been estimated that 65% of the US population has this infection (I do not have worldwide data).
This version of the virus is relatively benign, but it never leaves the body. It takes up residence in the roots of nerves; in the case of cold sores, it is a nerve near the cheekbone. In times of stress, fever, illness or even over exposure to sunlight, it can activate and travel down the the nerve and erupt as lesions in and around the lips.
All information contained here can be referenced through this government posting, however there is a huge reference pool available. Currently there is no cure or vaccine for HSV-1 or 2 (The HSV-2 is genital herpes, however HSV-1 as has been pointed out, may be introduced through oral contact with genitalia).
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a new module in Sitefinity
I'm trying to create a new module for Sitefinity. I'm basing my module off the sample module linked to from the documentation. http://www.sitefinity.com/help/developer-manual/adding-modules-pluggable-explained.html
What I want is a list of videos. On the left-hand side - the CommandPanel - there should be 3 buttons - "Videos", "Artists" and "Genres".
Whenever either of these is selected, on the right-hand-side, a list of Videos/Artists/Genres should be displayed.
The concept is simple, but what I'm struggling with is, where to actually put the code.
Should I hard-code the list directly into CommandPanel.ascx? Am I supposed to create new controls for Videos, Artists and Genres? Or should I have one control and multiple Panels, which I show/hide? And how do I connect the menu items on the left with changing the panel on the right?
NB. I might be wrong to have Videos, Artists and Genres all on the left. Maybe it should just be "Videos", and Artists and Genres should be separate module each?
I don't need a complete answer, just some direction on how to code in this framework, and where everything should go.
A:
Hi there I just saw this come up I am not sure if you have already started this module yet you may even be finished by now, but I just wanted to say had you checked out the Sitefinity Beta for 3.6 because they are about to simplify the whole Sitefinity module process and particularly for what you are trying to do. Check it on the Sitefinity block a barebones module with the new architecture. This I think would satisfy your needs because you can create a separate "View" for each one of your Videos, Artist and Genres and all their views like create, edit etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting environmental variables with !Ref in AWS SAM?
I'm using SAM CLI v0.8.1. I'm trying to set environmental variable MY_TABLE_VAR as name of the table in my resources (MyTableResource). However, while running my app locally, the MY_TABLE_VAR is undefined. Can you tell me what's wrong in my template and how can I set it properly? Following is my SAM template:
Globals:
Function:
Timeout: 30
Runtime: nodejs8.10
Environment:
Variables:
MY_TABLE_VAR: !Ref MyTableResource
Resources:
MyTableResource:
Type: AWS::Serverless::SimpleTable
Properties:
TableName: table1
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
A:
From my understanding, the Globals section cannot reference resources in the Resources section (the dependency is in the other direction, since whatever is added to the Globals section is added to all Serverless Functions and APIs in the Resourcessection). To work around this, I suggest that you use either Mappings or Parameters, e.g.
Parameters:
TableName:
Type: String
Default: table1
Globals:
Function:
Timeout: 30
Runtime: nodejs8.10
Environment:
Variables:
MY_TABLE_VAR: !Ref TableName
Resources:
MyTableResource:
Type: AWS::Serverless::SimpleTable
Properties:
TableName: !Ref TableName
# more table config....
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need a ball valve on my brew kettle?
I am shopping for a brew kettle so I can upgrade to full volume boils. Many pots have ball valves.
I can think of two reasons to use a ball valve
Drain through it to avoid picking up the kettle to pour wort into the fermentor
Transfer wort through a counterflow chiller
I don't plan on doing either of these things any time soon, so it seems like I'm better off avoiding the extra complexity and possible leaks.
Should I reconsider and get a ball valve on my kettle?
A:
You can always add one later. I have them on all my kettles and they're helpful, but not a necessity for basic brewing. I'd say the biggest thing mine do for me is allow me to use a pump for recirculated chilling. But you can always go on stages, adding a valve (the weldless kits work great) and pump, etc. as need and finances dictate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dropbox стоит ли доверять и насколько?
Многие начали использовать его для хранения конфигов, паролей (естественно защищенных) и др..
Но меня интересует вопрос доверия и еще один вопрос: если удалю на своем компе папку Dropbox, что будет? Исчезнут ли те 2 гига и у них на сервере? То есть, если у меня рухнет винт и полетят все данные, то останутся ли они в облаке?
A:
Ввиду того, что в облаке хранится копия данных, они не пропадут. Первоначальная задача этого сервиса состояла в онлайн-бэкапе информации. То есть чтобы можно было восстановить её в случае порчи или утери.
Файлы хранятся на сервере даже если вы их удалите у себя. (Хотя есть возможность их удалить совсем)
Насчёт надёжности и защищённости от неправомерного доступа - точно не знаю. Но судя по описанию - подход там вполне серьёзный. (How secure is Dropbox?)
| {
"pile_set_name": "StackExchange"
} |
Q:
gem installation ok but not with bundle
I am trying to install the pusher-client gem.
I've put this in my Gemfile:
gem "pusher-client",:git=>"git://github.com/logankoester/pusher-client.git"
bundle install is ok
But when I start the app:
/Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler/runtime.rb:76:in `require': no such file to load -- pusher/client (LoadError)
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler/runtime.rb:76:in `rescue in block in require'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler/runtime.rb:62:in `block in require'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler/runtime.rb:55:in `each'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler/runtime.rb:55:in `require'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/bundler-1.2.0/lib/bundler.rb:128:in `require'
from /Users/thomas/Documents/TweetTv/server/tvtweet/config/application.rb:12:in `<top (required)>'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.1.0/lib/rails/commands.rb:38:in `require'
from /Users/thomas/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.1.0/lib/rails/commands.rb:38:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
It seems to be linked to the - in the gem name, but other gem install correctly.
Any help or suggestion greatly appreciate...
A:
Your git path is wrong. If you go to the repository on GitHub you'll see the code has moved to here.
You should do this in your Gemfile instead:
gem 'pusher-client', :git => "git://github.com/pusher/pusher-ruby-client.git"
| {
"pile_set_name": "StackExchange"
} |
Q:
Как изменить цвет рамки нажатой button
Как поменять синий цвет рамки уже нажатого input type = 'button' на какой-нибудь другой?
A:
Похоже, что это у вас :focus на этой кнопке. Попробуйте ей дать outline. Ну или меняйте его по тому же :focus.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eager Garbage Collection in Java
I would like to better understand my application and specifically its memory footprint.
I do understand the concepts of garbage-collection and I am aware, that there will always be a certain amount of dead objects in the heap, however, I would like to minimize this amount such that monitoring with JConsole (or JVisualVM) provides me with some information about the currently required (not occupied) space.
Is there any way to configure an existing garbage-collector (e.g. G1GC) in the SunVM such that (at the cost of responsiveness and runtime) the amount of dead objects in the heap is minimized?
Clarification
To be more clear about my objectives: My application is non-interactive so the memory-footprint over time is more or less the same between two runs. I want to determine the minimum required heap space and the influence, code changes have on that footprint. The output from JConsole is not really helping here because of the dead objects. I also want to know, whether my peak-memory really is an outstanding peak at one point in time or whether it is streched over time. This is why reducing the Xmx until I reach a OOME is not what gets me there.
Also: I'm talking about use during developer tests, not the use in production here. In production, througput and performance are - of course - more important than a more realistic memroy-footprint.
A:
If you want to know the total amount of memory that your application is using you must monitor it for quite a long time. Samples of the heap at random moments of the application:
jps -> output the pid of java process
jmap -dump:live,format=b,file=heap.bin [pid]
and then with jhat navigate the heap. There are another tools to do so.
Doing this you will know what's on the heap at a moment.
Bear in mind that objects such as memory mapped files are not stored in the heap but in the memory.
When reaching OOM try adding this, and then reading the output to see which objects are actually in the heap:
-XX:-HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=./java_pid<pid>.hprof
To do so, enable the GC log and then use a tool such as GCViewer.
-XX:+PrintGCTimeStamps
-XX:+PrintGCDetails
-verbose:gc
-Xloggc:garbage_collector -> this set the file of the output
When you talk about heap, I understand that you are talking about the tenured space. If so, you need to know the average life of objects. And follow some best practices and then do the fine tuning. Also remember that issuing a System.gc() does not guarantees that the GC is performed.
The thing is that instances goes to young generation (eden) and when it is full a minor GC is performed. Objects that still reachable are passed to one of the two spaces called survivor. Once this is full that space is dumped into tenured. When full, a full GC executes and delete all instances that are not reachable.
One thing you can do is to use primitives in methods. Those won't be placed in the heap as their span of life is in the thread stack.
The useful parameters are those which tie the size of the tenured and young generation (eden). These works by ratios. If you are to issue many GC bear in mind to set a max time for GC stop.
Some interesting parameters are:
-XX:MinFreeHeapRatio=
-XX:MaxHeapFreeRatio=
-XX:NewRatio=
-XX:SurvivorRatio
For example, setting -XX:NewRatio=3 means that the ratio between the young and old generation is 1:3; in other words, the combined size of eden and the survivor spaces will be one fourth of the heap.
Anyway I don't know why you need this requirement. I usually worry only about the throughput and only care for those parameters when the throughput is bad.
| {
"pile_set_name": "StackExchange"
} |
Q:
When to go from basic .erb to Sinatra or Rails
In the old, pre-Ruby & Rails days o' the web, one typically used PHP when they needed to add server-side functionality that HTML or CSS could not provide. Nowadays, we have a ton of options for creating super-dynamic websites and applications. I recently discovered that you can just use .erb files on a web server to get the same functionality as throwing PHP files in there in order to make things more dynamic.
I am building my first from-the-ground-up website, which will actually be my own personal website. I'm a huge Ruby nerd, and definitely want to invest in the technologies I'm most learned and familiar with. I want to build with a focus on simplicity, speed, and power in mind. I love Rails, and have had the most training in it, so I am, for the time being (for version 1.0 of my beloved sexy website), excluding Sinatra or other frameworks from my list of choices.
Now, here's the question, which is admittedly a bit ambiguous: when is it appropriate to go from using regular old .erb files to using a full-blown Rails framework? The website won't be processing any users or anything, and will mostly be a portfolio for my art, music, and technology works. I'll be doing a blog with Jekyll, additionally, so that level of dynamic content will be handled separately.
A:
Strait ERB files are great to set up a simple template system. Jekyll is a more robust way to build a simple static site using templates. It's great for a personal site that doesn't have dynamic content, it doesn't work when you have users storing new content constantly to a database, which then needs to be rendered on the fly to a new page. Rails is based on the idea that you need a database, if you don't need it skip Rails and save yourself loading time, hosting costs, and sysadmin headaches.
Also check out https://github.com/laurilehmijoki/jekyll-s3 you can host your site on S3 for dirt cheap.
| {
"pile_set_name": "StackExchange"
} |
Q:
Browser prompting download of JSON response, ASP.NET MVC2
I've encountered this problem all of a sudden doing a simple ajax submit of a form. The JSON comes back formatted correctly but the browser prompts to download it. Fiddler shows the content-type as correct:
application/json; charset: utf-8
Here's my javascript:
$("#submitbutton").click(function(e) {
$.post('FormTest', function(o) {
FormCallback(o);
});
});
Here is the server side:
public JsonResult FormTest(string test) {
return Json("This worked!");
}
Again, I get back an object from the server fine, but it either prompts me to download (Firefox) or simply shows the object in a new tab in the browser (Chrome).
I found one other question like this but the author didn't explain what was wrong. This is crazy! Any ideas?
Edit: The correct code is below, beside the e.preventDefault, I also needed to tell it which form data to use:
$("#submit-button").click(function(e) {
$.post('address', $("#form").serialize(), function(o) {
FormCallback(o);
});
e.preventDefault();
});
A:
You want to cancel the default action, I expect:
$("#submitbutton").click(function(e) {
$.post('FormTest', function(o) {
FormCallback(o);
});
return false; // <<=====
});
You can also try:
e.preventDefault();
if that doesn't work by itself
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the natural (asymptotic) density of a set A change if a subset of A with natural density zero is subtracted from A?
I know that given two subsets of the Naturals A and B, if the natural density of A equals some non-zero real number a, and the natural density of B is zero, then the natural density of the symmetric difference of A and B is still a. But what are the properties of just set difference with respect to natural density? That is, suppose we have the sets A and B, with respective natural densities as above. Would the natural density of the set difference A-B still be a?
A:
$A\setminus B=A\Delta (B\cap A)$, and $B\cap A$ still has density zero since $B$ does and $B\cap A\subseteq B$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sufficient condition for $M$ to have constant curvature
I decided to keep my original question. However, I'm having trouble only in a part of it (check NOTE)
Let's consider a Riemannian manifold $(M,g)$, with the Levi-Civita connection $\nabla$.
I would like to know why is it that if $M$ has constant sectional curvature, then $\nabla R=0$, where $R$ is the curvature tensor.
Moreover, I read that $\nabla R=0$ does not imply that necessarily that $M$ has constant curvature. However, if $\dim(M)=2$, that holds. (I read in an online set of exercises)
Can anyone give solution/hints/references for this questions ?
Thanks in advance...
NOTE : Meanwhile, I figured it out how to prove that if $M$ has constant sectional curvature, then$\nabla R=0$. However, it is not clear to me the second question : If $\dim(M)=2$ and $M$ is such that $\nabla R=0$, then $M$ has constant curvature. How ?
A:
If $(M,g)$ has constant sectional curvature, its curvature tensor $R$ can be built up from a constant function, the metric $g$ and a Kronecker-$\delta$ by tensorial operations, see e.g. http://en.wikipedia.org/wiki/Ricci_decomposition . Since all these ingredients are parallel, so is $R$.
In general $\nabla R=0$ is equivalent to $(M,g)$ being a locally symmetric space, and there are many examples of such spaces which do not have constant curvature, for example Grassmannians.
In dimension $2$, the Riemann curvature can be built up from the Gauss curvature, the metric and a Kronecker-$\delta$ by tensorial operations. If you look at the explicit form for this, you see that $\nabla R=0$ if and only if the Gauss curvature is constant.
| {
"pile_set_name": "StackExchange"
} |
Q:
select a record from each group if it has given value in column otherwise any one record
Vendor
VendorID | City
1 LosAngels
2 HongKong
VendorDetail
VendorDetailID | DetailCity | VendorID
11 Cairo 1
12 MosCow 1
13 Budapest 1
14 NewDelhi 2
15 Cairo 2
Mastervalues
Text | Value
LosAngels LA
HongKong HK
Cairo CA
MosCow Mo
Budapest BU
NewDelhi ND
The query should return records for every group of VendorID the City should be @GivenCityValue if any of its record has that value in DetailCity Column otherwise the City Should be the value from City Column of Vendor table
This can be achieved with SubQuery and Case When expression.
SELECT VendorID,
(SELECT Text FROM Mastervalues
Where Value IN(CASE WHEN (SELECT COUNT(*)
FROM VendorDetail
WHERE VendorID = Vendor.VendorID AND DetailCity = @GivenCityValue)>0
THEN @GivenCityValue
ELSE Vendor.City END)) AS City
FROM Vendor
if the given value for City is @GivenCityValue = 'Moscow' the desired result is
VendorID | City
1 MO
2 HK
But I am trying to do in Join itself. Do we need any user defined aggregate function ?
Is there any way to do it using join ?
A:
Try this one -
SELECT VendorID
, City
FROM Vendor
OUTER APPLY (
SELECT City = [text]
FROM Mastervalues
WHERE EXISTS(
SELECT COUNT(*)
FROM VendorDetail
WHERE VendorID = Vendor.VendorID
AND DetailCity = @GivenCityValue
AND value = DetailCity
) OR Vendor.City = value
) t
| {
"pile_set_name": "StackExchange"
} |
Q:
3-Way Light Switch, two blacks and a red?
Usual story of remodeling etc. Replaced all the other 4 ways and 3 ways near it just fine, then I run into this guy. It's a 3-way, and I could have sworn I put all the wires exactly where they were on the one I replaced (which worked fine before.) So as it sits replaced, it's not working/switching, but the other end of the 3-way switch I replaced does just fine.
Now I'm at a point where beyond just color matching the normal red/white/black (since in this case I have two blacks and one red) I'm not sure what causing this. I have the red & black you see in the picture from the top wire group, and the additional black wire heading out the other way (see pictures.)
My question would be; Do I just have a bad switch and need to run and get another to make it happy again? Do I swap the two black wires? If I swap them is there possibility of damage?
We just moved in a couple days ago and my meter is in a box god knows where so I can't even test for lives, but I only do one switch at a time and test in between because I'm anal about this sort of thing. Any advice?
A:
It sounds like your wiring is like this:
I believe the switch you took a picture of is the one on the left. If so, it looks like it's wired correctly: the black screw is usually common, and it seems to be coming from the red wire nut, which is the power source (am I seeing that correctly?)
If the other switch is turning on/off the light, regardless of which position this switch is in, then it is very likely this is a defective switch.
However, if it is only happening when this switch is in one particular position, then it's highly likely one of the two switches has the common wire connected to one of the traveller terminals. It could be either one.
If you can determine which wire goes where (the biggest hint is that the traveller wire is 14-3 while the others usually aren't), then you should be able to match it up to the wiring diagram here.
| {
"pile_set_name": "StackExchange"
} |
Q:
I can't find the vender.js when I use webpack
I am using webpack and having a problem.I want to product a html in the public but I can't succeed.
when I use npm run dev ,I encounter a problem
this is my github
https://github.com/wohuifude123/webpack20180315
supplement
I have read you answer many times, and then I modidy webpack.dll.js
output: {
path: __dirname + 'public/dist',
filename: '[name].[chunkhash:8].js',
library: '[name]_[chunkhash:8]'
},
and then I modify the webpack.dev.js
const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
// 引入dev-server配置文件
let BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// a third party
const manifest = require('./vender-manifest.json');
const _venderName = manifest.name.split('_');
const venderName = _venderName[0] + '.' + _venderName[1];
module.exports = merge(common, {
output: { //打包路径
//filename: '[name].bundle.js', //出口文件名
// filename: '[name].[chunkhash].js',
// 可以使用__dirname变量获取当前模块文件所在目录的完整绝对路径
path: __dirname + 'dist', //打包路径
publicPath:'dist/', // 指定publicPath
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
library: '[venderName].js'
},
devtool: 'source-map',
devServer: {
contentBase: [path.join(__dirname, "./public")], // 本地服务器 加载页面 所在的目录
host: '127.0.0.1',
compress: true,
port: 6600,
open: false // 将自动打开浏览器
},
plugins:[
new BundleAnalyzerPlugin({
analyzerMode: 'server', // static/disabled
analyzerHost: '127.0.0.1',
analyzerPort: 9900,
openAnalyzer: false
})
]
});
finally I modify the webpack.common.js
plugins: [
new CleanWebpackPlugin(['dist'], { // 清除 dist 文件中的内容
exclude: [venderName + '.js'] // 排除 提取出的 第三方的 js
}),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./vender-manifest.json') // 加载 manifest.json
}),
new HtmlWebpackPlugin({
filename: './index.html',
template: './src/index.html',
//favicon: './src/favicon.ico',
alwaysWriteToDisk: true // 是否开启 new HtmlWebpackHarddiskPlugin()
}),
new HtmlWebpackIncludeAssetsPlugin({
assets: [venderName + '.js'],
append: false // 不会被 webpack 自动打包
}),
// new HtmlWebpackIncludeAssetsPlugin({
// assets: ['config/env-config.js'],
// append: false, // 不会被 webpack 自动打包
// hash: true
// }),
new HtmlWebpackHarddiskPlugin(), // 将[venderName + '.js']和['env-config.js']放进 index.html 中
new webpack.DefinePlugin({ // 创建一个编译时可以配置的全局常量
PRODUCTION: JSON.stringify(true),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
]
Although I have read your answer carefully, I can't understand details.
I try to modify many places ,but the product can't work .
A:
There are 2 problems in your code:
You are not matching the dll library to your app's output library:
Your webpack.dll.js:
output: {
// some properties
library: '[name]_[chunkhash:8]'
}
//...
new webpack.DllPlugin({
name: '[name]_[chunkhash:8]'
})
Your webpack.dev.js:
const manifest = require('./vender-manifest.json');
//...
module.exports = merge(common, {
output: {
// some properties
library: manifest.name // this was missing
}
}
What I see you were doing was matching the DllPlugin name to the dll output file library, which is not the case.
The webpack dll plugin docs inform to Keep the name consistent with output.library, but applying to where you are using the dll (while using DllReferencePlugin), not where you are creating them (DllPlugin).
You are not creating the dll in the dist folder:
Your webpack dll config looks like:
output: {
path: __dirname + '/dist'
}
which writes your dll file into rootDir/dist and not rootDir/public/dist as you rather wanted.
So the fix for this one would be to just change it to path: __dirname + 'public/dist'.
After those fixes your code started to work for me. If you have any more questions feel free to ask ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
Create ID automatically for all entries into tables with same foreign key
I have 19 tables that all have a column named CompanyID set as a foreign key that references the company table Primary key CompanyID which is set to auto_increment.
Is there a way I can INSERT into all the tables without having to specify the CompanyID in every query? So if I insert into the company table first it will get assigned a CompanyID automatically and I need to use that to insert into the other 19 tables but how do I get this information?
The only way I can think of is to auto generate an ID with php but I don't like this method because it won't follow the 1,2,3 convention I want to use. Also another method is to INSERT the information into the company run a select after its been inserted and match the company name with the CompanyID and set this as a variable in my script but that seems like a lot of extra nonsense. Is there a better way? Hope this makes sense.
A:
You use last_insert_id();
e.g.
INSERT INTO company ....
$id = SELECT last_insert_id();
INSERT INTO othertable (company_id) VALUES ($id)
INSERT INTO yetanothertable (company_id) VALUES ($id)
Most DB libraries which handle MySQL will have some dedicated function/method to get this ID without having to do a full-blown query, but the basic mechanism will be the same in all libraries - insert your "core" record, retrieve its auto-generated ID with last_insert_id()-type calls, then use that retrieved ID in all child record insertions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Paperclip doesn't work showing multiple has_attached_model
I have a model called advertiser and it 5 url for image upload
Here the model
attr_accessible :link, :publishoff, :publishon, :title, :adone, :adtwo, :adthree, :adfour, :adfive
has_attached_file :adone, :styles => {
:small => "150x150>",
:medium => "300x300>",
:thumb => "100x100>"
},
:url => "/assets/advertiser/adone/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/advertiser/adone/:id/:style/:basename.:extension"
Where adone adtwo are my image upload and so on, all have the same idea of upload.
Now the view looks like this
8: <% unless @advertisments.nil? %>
9: <%= link_to image_tag(@advertisments.adone.url(:small), :title =>"#{@advertisments.title}"), @advertisments.link, :target => "_blank" %>
10: <% end %>
And here my controller
application_controller
@advertisments = Advertiser.where("publishon <= ? AND publishoff >= ?", Date.today, Date.today).limit(1)
The error i get is the following
undefined method `adone' for #<ActiveRecord::Relation:
A:
Your controller method is returning an ActiveRecord::Relation collection... the object you want is inside of it.
Add .first to the end of this line, like so:
@advertisments = Advertiser.where("publishon <= ? AND publishoff >= ?", Date.today, Date.today).limit(1).first
This will return the only Advertiser from within the collection and assign it to @advertisements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the Intel Atom processor need so much thermal dissipation compared to similar ARM processors
When looking at cases designed around the Intel NUC Atom-based board it seems they put a lot of effort into thermal dissipation (i.e. the entire case is basically a big heatsink). Of course, these cases are fanless and the logic goes that since there is no fan you need to get rid of heat by some other means - hence the huge heatsink.
However, my smartphone contains a very comparable processor (Qualcomm Snapdragon) and my phone contains neither a fan nor that huge heatsink. The TDP for the Intel Atom is advertised as 5W whereas it seems the Snapdragon is closer to 2.5W .
My questions are:
Is the Snapdragon's thermal design just so vastly superior to that of the Intel Atom processor or is there some benefit to the Intel Atom that I'm missing?
Also, assuming that the 5W/2.5W numbers are accurate, does that justify the huge difference between cooling solutions?
Are there any other solutions (for running a linux-based appliance) that I should look at that have solid industrial support but neither require a huge heatsink nor a fan?
A:
The atom processor is based on an older architecture, plus it has to carry the baggage of being PC-compatible. So it is more complicated to implement therefore requiring significantly more transistors for similar capabilities. I believe the term RISC came after the x86 was well on its way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the minimum amount of walls
I'm making a game where the walls are made of square blocks. The walls are placed on a two-dimensional grid, like this:
[X][X][X][X]
[ ][X][ ][ ]
[ ][X][ ][ ]
[ ][X][ ][ ]
Now, as I'm optimizing my collision detection, it helps to reduce the wall count to the bare minimum. In the above case, there is seven wall blocks, but only two walls if the blocks are combined. I'm having difficult time coming up with an optimal solution for finding these combined walls and get varying results depending on which block the search starts (the blocks are stored in an unordered list, the order comes from the order in which they were laid in an editor). Any thoughts on how to solve this? It should be pretty rudimentary stuff, but, y'know, it's friday and I can't function correctly. :)
Here's my sub-optimal code at the moment, it basically does two checks, both for horizontal and vertical "continuity" and then checks which one is better. It also stores the "already handled" blocks of walls so they won't be recognized twice, but this of course makes it go funky in crossing points.
public void CreateCollidersForExport()
{
List<Wall> handledWalls = new List<Wall>();
foreach (Wall w in walls)
{
if (handledWalls.Contains(w)) continue;
handledWalls.Add(w);
// Search how many walls there is horizontally
Vector3 horizontalCenter = new Vector3(w.X, w.Y, w.Z);
List<Wall> tmpWallsHorizontal = new List<Wall>();
tmpWallsHorizontal.Add(w);
foreach (Wall other in walls)
{
if (handledWalls.Contains(other) || tmpWallsHorizontal.Contains(other)) continue;
bool canAdd = false;
foreach (Wall _w in tmpWallsHorizontal)
{
if (other.X == _w.X + Wall.size && other.Y == _w.Y && other.Z == _w.Z)
{
canAdd = true;
horizontalCenter.X += Wall.size / 2;
break;
}
else if (other.X == _w.X - Wall.size && other.Y == _w.Y && other.Z == _w.Z)
{
canAdd = true;
horizontalCenter.X -= Wall.size / 2;
break;
}
}
if (canAdd)
{
tmpWallsHorizontal.Add(other);
}
}
// Search how many walls there is vertically
Vector3 verticalCenter = new Vector3(w.X, w.Y, w.Z);
List<Wall> tmpWallsVertical = new List<Wall>();
tmpWallsVertical.Add(w);
foreach (Wall other in walls)
{
if (handledWalls.Contains(other) || tmpWallsVertical.Contains(other)) continue;
bool canAdd = false;
foreach (Wall _w in tmpWallsVertical)
{
if (other.X == _w.X && other.Y == _w.Y && other.Z == _w.Z + Wall.size)
{
canAdd = true;
verticalCenter.Z += Wall.size / 2;
break;
}
else if (other.X == _w.X && other.Y == _w.Y && other.Z == _w.Z - Wall.size)
{
canAdd = true;
verticalCenter.Z -= Wall.size / 2;
break;
}
}
if (canAdd)
{
tmpWallsVertical.Add(other);
}
}
if (tmpWallsHorizontal.Count > tmpWallsVertical.Count)
{
// tmpWallsHorizontal has the longest "wall" now
}
else if (tmpWallsVertical.Count > tmpWallsHorizontal.Count)
{
// tmpWallsVertical has the longest "wall" now
}
else
{
// Both ways are the same length
}
}
}
A:
I'd try to treat this as a form of flood fill. The idea is that you walk over ever cell of the grid: every time you hit a 'wall' you start a flood fill, except that the flood fill only works on a single axis (so instead of flooding int o all four directions you either only go up/down or left/right).
Assuming you have your initial grid, and start iterating the cells left to right, top to bottom:
[X][X][X][X]
[ ][X][ ][ ]
[ ][X][ ][ ]
[ ][X][ ][ ]
You start with the top-left cell, notice it's a wall, start flooding. Since you can only flood to the right, you do a horizontal flood. You end up covering the area marked with '1' and memorize the area in a list:
[1][1][1][1] 0/0 -> 3/0
[ ][X][ ][ ]
[ ][X][ ][ ]
[ ][X][ ][ ]
You move on, eventually hit the wall in the second row. You cannot flood left (no wall), you cannot flood up (already covered), you cannot flood right (no wall), but you can go down - so you do a vertical flood:
[1][1][1][1] 1: 0/0 -> 3/0
[ ][2][ ][ ] 2: 1/1 -> 1/3
[ ][2][ ][ ]
[ ][2][ ][ ]
And now you're done. In this version, ever 'X' is always only part of one wall. So if you had
[ ][X][ ][ ]
[X][X][X][X]
[ ][X][ ][ ]
[ ][X][ ][ ]
you would have three walls:
[ ][1][ ][ ] 1: 1/0 -> 1/3
[2][1][3][3] 2: 0/1 -> 0/1
[ ][1][ ][ ] 3: 2/1 -> 3/1
[ ][1][ ][ ]
If you allow flooding 'X' cells covered by other walls, you could have just two:
[ ][1][ ][ ] 1: 1/0 -> 1/3
[2][*][2][2] 2: 0/1 -> 3/1
[ ][1][ ][ ]
[ ][1][ ][ ]
The '*' denotes a cell covered by two walls.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git rebase and git merge
I understand that if I have a branch ready to merge with remote master, I need to do:
git checkout 'my branch'
git rebase master (rebase because I want simple history + my changes are minuscule enough to do that). But it will be rebase with my local master, not with origin master, correct?
git checkout master
git merge 'my branch' - this will do fast-forward merge and completes the process.
But how to do the same merge with remote master? I don't see any explicit explanation in the Internet. I cannot just checkout on origin master on the 3d step.
What am I missing?
A:
You can simply rebase on top of the origin master like this
git rebase origin/master
Also you can skip 3. and 4. simple pushing your rebased branch to the origin/master
git push origin my_branch:master
A:
The remote master is whatever the remote repo identifies as master. Whenever you fetch from the origin remote, git tags that remote's master commit as your origin/master (in your remotes refs).
The way to update a remote repo's refs is to push to it (which also sends any commits or whatever else is needed). So:
git checkout master # or however you want to get `master` current with origin
git pull # ...
git checkout mybranch
git rebase master
git checkout -B master # you know it's going to --ff, so just move the ref
# or, you could `git checkout master; git merge mybranch`
git push origin master # push the new commits to the remote's `master`
| {
"pile_set_name": "StackExchange"
} |
Q:
How do exit two nested loops?
I have been using Java for quite some time, yet my education in loops is somewhat lacking. I know how to create every loop that exists in java and break out of the loops as well. However, I've recently thought about this:
Say I have two nested loops. Could I break out of both loops using just one break statement?
Here is what I have so far.
int points = 0;
int goal = 100;
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break; // For loop ends, but the while loop does not
}
// I know I could put a 'break' statement here and end
// the while loop, but I want to do it using just
// one 'break' statement.
points += i;
}
}
Is there a way to achieve this?
A:
In Java you can use a label to specify which loop to break/continue:
mainLoop:
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break mainLoop;
}
points += i;
}
}
A:
Yes, you can write break with label e.g.:
int points = 0;
int goal = 100;
someLabel:
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break someLabel;
}
points += i;
}
}
// you are going here after break someLabel;
A:
There are many ways to skin this cat. Here's one:
int points = 0;
int goal = 100;
boolean finished = false;
while (goal <= 100 && !finished) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
finished = true;
break;
}
points += i;
}
}
Update: Wow, did not know about breaking with labels. That seems like a better solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# tasks are not cancelled
I have several tasks to execute. Each task completes its execution in different duration. Some of the tasks perform database access, some of them just makes some calculations. My code has the following structure:
var Canceller = new CancellationTokenSource();
List<Task<int>> tasks = new List<Task<int>>();
tasks.Add(new Task<int>(() => { Thread.Sleep(3000); Console.WriteLine("{0}: {1}", DateTime.Now, 3); return 3; }, Canceller.Token));
tasks.Add(new Task<int>(() => { Thread.Sleep(1000); Console.WriteLine("{0}: {1}", DateTime.Now, 1); return 1; }, Canceller.Token));
tasks.Add(new Task<int>(() => { Thread.Sleep(2000); Console.WriteLine("{0}: {1}", DateTime.Now, 2); return 2; }, Canceller.Token));
tasks.Add(new Task<int>(() => { Thread.Sleep(8000); Console.WriteLine("{0}: {1}", DateTime.Now, 8); return 8; }, Canceller.Token));
tasks.Add(new Task<int>(() => { Thread.Sleep(6000); Console.WriteLine("{0}: {1}", DateTime.Now, 6); return 6; }, Canceller.Token));
tasks.ForEach(x => x.Start());
bool Result = Task.WaitAll(tasks.Select(x => x).ToArray(), 3000);
Console.WriteLine(Result);
Canceller.Cancel();
tasks.ToList().ForEach(x => { x.Dispose(); }); // Exception here
tasks.Clear();
tasks = null;
Canceller.Dispose();
Canceller = null;
I have a period of 5 seconds to start all these tasks. In every 5 seconds I call the code above. Before the next call I have to be sure that no task remains from the previous execution period. Let's say if 3 seconds are passed after the execution I would like to cancel execution of tasks which are not completed.
when I run the code Task.WaitAll parameter of 3000 lets first 3 tasks are completed as expected. Then I get Result as false because 2 other tasks are not completed. Then I must cancel these two tasks. If I try to dispose them I get exception saying "Tasks in completed state can only be disposed."
How can I achieve this? After I call Cancel method of CancellationTokenSource these two tasks are still executed. What is wrong here?
A:
First, you should almost never use Task.Start. Use the static Task.Run method instead.
When you pass a CancellationToken to Task.Run or other APIs that create tasks, this does not allow you to abort the task immediately by requesting cancellation. This just only sets the status of the task to Canceled if the code in the task throws a OperationCanceledException exception. Please take a look at the CancellationToken section of this article.
To cancel a task, the code that the task runs must cooperate with you. For example, if the code does something in a loop, then that code must check periodically if cancellation is requested and throw an exception if so (or simply exit the loop if you don't want the task to be considered cancelled). There is a method in CancellationToken called ThrowIfCancellationRequested that does just that. This of course means that such code needs to have access to the CancellationToken object. This is why we have methods that accept cancellation tokens.
As another example, if the code that the task runs calls a database access method, you'd better call a method that accepts a CancellationToken so that such method will try to exit as soon as cancellation is requested.
So in summary, cancelling an operation is not a magical thing as the code that the task runs need to cooperate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convertir XML a objeto en Java
Estoy haciendo un proyecto en el cual necesito convertir un xml que obtengo desde un RestFul y convertirlo a un objeto en Java y no se como hacerlo, alguien que me ayude.
A:
JAXB es el estándar de Java ( JSR-222 ) para convertir objetos a / desde XML. Lo siguiente debería ayudar:
Descomponer desde una cadena
Tendrá que envuelva el String de una instancia de StringReaderantes de que sus impl JAXB puede deserializar ella.
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);
Diferentes nombres de campo y XML
Puede usar la @XmlElement anotación para especificar cuál quiere que sea el nombre del elemento. Por defecto, JAXB analiza las propiedades. Si desea basar las asignaciones en los campos, debe configurarlas @XmlAccessorType(XmlAccessType.FIELD)
@XmlElement(name="count")
private int size;
Espacios de nombres
Las anotaciones @XmlRootElementy @XmlElement también le permiten especificar la calificación del espacio de nombres donde sea necesario.
@XmlRootElement(namespace="http://www.example.com")
public class Response {
}
En Conclusion
JAXB crea objetos java a partir de archivos XML. Primero deberá generar clases Java utilizando el generador de código de jaxb que toma XSD como entrada y luego serializar / deserializar estos archivos xml de manera adecuada.
Referencias
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Где лучше хранить свои функции для Django?
Есть сайт, работающий на Django 2.2.4, появилась необходимость написать функцию, которая будет парсить другой сайт и срабатывать в определенное время, так вот, в каком файле проекта/приложения Django ее лучше хранить?
A:
Такую функцию лучше хранить в тасках Celery или в виде management command.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Context Api and State hooks mutation
I have a modern react application using the context api and many hooks, i use the context to store global values for my application, this values or the context itself should never directly re-render other components, the context itself has a its own getter/setter in form of the UseState hook/s which is what is called from the consumer components to be used, if any component is dependent on the context data a separate state in this component itself is created and state is then being properly handled.
My concrete question in my case how bad is it to directly mutate the object i have stored in the context?
for example from any random consumer component changing the context object as follows:
const handlerFunction = () => {contextObjData.value = "Something"};
Instead of the "intended" react way:
const handlerFunction = () => {setContextObjData(...contextObjData, value: "Something")};
To me it seems overkill to each time save the entire object again but maybe someone can give me another perspective and some insights.
Side question kind of nooby but i am not sure, is there a difference between these two:
const handlerFunction = () => {setContextObjData(...contextObjData, value: "Something")};
const handlerFunction = () => {setContextObjData(prevState => ({...contextObjData, value: "Something"}));
A:
A state change will trigger a render. When you mutate something then React won't detect that the state has changed and will not re render.
The handlerFunction examples matter only if you want to optimize it using useCallback but the way you do it it is broken either way (syntax error and not using prevState in the second example).
//handlerFunction will be re created every render
const handlerFunction = () =>
setContextObjData({
...contextObjData,
value: 'Something',
});
//handler function will only be created on mount
const optimizedHandler = React.useCallback(
() =>
setContextObjData((prevState) => ({
...prevState,
value: 'Something',
})),
[] //empty dependency, only create optimizedHandler on mount
);
//broken handler, using stale closure will give you liner warning
const brokenHandler = React.useCallback(
() =>
//callback only used on mount so has contextObjData
// as it was when mounted (stale closure)
setContextObjData({
...contextObjData, //needs contextObjData in closure scope
value: 'Something',
}),
[] //empty dependency, but contextObjData will be a stale closure
);
Pure components will only re render when props change, state change or return value from useSelector or useContext change.
When you pass a callback as a prop to a child and your component re renders without the child needing to re render you can optimize a passed callback with useCallback so the child doesn't get needlessly re rendered:
//Child is a pure component
const Child = React.memo(function Increment({ increment }) {
const r = React.useRef(0);
r.current++;
return (
<button onClick={increment}>
rendered: {r.current} times, click to increment
</button>
);
});
const Parent = () => {
const [count, setCount] = React.useState(1);
const increment = React.useCallback(
() => setCount((c) => c + 1),
[]
);
React.useEffect(() => {
const t = setInterval(() => increment(), 1000);
return () => clearInterval(t);
}, [increment]);
return (
<div>
<h4>{count}</h4>
<Child increment={increment} />
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Here is an example how mutation will break re rendering:
const CounterContext = React.createContext();
const CounterProvider = ({ children }) => {
console.log('render counter provider');
const [c, setC] = React.useState({ count: 0 });
const increment = React.useCallback(
() =>
setC((c) => {
console.log('broken:', c.count);
c.count++;
return c;
}), //broken, context users never re render
[]
);
return (
<CounterContext.Provider value={[c, increment]}>
{children}
</CounterContext.Provider>
);
};
const App = () => {
console.log('render App');
const [count, increment] = React.useContext(
CounterContext
);
return (
<div>
<h4>count: {count.count}</h4>
<button onClick={increment}>+</button>
</div>
);
};
ReactDOM.render(
<CounterProvider>
<App />
</CounterProvider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Grafana be installed on a 32 bit Ubuntu 14.04LTS?
I did the following as instructed in the Grafana website:
deb https://packagecloud.io/grafana/stable/debian/ wheezy main
curl https://packagecloud.io/gpg.key | sudo apt-key add -
sudo apt-get update
sudo apt-get install grafana
No such package found
Is Grafana currently supported on 32bit Ubuntu
A:
Official repo contains only 64 bit packages. There's Github issue for providing 32 bit package but no progress there.
You can try to build own binary, using instructions on Github repo and 32 bit VM.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prevent iostreams::mapped_file_sink from creating executable txt files
EDIT: code sample is broken, it is missing .is_open(), please DON'T use it.
I have a rather strange question. I use boost iostreams and they work awesome, but the problem is that files that program creates are executable txt files(I'm on ubuntu,msg is :""lol2.txt" is an executable text file.").
So is there any way to make it a regular nonexecutable file. I would like to change the code so that it doesnt create executable, files I know I can change the file after it is created from terminal or Nautilus.
btw this is the code that I'm using:
void write_file(const std::string& name,string data)
{
iostreams::mapped_file_params params;
params.new_file_size=data.size();
params.path=name;
iostreams::mapped_file_sink file(params);
memcpy(file.data(),&data[0],data.size());
}
A:
You can change the file creation mask of your process to create non-executable files by default:
umask(getumask() & ~(S_IXUSR | S_IXGRP | S_IXOTH));
| {
"pile_set_name": "StackExchange"
} |
Q:
Wallch changing frequency resets automatically
I have been using the wallpaper changing utility Wallch for quite some time and very happy with the experience.
But recently the utility has started giving some trouble.
No matter what I do, the frequency of changing the wallpapers always resets to the minimum value (10 secs) automatically.
A:
Wallch developer here. No need to post a bug at askubuntu :D
I have changed the bug at launchpad to "Fix Commited"
Wallch 4.0 should be ready in 1-2 weeks, if you are in a hurry use our latest ppa of version 3
For 12.04:
sudo add-apt-repository ppa:wallch/12.04-3+
sudo apt-get update && sudo apt-get install wallch
For 13.04/13.10:
sudo add-apt-repository ppa:wallch/3+
sudo apt-get update && sudo apt-get install wallch
For instant updates (within 24 hours from the last code change):
sudo add-apt-repository ppa:wallch/wallch-daily
sudo apt-get update && sudo apt-get install wallch
| {
"pile_set_name": "StackExchange"
} |
Q:
Хвостовая рекурсия и аккумуляторы в Haskell
Как работает хвостовая рекурсия и аккумуляторы в Haskell на конкретном примере, а именно реализация Чисел Фибоначчи:
fibonacci' :: Integer -> Integer
fibonacci' n = helper 0 1 n
helper :: Integer -> Integer -> Integer -> Integer
helper first second 0 = first
helper first second n | n > 0 = helper (first + second) first (n - 1)
| n < 0 = helper second (first - second) (n + 1)
| otherwise = first
Как это работает вообщем в данном языке? К примеру если мы вводим fibonacci 6, то почему мы получаем 8, с помощью подстановки? что происходит (пошагово) за "кулисами"?
A:
На примере 6 (надеюсь, что верно понял вопрос):
helper 0 1 6 -- изначально вызываем
helper 1 0 5 -- в первом аргументе сумма первого и второго предыдущего 0+1 , а 0 из первого предыдущего - во второй аргумент = 0
helper 1 1 4 -- в первом сумма 1+0, а во второй идёт значение из первого = 1
helper 2 1 3 -- в первом сумма 1+1, а во второй берём значение из первого = 1
helper 3 2 2 -- в первом сумма 2+1, а во второй = 2
helper 5 3 1 -- в первом сумма 3+2, а во второй = 3
helper 8 5 0 -- т.к. значение третьего аргумента равно нулю, то получаем результат из первого = 8
| {
"pile_set_name": "StackExchange"
} |
Q:
How is pre-image resistance defined, formally?
Earlier today, forest asked in our chat, The Side Channel whether the definition of first pre-image security actually requires that an input that evaluates to the challenge hash result must be known to exist a-priori.
This got me thinking. How does one actually, formally define first pre-image security for hash functions?
This is also motivated by the fact that formal definitions are crucial in cryptography to actually understand what is needed to break security. For example, the RSA problem isn't "given $c$ that was constructed as $c=m^e\bmod n$, find $m$" but rather requires specific properties from $n$ (by requiring correct key generation) and requires correct choice (uniformly at random) of $m$ as well.
A:
$\newcommand{\xs}{\xleftarrow\$}\newcommand{\mc}{\mathcal}$
There is a paper from 2004 (last revised 2009) by Rogaway and Shrimpton "Cryptographic Hash-Function Basics: Definitions, Implications and Separations for Preimage Resistance, Second-Preimage Resistance, and Collision Resistance" which talks about this very topic (among others). I shall use it as the primary reference of this answer.
In the paper, there are three definitions given for first pre-image resistance. One which is separate from the others, one somewhat weaker and a strong one (to which quite a few other properties also reduce to). So we shall go through them in order.
Before we can start though, we need to take a moment to acustom to the fact that any hash function is written as $H_K(M)$ from here on, i.e. that the hash functions take a "key" as well. This is done to be able to model them as random functions and in practice this "key" can be assumed to be fixed and e.g. represent the initial internal chaining value of the hash function or a salt-like input to the hash. So from here on, let our hash function be $H:\mathcal K\times \mathcal M\to\mathcal Y$ and let $m$ be an integer such that $\{0,1\}^m\subseteq\mathcal M$, i.e. pick a length $m$ of bit strings that is a valid input length to the hash function. This set is useful because it allows us to reason about a finite subset of the potentially infinitely large hash input and we can make any choice of $m$ to our liking to model a particular string length.
Also all the definitions will talk about advantages for some adversary and some auxilliary parameters. Usually you want to bound this advantage to be negligble (in some security parameter, e.g. the digest length or the input entropy) for all adversaries that run in polynomial cost (i.e. efficiently and don't just enumerate the hash) and for all auxiliary parameters.
Definition 1: everywhere Preimage resistance (ePre)
$$\mathrm{Adv}^{\text{ePre}}_H(A)=\max_{Y\in\mc Y}\{\Pr[K\xs\mc K;M\xs A(K):H_K(M)=Y]\}$$
So what does this definition say? First, iterate over all possible output values $Y$. Next pick a hash function uniformly the selection. Then ask the attacker to come up with a value given the function selection. The attacker "wins" for the given $Y$ value if they actually found a pre-image. Now take the advantage of the attacker to be the maximum over all possible choices of $Y$.
Now this definition essentially says that it should be hard for an attacker to come up with a pre-image for any output value, given that they had no a-priori knowledge of the concrete (secure) variation of the hash.
It may appear that this definition isn't all that useful in practice, because an attacker may just always guess the empty string, but as the range point is fixed first and then the hash is selected uniformly at random, there's a $1/|\mc K|$ probability of being right with the guess, which is negligible. Thanks to Maeher for pointing this error out in a previous version of this answer.
Definition 2: always Preimage resistance (aPre)
$$\mathrm{Adv}_H^{\text{aPre}[m]}(A)=\max_{K\in \mc K}\{\Pr[M\xs\{0,1\}^m;Y\gets H_K(M);M'\xs A(Y):H_K(M')=Y]\}$$
What does this mean? Well, first it asks to iterate over all possible hash selections and fix one, e.g. the concrete instance. Now pick a message uniformly at random. Hash it using the hash instance. Hand the result to the adversary and ask them to come up with a value. If this value is actually a pre-image of the value given hash function then the adversary won.
Now practically speaking it appears that this definition is the one most closely modeling actual hash functions, because you fix the selection of the function and then ask the adversay to find a pre-image for a randomly chosen message.
Definition 3: Preimage resistance (Pre)
$$\mathrm{Adv}_H^{\text{Pre}[m]}(A)=\Pr[K\xs\mc K;M\xs\mc \{0,1\}^m;Y\gets H_K(M);M'\xs A(K,Y):H_K(M')=Y]$$
So what does this mean? Well it first says that you should pick an instance of the hash function uniformly at random. Then we pick a message uniformly at random from the set of bit strings of length $m$. Next we compute the challenge output value $Y$ using the previously determined message and function selection. Finally we give the adversary, ie the attacker both our function selection and the output value and ask it to come up with a value. If that value is indeed a first-preimage then the attacker "won". The advantage an attacker has now is the probability over the choice of the function selection and the value selection that they can come up with a valid pre-image.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby, что не так с кодом? и что на счет лаконичности и правильности
Изучаю Ruby. Решил написать консольную программку "Компьютер выбирает рандомное число, а пользователь должен его угадать с трёх попыток."
Но программа работает не верно, Ограничение по попыткам не работает. То ли не плюсует, то ли что. Т.к больше трех попыток, а в выигрыше вывод что угадал с 1 попытки.
puts "Приветствуем вас. Компьютер загадал число от 1 до 7, попробуйте его угадать с 3-ёх попыток."
chislo_komp = rand(7)
chislo_user = nil
popitka = 0
while chislo_user != chislo_komp
puts "Введите число: "
chislo_user = gets.chomp.to_i
if chislo_user != chislo_komp && popitka <=3
puts "Введите число: "
chislo_user = gets.chomp.to_i
popitka = popitka+1
elsif chislo_user == chislo_komp
puts "Урааа, вы выиграли!"
puts "Вы угадали число с " + popitka.to_s + " раза."
elsif popitka > 3
puts "Сожалеем, но ваши попытки исчерпаны. Вы проиграли."
end
end
A:
Во-первых, условия созданы крайне отвратные. Во-вторых - дважды спрашивается число, не надо так.
Значительно улучшенный вариант (хотя, их можно придумать ещё больше разных):
puts "Приветствуем вас. Компьютер загадал число от 1 до 7, попробуйте его угадать с 3-ёх попыток."
computer_choice = rand(7)
user_choice = nil
step = 1
guessed = false
while step <= 3
puts "Введите число: "
user_choice = gets.chomp.to_i
if computer_choice == user_choice
guessed = true
break
end
step += 1
end
if guessed
puts "Урааа, вы выиграли!"
puts "Вы угадали число с " + step.to_s + " раза."
else
puts "Сожалеем, но ваши попытки исчерпаны. Вы проиграли."
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Does NetBIOS name resolution maps NetBIOS names to IP address or to MAC address
Does NetBIOS name resolution maps NetBIOS names to IP address or to MAC address?
A:
It maps names to ip-addresses. ARP is used to map ip-addresses to MAC addresses.
The output of NBTSTAT -c lists the local cache if you want some direct evidence:
Node IpAddress: [192.168.1.6] Scope Id: []
NetBIOS Remote Cache Name Table
Name Type Host Address Life [sec]
------------------------------------------------------------
MUNNIN <20> UNIQUE 192.168.1.9 535
Edited to add:
Theo's answer made me realize that while the above answer is probably what you are looking for since almost all NetBIOS today is NetBIOS over TCP (NBT), there are other NetBIOS implementations. For Microsoft's NetBEUI (more correctly NBF) the name resolution service returned MAC addresses and with NetBIOS over IPX\SPX (NBX) name resolution would return an IPX address.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the Necklace of Prayer Beads allow two spells to be cast in a round?
The Necklace of Prayer Beads states that it allows casting certain spells as a Bonus Action.
Can a memorized spell be cast as an Action - or do the normal rules apply in that only cantrips are allowed as a main action when using the Necklace of Prayer Beads?
A:
There is no rules exception for same-round casting of spells from magic items.
In the DMG, under "Activating Magic Items", it says...
Some magic items allow the user to cast a spell from the item, often by expending charges from it. The spell is cast at the lowest possible spell level, doesn’t expend any of the user’s spell slots, and requires no components unless the item’s description says otherwise. The spell uses its normal casting time, range, and duration, and the user of the item must concentrate if the spell requires concentration. Certain items make exceptions to these rules, changing the casting time, duration, or other parts of a spell.
Other than the fact that they do not require components or slots (first bold section above), spells cast from items are no different from casting them normally... unless the magic item specifically calls it out (second bold section).
The Necklace of Prayer Beads specifies a reduced casting time for the spells it contains, but that's it. If it were meant to bypass any of the other spellcasting rules, it would say so.
A:
They do not - the normal rules apply.
Prayer Beads specify you are casting the spell:
Each bead contains a spell that you can cast from it as a Bonus Action (using your spell save DC if a save is necessary).
Since you are casting the spell, the normal rules for spells cast with a Bonus Acton apply;
A spell cast with a bonus action is especially swift. You must use a bonus action on Your Turn to cast the spell, provided that you haven’t already taken a bonus action this turn. You can’t cast another spell during the same turn, except for a cantrip with a casting time of 1 action.
This would not be the case if the item were casting the Bonus Action spell rather than you - however in this case it's clear you are the caster.
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA's range causes "Run time error 9 Subscript out of range"
The following code fails whenever I go beyond certain number of columns e.g. if I was using this array: AD2:BM, everything works well and it bounds the letter with each other (its original purpose). However, whenever I try to go from AD2:KQ it fails by indicating
Run time error 9 Subscript out of range.
Can you please advise how to extend the ranges within this code (without generating error)? Regards West
Sub WL()
Dim R As Long, C As Long, X As Long, Data As Variant
Data = Range("AD2:BM" & Columns("AD:BM").Find("*", , xlValues, , xlRows, xlPrevious).Row)
For R = 1 To UBound(Data, 1)
X = -1
For C = 1 To UBound(Data, 2)
If Len(Data(R, C)) Then
X = X + 1
If X Then Data(R, C) = Data(R, C + 1) & Data(R, C)
End If
Next
Next
Range("AD2:BM2").Resize(UBound(Data)) = Data
End Sub
2. UPDATE:
All strings of W's & L's begin with one letter and end with one letter.
Everything inbetween is perfect.
The question is: what can be done to double first far-right and first far-left values (that are singles)? E.g. I have highlighted these event on the attached photo below [don't be fooled, every single string starts and ends with one letter - these two cases are simply visible in their entirety].
I need beginning and ending L or W to double, from W to WW and from L to LL. Wherease the W's & L's in between to remain the way they are, i.e. move from one period to the other and join other single letter [just like in the code below].
Thanks
A:
You are incrementing C to the UBound(Data, 2) but within that loop you expect to use Data(r, C + 1) which is outside the UBound.
Sub WL()
Dim R As Long, C As Long, X As Long, Data As Variant
Data = Range("AD2:BM" & Columns("AD:BM").Find("*", , xlValues, , xlRows, xlPrevious).Row)
For R = 1 To UBound(Data, 1)
X = -1
For C = 1 To UBound(Data, 2) - 1 '<~~ FIX HERE!!
If Len(Data(R, C)) Then
X = X + 1
If X Then Data(R, C) = Data(R, C + 1) & Data(R, C) 'Now C+1 doesn't error
End If
Next
Next
Range("AD2:BM2").Resize(UBound(Data)) = Data
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Applying wooden planks to masonry wall
Introduction
I would like to cover my bathroom walls with wooden planks because it looks downright hipster. Trouble is that there is masonry directly under the surface, and also they will potentially face a lot of moisture from the shower.
The question
What would be the best way to apply about 12sqM of wooden planks (taken from wooden pallets) to this masonry, and would they suffer from moisture in the long run and therefore require special treatment?
We currently have the lower half of the walls covered in tiles which we would like to keep. Any solution will have to work with these.
Ideas
Masonry nail gun
No nails adhesive
Screws with hammer drill (this would take years)
That's about it, thanks for your help!
Our bathroom looks like this:
This is the effect we are going for:
A:
Your question is concerning two things:
1. Proper fitting (wood planks to masonry wall).
2. Proper wood treatment (anti-moisture).
So that's how will my answer look like. Let's look at this.
1. Proper fitting.
I would advise preparing additional support planks going vertically with - say - 1 meter space (that spacing requires additional insight on how much planks will weight, what wall you got and what kind of bolts you will use; use your aptitude and experience or ask a prO). These support planks will be bolted to the wall on all wood-wall height and have only supportive purpose (don't need any beautiful finishing or something). The spacing also determines if (or HOW MUCH) your wood-wall would deform over time. Shorter spaces mean less visible deformations (in short).
Your proper planks - THE planks you want to see as a decorative - will be attached to these supports I mentioned before. That will make support planks perpendicular to these decoratives. Also, I would leave some few centimeters (or, preferably, more) space from the floor to avoid water to be in contact with planks (due to water from shower or cleaning tools) and to let air circulate between masonry wall and wood-wall. Similiar space would be needed up near ceiling.
2. Proper wood treatment.
This will require appropriate info on what you got in stores - all of these chemicals that render your wood water- and moisture-proof (at least for some years...). On that I advise to talk to some shot helper that seem to have proper knowlege.
EDIT concerning question edit :)
The space between masonry and wood is to be kept, I'm afraid. Here are some reasons:
it allows air (and often steam) to travel op the wall; moisture has an occasion to evaporate
using supportive planks lets you not to drill that many holes in a wall (cuz you will connect decorative planks to supportive planks with screws)
it allows planks to deform, avoiding some of tensions that would lead to look bad/destroy it
I'm aware that it may not look as intended with this visible difference between wood and tiles, but you may try either to neutralize that view or use it to your benefit (better visual effect). You can achieve that whatever you like (covering first line of tiles with last line of wood; plaing decorative hangers and so on...).
Of course, You can glue/attach wood to the wall with some glu-ish adhesive, but I guess that wood will 'work' and deform over time. If, later on, You would decide that any refinishing is to be done, it would be easier to unatttach the screws than tearing down (un-glue) all of them.
I would also wait for other DIY-ers to give their opinions as well. Mine is one of many, and I know it :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple cases of Jung's Theorem
Jung's theorem states that if $A\subset\mathbb{R}^n$ and $0<d=\operatorname{diam}(A)<\infty$, then there exist a unique closed ball $\bar{B}(x,r)$ of radius $r$ where $$r=\sqrt{\frac{n}{2(n+1)}}d$$that contains A.
The book I'm reading (an introductory real analysis book) only mentions this results and asks, as an exercise, to check that the theorem is true when $A$ is an equilateral triangle in the plane or a regular tetrahedron in the space, and that the constant $\sqrt{\frac{n}{2(n+1)}}$ is the best possible .
Now, I can see that in those simple cases, $A$ is indeed contained in a closed ball with center its center of gravity and radius $r$ just described. However, I can't figure out why this radius is the best possible... This is just chapter 1 of the book, so I'm expecting some simple ways to explain this but it's quite challenging.
To summarize, assuming $A$ is an equilateral triangle in the plane or a regular tetrahedron in the space, why is the radius $r$ the best possible to cover $A$? Also, why is such a closed ball with radius $r$ unique? Please enlighten me.
A:
To put matters straight:
Let $R$ be the set of all real numbers $r>0$ such that the given set $A\subset{\mathbb R}^n$ is contained in some closed ball of radius $r$. Then the number $\rho:=\inf R$ is uniquely determined.
Jung's theorem states that
$$\rho\leq\sqrt{{n\over2(n+1)}}\>{\rm diam}(A)\ .$$
Furthermore it can be proved by some compactness arguments that there is actually a ball $B_\rho$ of radius $\rho$ containing $A$, and this ball is uniquely determined.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.