text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
How to increase the line height of RStudio editor?
I wonder if there are any ways to increase the line height of the coding in RStudio.
Someone said that the following seems to work in the active.rstheme:
#rstudio_source_text_editor div { line-height: 1.3 !important; }
So I added it to the end of the active.rstheme but it didn't work.
That command worked for me. Be sure to remove the "#" at the start of the line, and perhaps instead of "1.3" change it to "1.8" so the difference is clearer? Also, what rstheme are you using?
@jared_mamrot Thank you. I have removed the "#" but it still cannot work. Is it because of the rstheme I'm using? I'm using Material now. What rstheme are you using?
I'm using a custom theme (atom dark); not sure what else to try - perhaps someone will come up with an answer or you could post your question to https://community.rstudio.com/
Adding the line-height to the ace_editor selector in the .rstheme file worked for me.
.ace_editor, .rstudio-themes-flat.ace_editor_theme .profvis-flamegraph,
.rstudio-themes-flat.ace_editor_theme, .rstudio-themes-flat .ace_editor_theme {
background-color: #282c34;
color: #abb2bf;
line-height: 1.3 !important;
}
However, there may be a better way.
| common-pile/stackexchange_filtered |
How to remove gaussian noise from an image in MATLAB?
I'm trying to remove a Gaussian noise from an image. I've added the noise myself using:
nImg = imnoise(img,'gaussian',0,0.01);
I now need to remove the noise using my own filter, or at least reduce it. In theory, as I understand, using a convolution matrix of ones(3)/9 should help and using a Gaussian convolution matrix like [1 2 1; 2 4 2; 1 2 1]/9 or fspecial('gaussian',3) should be better. Yet, they really don't do the trick so well:
Am I missing something important? I need to use convolution, by the way.
The averaging filter (your "ones" filter) is a bad low-pass filter. The gaussian is a better LPF. The reason you are getting distortion on the 1 2 1; 2 4 2; 1 2 1 filter is because it isn't normalized properly.
You're right about the 1 2 1;2 4 2;1 2 1. I should have divided by 16 and not by 9. Even so, it's not working too well:
link
You are not missing anything!
Obviously, you can't remove the noise completely. You can try different filters, but all of them will have a tradeoff:
More Noise + Less blur VS Less Noise + More blur
It becomes more obvious if you think of this in the following way:
Any convolution based method assumes that all of the neighbors have the same color.
But in real life, there are many objects in the image. Thus, when you apply the convolution you cause blur by mixing pixels from different adjacent objects.
There are more sophisticated denoising methods like:
Median denoising
Bilateral filter
Pattern matching based denoising
They are not using only convolution. By the way, even they can't do magic.
Thanks. I've seen that tradeoff during implementation and I've also implemented median denoising which works great for salt&pepper noise but not so much for Gaussian noise.
Still, how can I find the thin boundary between an image that is too noisy but sharp and an image that is too blurry but with a little noise?
I have a few parameters to play with: Matrix dimensions (small, large, square, rectangular) and matrix values (Gaussian, uniform, some other weird setting).
So, is there really nothing decent I can do with just convolution?
@shwartz, unfortunately, not. You need at least some kind of logic that will detect edges, corners, etc and will treat them accordingly. Which isn't only convolution by definition.
Actually, that's kind of encouraging since the assignment is to use convolution (solely, as I understand). Only problem is to find a "good" method and how to know which result is best. Is there any way to quantify the quality of the result? For example, will some sort of matrix distance from the original noise-less image be a good way to determine the quality of my result? Or is there some other common method?
I suggest that you ask another question on the subject :) You can put a link to this one.
@Andrey I am interested in what you have said... should I ask a new question all together on stack exchange? What I am trying to understand is the trade off between cancelling noise, but not cancelling edges... perhaps a summary of some of those techniques. (I have come across 'ansiotropic diffusion' for example)... how do those work? What is being changed? Thanks.
you can use wiener2 which works best when the noise is constant-power ("white") additive
noise, such as Gaussian noise.
You made a mistake with the Gaussian convolution matrix. You need to divide it by 16, not 9, so that it's sum equals 1. That's why the resulting image using that matrix is so light.
Thanks, I know. Someone already commented below the original post.
| common-pile/stackexchange_filtered |
How to copy all hlsearch text to clipboard in Vim
file.txt
abc123
456efg
hi789j
command
:set hlsearch
/\d\+
I want to copy highlighted text bellow to clipboard (or register):
123
456
789
Just like
egrep -o '[0-9]+' file.txt
Thanks.
One can follow the below procedure.
Empty a register (for instance, "a).
qaq
or
:let @a = ''
Run the command1
:g/\d\+/norm!//e^Mv??^M"Ay
If it is necessary to append a new line character after each of the
matches, run this command instead:2
:g/\d\+/norm!//e^Ma^M^[??^Mv$"Ayu
Type ^M as Ctrl+V then Enter (or
Ctrl+M), type ^[ as
Ctrl+V then Esc (or
Ctrl+[). In order not to retype the pattern
that just have been used in search, one can press
Ctrl+R, / to automatically insert
last search pattern.
Also one can record the command to execute on matched lines (the part
following norm!) as a macro. This allows to see the actions
immediately on a sample line and to make sure they are correct. Then,
the macro can be applied using :global:
:g/\d\+/norm!@z
1 At the top level, the command is a :global executing the Ex
command norm!//e^Mv??^M"Ay on each of the lines that match the pattern
\d\+. The Ex command begins with the norm! command to execute the Normal
mode commands //e^Mv??^M"Ay. These are three commands separated by the
carriage return symbol ^M. The first one, //e, looks for the search
pattern (which is set to the pattern used in the global command) and put the
cursor to the last symbol of the match (because of the flag e, see :help
search-offset). Then v command starts Visual mode. The command ?? looks
for the last search pattern backwards (and put the cursor to the first
character of the match), thus selecting the text that match the last search
pattern. The last command, "Ay, yanks the selected text appending it to the
a register.
2 The second global command resembles the first one in outline.
At each of the matched lines, it moves cursor to the last symbol of the match
and inserts newline after that symbol. Then it puts the cursor to the start
of the match and selects (in Visual mode) everything up to the end of line
(including just inserted newline). Finally, the command appends the selected
text to the register, and undoes newline inserting.
3 One can always see the actions recorded in particular macro by
examining the contents of the corresponding register using :di z or "zp,
for example.
it's very hard to understand //e^Mv??^M"Ay, could you please explain it? thank you
?? is very uncommon. qaq is very good. I never seen before.
could you point where can I get more information about ^M? thanks
That's some serious vim-fu in your global command. Thanks for the tip.
@freitass: I believe, there is no description dedicated to ^M code in Vim help. ^M is the escape code of the carriage return character. To type some characters that could not be entered the other way (as carriage return here—pressing Enter key would not insert CR, running incomplete command), Ctrl+V is used (see :help c_CTRL-V and :help i_CTRL-V).
@a becomes a long string, and no newlines or white space between them.
@Kev: I didn't notice that you need to separate copied matches with newlines, as it is not stated strictly in the question. Anyway, it's not any harder to take that into account (see updated answer).
If your text obeys the pattern you posted you can start visual mode blockwise with Ctrl+V and select from 1 in the first line to 9 in the last line. Then you just copy to the + register, which is the system clipboard, by typing "+y.
Edit:
I have tested this new solution for the text:
abc123
456efg
hi789j
Replace all non-digit by nothing with :%s/\D//g and the result will be:
123
456
789
Copy it to the clipboard typing "+y%, then revert the changes with u and you are done.
it's not rect-block in most case
I think there is no way to append text to registers, the solution I found was by changing the buffer to the result you want and then undo the changes. You will have to type u just once to get to the original text.
I just figured out a long command :g/^/call setreg('X', matchstr(getline('.'), '\d\+') . "\n"). It's too long, there must be a simple one.
Use this command to extract all URLs, and append to the end of file:
:let urls = [] | %s/http:[^"]*/\=add(urls, submatch(0))[-1]/g | call setline(line('$')+1, urls)
| common-pile/stackexchange_filtered |
Application of Seifert-van Kampen Theorem
I am trying to wrap my head around the following problem: I have three objects lined up horizontally, a $2$-sphere, a circle, and another $2$-sphere. It is the wedge sum $S^2 \vee S^1 \vee S^2$. I am trying to find the fundamental group of this space as well as the covering spaces. For the fundamental group, I believe that I can use van Kampen in the following manner:
$$\begin{align*}
\pi_1(S^2 \vee S^1 \vee S^2) &= \pi_1(S^2) * \pi_1(S^1 \vee S^2) \\
\pi_1(S^2 \vee S^1 \vee S^2) &= 0 * \pi_1(S^1 \vee S^2) \\
\pi_1(S^2 \vee S^1 \vee S^2) &= 0 * (\pi_1(S^1) * \pi_1(S^2)) \\
\pi_1(S^2 \vee S^1 \vee S^2) &= 0 * \mathbb Z * 0
\end{align*}$$
Does this make sense?
I am still trying to work out how to find the covering spaces.
Let the space be $W$. Then as you have seen Seifert-van Kampen tells us that $\pi_1 (W)\cong \mathbb{Z}$, and more generally $\pi_1(V\vee U)\cong \pi_1(V)*\pi_1(U)$. But this is also intuitively true: Say I had a big loop in our space $W$. We know the fundamental group of the circle is $\mathbb{Z}$, and since any higher dimensional sphere is simply connected, I can just contract the parts of the loop on the $2$-spheres so that the big loop becomes only a loop on the circle. This gives us a correspondence between loops in the space $W$, and loops in the circle.
The universal cover will be an infinite line with a string of $S^2$'s attached to it. The deck transformations are generated by motion two steps to the right. Do you see how to get the other covering spaces?
Thanks a lot for the help; I really appreciate it. I'm sorry, but I am not seeing how to get the other covering spaces. What is the best way to begin deriving them?
You're correct about the computation of $\pi_1$, though depending on the level a bit more work may need to be shown (i.e., how does Seifert- van Kampen give the results you stated). Also, $0*\mathbb{Z}*0$ is naturally isomorphic to $\mathbb{Z}$, and you may want to mention this.
As far as the covering space aspect, it may help to note that $S^2\vee S^1\vee S^2$ is homeomorphic to $S^1\vee S^2\vee S^2$ and you somehow need to "unravel" the $S^1$. Since the universal cover of $S^1$ is $\mathbb{R}$, it should be no surprise that $\mathbb{R}$ enters the picture somehow when finding the universal covering space.
In fact, you might guess that the universal cover is $\mathbb{R}\vee S^2\vee S^2$, since this space is simply connected. Unfortunately, this isn't correct. The problem is that every $2\pi$ along the $\mathbb{R}$ piece should project to the wedge point which has an $S^2\vee S^2$ attached to it. So, our next guess is that the universal cover is a copy of $\mathbb{R}$ with an $S^2\vee S^2$ attached to each point of the form $2\pi k$ for $k\in\mathbb{Z}$. Now that you have the picture in mind, I'll leave it to you to try to prove this space is the universal cover.
More, in fact, is true: If $X$ is simply connected, then the universal cover of $S^1\vee X$ is $\mathbb{R}$ with an $X$ wedged to each point of the form $2\pi k$. Your proof in the $S^2\vee S^2$ case will likely automatically generalize to this statement.
I think I understand. And by this same logic, would the regular covers be S2∨S2 attached to points of the form 2pik for k∈Z?
I don't understand what you're asking. All of the covers, in this case, would be regular. If you attach $S^2\vee S^2$ to poitns of the form $2\pi k$, you get the universal cover. You have to attach $S^2\vee S^2$ to a circle (some number of times) to get the other covering spaces.
All right i see now. I apologize for the confusion. Thank you for your help!
The fundamental group of $S^2\vee S^1\vee S^2$ is $\mathbb{Z}$ as you stated ($S^2\vee S^2$ is simply connected, wedge with a circle gets you $\mathbb{Z}$). For each subgroup $n\mathbb{Z}$ of $\mathbb{Z}$ there is a covering space corresponding to that subgroup. These are "bracelets" with a sphere attached at regular intervals ($S^1$ with spheres attached), with $n\mathbb{Z}$ corresponding to the bracelet with $n$ beads. For $n=0$ the universal cover is an infinite bracelet ($\mathbb{R}$ with spheres attached).
This is assuming that the wedge points are distinct, else the "beads" on the bracelet come in pairs
| common-pile/stackexchange_filtered |
Foreign key use with user model upload
These are my models and one user can upload multiple videos but one video belongs only to one user. How do I use the foreign key concept over here? When I add a user, does this automatically add a username in the Video model? If not, how do I do that? I'm very new to django over here
class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='')
def __str__(self):
return self.username
class Video(models.Model):
username=models.ForeignKey(User,on_delete=models.CASCADE,default="")
video=models.FileField(upload_to='videos/%Y/%m/%d/',default='')
videotitle=models.CharField(max_length=100)
likes=models.PositiveIntegerField(default=0)
dislikes=models.PositiveIntegerField(default=0)
def __str__(self):
return self.video
Take a look at this! https://docs.djangoproject.com/en/1.10/topic…
Not, it won't do it automatically -- and how would it do that. You need to pass user. Also you definitely don't want to add a username, but a reference to a User object. This is misleading in the code as you have a "username" in the Video class, which acutally is not just a name (string), but a ForeignKey -- a reference to an object User when adding the new video. So what you need to do when adding a video is something along the lines of:
def add_new_video(username, filename, title):
owner = User.objects.get(username=username)
newvid = Video(username=owner, video=filename, videotitle=title)
newvid.save()
assuming that likes and dislikes will be added later on...
ok... reading the post from @Niels, it is possible to fill it out automatically if you want to add the currently logged in user... but that was not part of the question ...
Thanks. Got it. The video is now being uploaded properly
Try the following
from django.db import models
from django.conf import settings
class Video(models.Model):
...
username = models.ForeignKey(settings.AUTH_USER_MODEL)
Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.
More info can be found here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model
| common-pile/stackexchange_filtered |
Numba @jit fails to optimise simple function
I have a pretty simple function which uses Numpy arrays and for loops, but adding the Numba @jit decorator gives absolutely no speed up:
# @jit(float64[:](int32,float64,float64,float64,int32))
@jit
def Ising_model_1D(N=200,J=1,T=1e-2,H=0,n_iter=1e6):
beta = 1/T
s = randn(N,1) > 10
s[N-1] = s[0]
mag = zeros((n_iter,1))
aux_idx = randint(low=0,high=N,size=(n_iter,1))
for i1 in arange(n_iter):
rnd_idx = aux_idx[i1]
s_1 = s[rnd_idx]*2 - 1
s_2 = s[(rnd_idx+1)%(N)]*2 - 1
s_3 = s[(rnd_idx-1)%(N)]*2 - 1
delta_E = 2.0*J*(s_2+s_3)*s_1 + 2.0*H*s_1
if(delta_E < 0):
s[rnd_idx] = np.logical_not(s[rnd_idx])
elif(np.exp(-1*beta*delta_E) >= rand()):
s[rnd_idx] = np.logical_not(s[rnd_idx])
s[N-1] = s[0]
mag[i1] = (s*2-1).sum()*1.0/N
return mag
MATLAB on the other hand takes less than 0.5 seconds to run this!
Why is Numba missing something so basic?
You are calling NumPy functions on scalar values in the loop body. These functions are designed to operate efficiently over large arrays, not single values. These function calls cannot be optimised away by numba. In short, you need to vectorise the code, not JIT-compile it.
@ajcr I think some of them can, actually, like rand() and ndarray.sum() (at least, they can in the latest version of numba).
@jme: ah, thanks, I wasn't aware that that was the case. I had thought that repeatedly calling np.logical_not (and other compiled functions) would slow down the loop. I ought to dig a little deeper into the numba docs.
Here is a reworking of your code that runs in about 0.4 seconds on my machine:
def ising_model_1d(N=200,J=1,T=1e-2,H=0,n_iter=1e6):
n_iter = int(n_iter)
beta = 1/T
s = randn(N) > 10
s[N-1] = s[0]
mag = zeros(n_iter)
aux_idx = randint(low=0,high=N,size=n_iter)
pre_rand = rand(n_iter)
_ising_jitted(n_iter, aux_idx, s, J, N, H, beta, pre_rand, mag)
return mag
@jit(nopython=True)
def _ising_jitted(n_iter, aux_idx, s, J, N, H, beta, pre_rand, mag):
for i1 in range(n_iter):
rnd_idx = aux_idx[i1]
s_1 = s[rnd_idx*2] - 1
s_2 = s[(rnd_idx+1)%(N)]*2 - 1
s_3 = s[(rnd_idx-1)%(N)]*2 - 1
delta_E = 2.0*J*(s_2+s_3)*s_1 + 2.0*H*s_1
t = rand()
if delta_E < 0:
s[rnd_idx] = not s[rnd_idx]
elif np.exp(-1*beta*delta_E) >= pre_rand[i1]:
s[rnd_idx] = not s[rnd_idx]
s[N-1] = s[0]
mag[i1] = (s*2-1).sum()*1.0/N
Please make sure the results are as expected! I changed much of what you had, and can't guarantee that the calculations are correct!
Working with numba requires a little care. Python functions, as well as most numpy functions, cannot be optimized by the compiler. One thing I find helpful is to use the nopython option to @jit. This means that the compiler will complain whenever you give it some code that it can't really optimize. You can then look at the error message and find the line that will likely slow down your code.
The trick, I find, is to write a "gateway" function in Python that does as much of the work as possible using numpy and its vectorized functions. It should create the empty arrays that you'll need to store the results in. It should package all of the data you'll need during the computation. Then it should pass all of these into your jitted function in one big, long argument list.
Case in point: notice how I handle random number generation in the jitted code. In your original code, you called rand():
elif(np.exp(-1*beta*delta_E) >= rand()):
But rand() can't be optimized by numba (in older versions of numba, at least. In newer versions it can, provided that rand is called without arguments). The observation is that you need a single random number for every one of the n_iter iterations. So we simply create a random array using numpy in our wrapper function, then feed this random array to the jitted function. Getting a random number is then as simple as indexing into this array.
Lastly, for a list of the numpy functions that can be optimized by the latest version of the compiler, see here. In my reworking of your code I was aggressive in removing calls to numpy functions so that the code would work over more versions of numba.
Excellent! Thanks for the detailed response. The Numba docs are a bit sparse on details.
| common-pile/stackexchange_filtered |
Efficiently removing missing values from the start and end of multiple time series in 1 data frame
Using R, I'm trying to trim NA values from the start and end of a data frame that contains multiple time series. I have achieved my goal using a for loop and the zoo package, but as expected it is extremely inefficient on large data frames.
My data frame look like this and contains 3 columns with each time series identified by it's unique id. In this case AAA, B and CCC.
id date value
AAA 2010/01/01 NA
AAA 2010/02/01 34
AAA 2010/03/01 35
AAA 2010/04/01 30
AAA 2010/05/01 NA
AAA 2010/06/01 28
B 2010/01/01 NA
B 2010/02/01 0
B 2010/03/01 1
B 2010/04/01 2
B 2010/05/01 3
B 2010/06/01 NA
B 2010/07/01 NA
B 2010/07/01 NA
CCC 2010/01/01 0
CCC 2010/02/01 400
CCC 2010/03/01 300
CCC 2010/04/01 200
CCC 2010/05/01 NA
I would like to know, how can I efficiently remove the NA values from the start and end of each time series, in this case AAA, B and CCC. So it should look like this.
id date value
AAA 2010/02/01 34
AAA 2010/03/01 35
AAA 2010/04/01 30
AAA 2010/05/01 NA
AAA 2010/06/01 28
B 2010/02/01 0
B 2010/03/01 1
B 2010/04/01 2
B 2010/05/01 3
CCC 2010/01/01 0
CCC 2010/02/01 400
CCC 2010/03/01 300
CCC 2010/04/01 200
I have identified the unique id's (60,000 of them)
Then used a for loop to loop through them, each time then creating a subset for the code and creating a zoo object
Then using zoo packages trim function to strip leading and trailing missing values
Then rbinding each to a new data frame that will contain the trimmed time series data in the end.
As expected, this is very ineficient.
I would do it like this, which should be very fast :
require(data.table)
DT = as.data.table(your data) # please provide something pastable
DT2 = DT[!is.na(value)]
setkey(DT,id,date)
setkey(DT2,id,date)
tokeep = DT2[DT,!is.na(value),rolltolast=TRUE,mult="last"]
DT = DT[tokeep]
This works by rolling forward the prevailing non-NA, but not past the last one, within each group.
The mult="last" is optional. It should speed it up if v1.8.0 (on CRAN) is used. Interested in timings with and without it. By default data.table joins to groups (mult="all"), but in this case we're joining to all columns of the key, and, we know the key is unique; i.e., no dups in key. In v1.8.1 (in dev) there isn't a need to know about this and it looks after you more.
I was preparing an answer with data.table, too, but it's good that Matthew beat me to it. However, one alternative would be to use the na.trim function from the zoo package. Something like DT[, na.trim(.SD), by = id, since that function accepts objects other than zoo objects.
@BenBarnes Sounds good, and shorter. Interesting to see which is faster.
@Matthew Dowle Works perfectly and extremely fast. Does exactly what I was interested in and I can prove to the die hard SAS coders at my office once again that R is a viable alternative. I think this executed way faster that their SAS alternative.
@BenBarnes I'm going to look into your suggestion about using na.trim as well.
@sizeight, Matthew's answer is much faster than mine (especially with a large amount of data). Trust the person who made the tools to know how to use them best!
@Matthew Dowle I upgraded to data.table 1.8.8 today and ran into problems with the above solution. I get an error "Attempting roll join on factor column x.date. Only integer, double or character colums may be roll joined." Any suggestions?
If your data is in data frame data
fun <- function(x)
{
x$value[is.na(x$value)] <- "NA"
tmp <- rle(x$value)
values <- tmp$values
lengths <- tmp$lengths
n <- length(values)
nr <- nrow(x)
id <- c()
if(values[1] == "NA") id <- c(id, 1:lengths[1])
if(values[n] == "NA") id <- c(id, (nr-lengths[n]+1):nr)
if(length(id) == 0)return(x)
x[-id,]
}
do.call(rbind,
by(data, INDICES=data$id,
FUN=fun))
Not the most elegant solution I guess. In the mood of this post.
| common-pile/stackexchange_filtered |
lot of internal links to one not relevant internal page may distort google's opinion of site content?
if I have a lot of pages talking about cars, and nearly any of them point to
/gray-cars.htm or /city-cars.htm
because they are the most sold ones... do you think that
/red-cars.htm and /super-cars.htm
will appear less important in google's opinion about the site, that talks about any type of car, not only the gray / city ones?
It might help if you explained in more detail what you want to accomplish. Is it to rank higher when a user searches for "red cars"? Or just to have red-cars.html show up before gray-cars.htm when the user searches for just "cars"? Or something else?
Of course. If you're linking to those other pages more you're in effect telling Google those pages are more important. And they are since you're selling more of them then the other ones.
thank you for the answer! rel="nofollow" will help? or it is better some javascript solution? thanks!
rel=nofollow probably won't help: you can use it to reduce the rank of they gray/city cars pages, but that won't increase the rank of the red/super cars pages (except in a purely relative sense).
If your goal is to increase the ranking of the red cars pages, etc, get more incoming links from other websites to them.
my goal is get all pages at the same identical rank (internally)... then nofollow may help? thank you
nofollow will only reduce PR of pages gray-cars/city-cars page WITHOUT increasing PR of othe red-cars pages in your sie. According to Matt Cutts (Google's alter ego) links with nofollow do not save your PR to flow away, the PR flows but evaporates instead of being passed to other pages, read this: http://www.mattcutts.com/blog/pagerank-sculpting
@MarcoDemaio hi, but what about internal links (links between pages on the same site) ?
It applies to all links
| common-pile/stackexchange_filtered |
Store specific value in javascript when multiple forms are present
I've got a list of 10-20 objects on each page creating these forms:
<div id="routeTable">
{% for route in route_list %}
<div id="routeDone">
<form class="doneForm" action="/route/complete/" method="post">
<input type="hidden" name="route_id" value="{{ route.route_id }}" />
<input type="hidden" name="next" value="{{ request.get_full_path }}" />
<input type="submit" value="Done" class="doneButton" />
</form>
</div>
{% endfor %}
</div>
And I'm trying to add some jquery to the page in order to intercept the usual form submit and instead do so using ajax as below. (I already have a view that returns an html chunk which will be swapped out for the above div#routeTable. The problem is line 4 "var route_ID...":
<script>
$(document).ready(function() {
$(".doneForm").submit(function() {
var route_id = $(this).attr('input[name=route_id]').val()
$.ajax({
type: "post",
url: "/route/complete/",
data: route_id,
success: function(data) {
$("#routeTable").html(data);
}
});
return false;
});
});
</script>
Unfortunately I'm having trouble passing the proper route_id into the js variable named route_id. I expect it will require use of the 'this' keyword, but I haven't been able to figure out exactly how.
Any suggestions on how to fix up my javascript would be greatly appreciated.
Try to change
var route_id = $(this).attr('input[name=route_id]').val()
to
var route_id = $(this).find('input[name=route_id]').val()
The reason being that input[name=route_id] is not an attribute, but a selector that represent a tag input and an attribute on that tag [name=route_id].
You could also do
var route_id = $('input[name=route_id]',this).val()
var route_id = $(this).attr('input[name=route_id]').val()
Should be something like:
var route_id = $(this).find('input[name=route_id]').val()
| common-pile/stackexchange_filtered |
Rent Increase for Section 8 tenants
We live on a property managed by a non-profit housing cooperation claiming to promote quality affordable housing.
We receive Section 8 and when we moved here in 2008, the rent was $1110.00/month, and in December 2015, the rent was $1300.00/month. Effective January 2016, management increased the rent to $1810.00/month. Our share of the rent went up $500/month. We've paid this months rent, but will not be able to pay next months rent without sacrificing two other monthly bills, since we are now paying about 70% of our gross monthly income for rent on a "affordable" housing property. Comparable apartments on the property are currently advertised for rent at $1500-$1600/month. And, the neighboring rentals of much higher quality with more amentities, are cheaper than $1810.00/month.
I've called numerous state and federal housing offices trying to get help on what to do, and no one seems to have answers as they keep refering me to other offices. Even the State Housing Authority that handles our Section 8 doesn't have answers. Who can I call for help?
what country and state are you in?
Reference to Section 8 almost surely means the poster is in the USA. I added country tag.
I'm not sure this really falls under personal finance, as your question is "who can I call for help?" However, one possibility is to look up local rental housing mediation groups, tenants' associations, or legal aid offices. Also, have you talked directly to your landlord (i.e., someone at the company that owns the apartment) to ask about this?
I know Section 8 rents can be raised but they must be approved and a 60 day notice given to the tenants. As for calling for help - the State Housing Authority is who you would need to get answers from - even if it is like pulling teeth. I'm sure that department is about as efficient as the DVM system.
If your city has a 211 service, you can try calling them. It's free.
Thank you for responding. I am in the U.S.. I've called the State Housing Authority. They say they don't know what can be done. (Although they're the one who approved the increase) I plan to ask the property management how the increase makes it "affordable" for me based on my income. I also found there's a Renter's Protection Agency that handles complaints and the outcome is legally and binding.
Section 8 tenants have an agent assigned to them. You said your share is now $500. This implies the agent approved this apartment. Something seems wrong here.
I am a Realtor, and have rented sec 8 apartments. We need to justify a price, typically by showing other identical units at the same price, or if not identical, a detailed explanation as to the difference.
I'd call the agent and get a recommendation on another apartment. We prefer to charge a fair price and keep a good reputation with the local section 8 office. Your landlord may not care.
TITLE 42 / CHAPTER 8 / § 1404a
42 USC 1404a: Secretary of Housing and Urban Development; right to sue; expenses
Text contains those laws in effect on March 21, 2016
From Title 42-THE PUBLIC HEALTH AND WELFARE
CHAPTER 8-LOW-INCOME HOUSING
§1404a. Secretary of Housing and Urban Development; right to sue; expenses
The Secretary of Housing and Urban Development may sue and be sued only with respect to its functions under the United States Housing Act of 1937, as amended [42 U.S.C. 1437 et seq.], and title II of Public Law 671, Seventy-sixth Congress, approved June 28, 1940, as amended [42 U.S.C. 1501 et seq.]. Funds made available for carrying out the functions, powers, and duties of the Secretary of Housing and Urban Development (including appropriations therefor, which are authorized) shall be available, in such amounts as may from year to year be authorized by the Congress, for the administrative expenses of the Secretary of Housing and Urban Development. Notwithstanding any other provisions of law except provisions of law enacted after August 10, 1948 expressly in limitation hereof, the Secretary of Housing and Urban Development, or any State or local public agency administering a low-rent housing project assisted pursuant to the United States Housing Act of 1937 or title II of Public Law 671, Seventy-sixth Congress, approved June 28, 1940, shall continue to have the right to maintain an action or proceeding to recover possession of any housing accommodations operated by it where such action is authorized by the statute or regulations under which such housing accommodations are administered, and, in determining net income for the purposes of tenant eligibility with respect to low-rent housing projects assisted pursuant to said Acts, the Secretary of Housing and Urban Development is authorized, where it finds such action equitable and in the public interest, to exclude amounts or portions thereof paid by the United States Government for disability or death occurring in connection with military service.
I hope this helps you, i.e. the answer is you should call the above secretary.
| common-pile/stackexchange_filtered |
SQL Append criteria
I need to know where Xy Street can be found and I have 3 tables.
select t.nev
from hospital.person sz, hospital.place t, hospital.member ti
where 1=1
and sz.residence_placeid=t.placeid
and sz.residence_placeid=ti.placeid
and t.placeid=ti.placeid
and t.street like 'Xy Street %'
order by t.street
Addresses can also be found in table sz and ti. My question is how to append those to the criteria (like union or something like that)
First, you should eschew using commas in your FOR statement because it makes the query hard to read, and this style of query has been deprecated. Instead, use an explicit JOIN. Regarding your question, if the other two tables also have a street column for the address, then you can simply add two more conditions to your WHERE clause. Here is what your revamped query might look like:
SELECT t.nev
FROM hospital.person sz INNER JOIN hospital.place t
ON sz.residence_placeid = t.placeid
INNER JOIN hospital.member ti
ON sz.residence_placeid = ti.placeid AND t.placeid=ti.placeid
WHERE t.street like 'Xy Street %' OR
sz.street LIKE 'Xy Street %' OR
ti.street LIKE 'Xy Street %' OR
ORDER BY t.street
| common-pile/stackexchange_filtered |
Transforming data frame to a selection list in selectInput (Shiny)
I've a data frame corresponding to the sample below:
df = data.frame(subject=c("Subject A", "Subject B", "Subject C", "Subject D"),id=c(1:4))
I would like to transform this data frame to a list object that could be conveniently implemented in selectInput:
selectInput("subject", "Subject",
choices = #my_new_list )
I would like for the end-user to see the list of subjects in the selection and for the selectInput to return the corresponding numerical value (id).
If I attempt to get my list via:
df <- data.frame(lapply(df, as.character),
stringsAsFactors = FALSE)
df <- as.list(df)
The selectInput drop down menu shows all available options:
I'm only interested in listing subjects and passing the corresponding numerical values.
I am not sure about the structure you want to get. Maybe split(df$id, df$subject).
For the choices argument, you can use a named list, from the doc:
If elements of the list are named then that name rather than the value
is displayed to the user
To make the named list you could try:
your_choices <- as.list(df$id)
names(your_choices) <- df$subject
And in the app:
selectInput("subject", "Subject",
choices = your_choices )
this answer is an absolute jackpot. worked great for me. Tks NicE
Use setNames, for example:
selectizeInput('x3', 'X3', choices = setNames(state.abb, state.name))
like in this example http://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html
| common-pile/stackexchange_filtered |
How to make all the error responses for API access in Content-Type of application/json instead of Content-Type of text/html in Flask?
I am building a Flask app that support access by human users and through API. The /api path and its subpaths are dedicated for API access. All API access should receive a response in JSON, i.e., with Content-Type of application/json.
I have organized all API endpoints within a blueprint named api. Using the technique illustrated in Implementing API Exceptions, I have defined a custom error class called ApiAccessError and registered the handler for it in the api blueprint, so whenever ApiAccessError is raised in a view function in the api blueprint, the registered handler for ApiAccessError is invoked to generate a JSON response with Content-Type of application/json.
The issue I have with the current design is that whenever an error that is not an ApiAccessError is raised in handling an API request, the response to the request is not in JSON but in HTML, i.e. having Content-Type of text/html. Such an error can occur, for example, in accessing a GET-only API endpoint with the POST method. In this case, the server response is in HTML with status code of 405. I would like the response to be in JSON while keeping the status code of 405. How can set Flask to respond to the 405 error and all other default errors in JSON instead of HTML in handling API requests?
Try implementing a global error handler with the instructions from the page you linked, and using the flask request global with a check like request.path.startswith('/api') to decide to override the content-type or not
After further examination of the error handling mechanism through Application Errors, Error Handlers, Custom Error Pages, the source code, and @Jonhasacat's suggestion. I think the best way to accomplish what I wanted in the program is to register an error handler at the app level for HTTPException. In my application, this is done as:
def handle_http_exception(e: HTTPException):
if request.path.startswith(API_PATH):
# Start with the response represented by the error
resp = e.get_response()
# jsonify the response
resp.set_data(
json.dumps(
{
'name': e.name,
'err_msg': e.description
}
)
)
resp.content_type = 'application/json'
return resp
else:
return e
app.register_error_handler(HTTPException, handle_http_exception)
This works because, roughly speaking, all errors raised in the process of handling a request that is an instance of Exception is either an HTTPException or an error to be converted to HTTPException if it doesn't have a handler registered for handling it.
| common-pile/stackexchange_filtered |
How to include (a) multipage pdf in the background
I want to include one/several multipage PDFs as a background to print additional information on it (header, page number, ...)
Save the mwe Package documentation in the directory in order to work
\documentclass[oneside]{book}
\usepackage{mwe}
\usepackage{pdfpages}
\newcommand\invisiblesection[1]{%
\refstepcounter{section}%
\addcontentsline{toc}{section}{\protect\numberline{\thesection}#1}%
\sectionmark{#1}}
\begin{document}
\pagestyle{headings}
\part{First}
\invisiblesection{My section}
% Only single pages
\AddToShipoutPictureBG*{\includegraphics[page=1]{mwe}}
.\pagebreak
\AddToShipoutPictureBG*{\includegraphics[page=2]{mwe}}
.\pagebreak
\AddToShipoutPictureBG*{\includegraphics[page=3]{mwe}}
.\pagebreak
% ...
\part{Second}
\invisiblesection{My section 2}
% No headers, ...
\includepdf[pages=1-]{mwe}
\end{document}
\includepdf has the option pagecommand for that
@DG' Thanks! \includepdf[pagecommand={},pages=1-]{mwe} solves it!
| common-pile/stackexchange_filtered |
Stuck at proving convergence of the series that is dependent on a converging series
Suppose $\sum_{n=1}^{\infty}{a_n}$ converges, and $a_n > 0$. Does $$\sum_{n=1}^{\infty}{\dfrac{\sin(\sqrt{a_n})}{\sqrt{n}+na_n}}$$ converge or diverge?
Attempt: I was able to prove that it diverges, as shown below, but could not find an example.
Claim: $\sum_{n=1}^{\infty}{\dfrac{1}{\sqrt{n}+na_n}}$ diverges.
Proof: Since $\sum_{n=1}^{\infty}{a_n}$ converges, there exists a $n\geq n_0$ such that $$0 \leq a_n \leq 1$$
which gives, $$\dfrac{1}{\sqrt{n}+na_n} \geq \dfrac{1}{\sqrt{n}+n}$$ proving the claim.
Doing a limit comparison test for$\sum_{n=1}^{\infty}{\dfrac{\sin(\sqrt{a_n})}{\sqrt{n}+na_n}}$ with $\sum_{n=1}^{\infty}{\dfrac{1}{\sqrt{n}+na_n}}$ we get $$\lim_{n\rightarrow \infty}{\dfrac{\sin(\sqrt{a_n})}{\sqrt{n}+na_n}\cdot \dfrac{\sqrt{n}+na_n}{1}} = \sin(\sqrt{a_n}) < \infty$$ and hence the given series diverges. However, I am having trouble finding an example.
Thanks in advance!
But $\sin \sqrt{a_n} \to 0$, that can easily force convergence (consider $a_n = \frac{1}{n^2}$). To see if/that is always the case is not so easy/obvious.
Right, but the series may fail to converge even if $\lim_{n\rightarrow \infty}{b_n}=0$ where $b_n$ is the series in question.
It may, but it does not always. I have an example of $a_n$ with finite sum so that the modified series diverges.
True. But that is what the question is, does it always fail to converge for the above series? By the reasoning I showed above, it seems so.
@user85390 Daniel already gave you an example where it does converge: $a_n=\frac{1}{n^2}$. You can use limit comparison with $\sum\frac{1}{n^{3/2}}$ to prove it.
Not always. Notice the comparison test gave you limit zero. In this case you only get one implication about convergence between the series. Which one?
I think it should be open, as this is challenging than the one you have linked above.
Hint: It is easy to see it converges for some $(a_n)$. To see it could diverge, you may consider $a_n=\frac{1}{n(\log n)^2}$ for $n\ge 2$.
I was just about to add that counterexample. (+1)
@robjohn: Thank you. I'm using iPad and it is quite inconvenient for typing, so I decided to only give a hint rather than a full answer. Probably that's why I could post the answer earlier than you. :)
| common-pile/stackexchange_filtered |
Spring REST controller partial update existing resource
I want to perform a partial update for a resource. I had an idea that I could combine @ModelAttribute (to load the existing resource) and @RequestBody to populate it with the provided fields and then run @Valid. As I understand @ModelAttribute is invoked before anything else.
My Controller invokes the ModelAttribut and is using my ContentPatternConverter to create the ContentPattern entity correctly. Though after that is done I want to populate the "pattern" with the provided fields from @RequestBody and finally check if it is valid. Though my the ContentPattern is not populated with RequestBody after it was created via ModelAttribute.
@RequestMapping(value = "/patterns/{id}", method = RequestMethod.PUT, produces = "application/json")
@ResponseBody
public ResponseEntity<ContentPattern> updateContentPattern(Principal principal, @ModelAttribute("id") @RequestBody ContentPattern pattern) { //implementation }
Any ideas how to solve this using my approach or if there is another (better) solution?
UPDATE 1
After some more researching I came up with following solution.
Created my own annotation @RequestBodyPathVariable
Wrote RequestBodyPathVariableMethodArgumentResolver which implements HandlerMethodArgumentResolver. What it does is 1) Based on the URI path variable (e.g. patterns/{id}) gets the existing resource from a custom converter. 2) Creates an object from the request body. 3) Merges the existing and the provided resource. 4) Validates the final object. 5) Returns the final object
See gist for source code: https://gist.github.com/2687913
(A better/other merge method might be needed for other cases.)
Helpful links:
http://blog.42.nl/articles/leveraging-the-spring-mvc-3.1-handlermethodargumentresolver-interface
http://stackoverflow.com/questions/6591665/merging-two-objects-in-java
I was thinking about this, and here is what I would do (disclaimer, I haven't tried this):
First of all, @ModelAttribute will only serve if you want to pass that object to the view.
@RequestBody allows Spring to parse your input body (let's say it's Json) and build a ContentPattern object. But you want to get that object from your repository and then update the relevant fields.
First, I would create an implementation of WebArgumentResolver. Using MethodParameter you check that it is from class ContentPattern. This implementation will receive as Dependency Injection, the HttpMessageConverter you use to create the ContentPattern object.
Then you create a HttpInputMessage from the NativeWebRequest, like this:
return new ServletServerHttpRequest((HttpServletRequest)nativeWebRequest.getNativeRequest());
Then using the Converter, you create your ContentPattern object. This object will have some fields populated, the ones you want to update, and also its identifier.
Using the identifier, and your repository, or an EntityManager persistence context (both injected to the class by Spring), you get the object from your repository.
Now you have two ContentPattern objects, the one obtained from the repository, and the one created from the request body.
Using your object's setters, update the object from the repository with the fields of the other object, and then validate it using your Validator also injected to this class by Spring.
If everything is ok, optionally save the updated object to persistance, and use it as the returning value of the resolverArgument method.
I hope this is clear enough!
Thanks for your advice. I ended up using the same concept but implemented HandlerMethodArgumentResolver.
| common-pile/stackexchange_filtered |
best way to compare sequence of letters inside file?
I have a file, that have lots of sequences of letters.
Some of these sequences might be equal, so I would like to compare them, all to all.
I'm doing something like this but this isn't exactly want I wanted:
for line in fl:
line = line.split()
for elem in line:
if '>' in elem:
pass
else:
for el in line:
if elem == el:
print elem, el
example of the file:
>1
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA
>2
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>3
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA
>4
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA
>5
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>6
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG
>7
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA
So what I want if to known if any sequence is totally equal to 1, or to 2, and so on.
(1) How many sequences do you have per line? (2) Are you trying to find if a sequence in a line matches other sequences in the same line OR if a sequence in a line matches any other sequence in the same file? (3) Can you post some sample lines?
How many sequences do you want to compare?
DO you just need to know there are matches, or do you need the location too?
How large is the file -- specifically, can it be stored in memory?
Right now, I'm would only compare around 700sequences, so yes it would be nice to have the location also :)
@FM not very large, around 1532 lines and 73Kb. It's a text file
If the goal is to simply group like sequences together, then simply sorting the data will do the trick. Here is a solution that uses BioPython to parse the input FASTA file, sorts the collection of sequences, uses the standard Python itertools.groupby function to merge ids for equal sequences, and outputs a new FASTA file:
from itertools import groupby
from Bio import SeqIO
records = list(SeqIO.parse(file('spoo.fa'),'fasta'))
def seq_getter(s): return str(s.seq)
records.sort(key=seq_getter)
for seq,equal in groupby(records, seq_getter):
ids = ','.join(s.id for s in equal)
print '>%s' % ids
print seq
Output:
>3
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA
>4
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA
>2,5
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA
>7
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA
>6
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG
>1
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA
Thanks! It's a really nice trick, that I don't even had thought about it
The following script will return a count of sequences. It returns a dictionary with the individual, distinct sequences as keys and the numbers (the first part of each line) where these sequences occur.
#!/usr/bin/python
import sys
from collections import defaultdict
def count_sequences(filename):
result = defaultdict(list)
with open(filename) as f:
for index, line in enumerate(f):
sequence = line.replace('\n', '')
line_number = index + 1
result[sequence].append(line_number)
return result
if __name__ == '__main__':
filename = sys.argv[1]
for sequence, occurrences in count_sequences(filename).iteritems():
print "%s: %s, found in %s" % (sequence, len(occurrences), occurrences)
Sample output:
etc@etc:~$ python ./fasta.py /path/to/my/file
GTCGTCGAAAGAGGCTT-GCCCGCTACGCGCCCCCTGATA: 1, found in ['4']
GTCGTCGAAAGAGGCTT-GCCCGCCACGCGCCCGCTGATA: 1, found in ['3']
GTCGTCGAAAGAGGTCT-GACCGCTTCGCGCCCGCTGGTA: 2, found in ['2', '5']
GTCGTCGAAAGAGGTCT-GACCGCTTCTCGCCCGCTGATA: 1, found in ['7']
GTCGTCGAAGCATGCCGGGCCCGCTTCGTGTTCGCTGATA: 1, found in ['1']
GTCGTCGAAAGAGTCTGACCGCTTCTCGCCCGCTGATACG: 1, found in ['6']
Update
Changed code to use dafaultdict and for loop. Thanks @KennyTM.
Update 2
Changed code to use append rather than +. Thanks @Dave Webb.
You should use result[sequence].append(line_number) rather than result[sequence] = result[sequence] + [line_number] as the concatenation needlessly creates a new list.
In general for this type of work you may want to investigate Biopython which has lots of functionality for parsing and otherwise dealing with sequences.
However, your particular problem can be solved using a dict, an example of which Manoj has given you.
Comparing long sequences of letters is going to be pretty inefficient. It will be quicker to compare the hash of the sequences. Python offers two built in data types that use hash: set and dict. It's best to use dict here as we can store the line numbers of all the matches.
I've assumed the file has identifiers and labels on alternate lines, so if we split the file text on new lines we can take one line as the id and the next as the sequence to match.
We then use a dict with the sequence as a key. The corresponding value is a list of ids which have this sequence. By using defaultdict from collections we can easily handle the case of a sequence not being in the dict; if the key hasn't be used before defaultdict will automatically create a value for us, in this case an empty list.
So when we've finished working through the file the values of the dict will effectively be a list of lists, each entry containing the ids which share a sequence. We can then use a list comprehension to pull out the interesting values, i.e. entries where more than one id is used by a sequence.
from collections import defaultdict
lines = filetext.split("\n")
sequences = defaultdict(list)
while (lines):
id = lines.pop(0)
data = lines.pop(0)
sequences[data].append(id)
results = [match for match in sequences.values() if len(match) > 1]
print results
Great idea, but the implementation is very inefficient due to removing elements with pop(0) -- an O(n) operation per element for Python lists, so the total time complexity will be O(n^2). Not a worry for small examples, but not ideal for large collections of sequences. Best not to use this recipe verbatim.
| common-pile/stackexchange_filtered |
How POSIX compliant is "/path/file/.."?
I wanted to change current directory into shell script into directory, containing specific regular file. I found that following trick works in mksh and busybox sh:
path=/path/to/regular/file
cd $path/..
but not in GNU Bash:
bash: cd: /path/to/regular/file/..: Not a directory
Is this trick not posix-compatible, or Bash is too pedantic?
Latest edition of the standard doesn't allow that. POSIX.1-2017 cd spec. says that if the pathname component preceding dot-dot is not a directory, cd shall consider that an error.
From cd § DESCRIPTION - step 8.b:
b. For each dot-dot component, if there is a preceding component and
it is neither root nor dot-dot, then:
i. If the preceding component does not refer (in the context of
pathname resolution with symbolic links followed) to a
directory, then the cd utility shall display an appropriate
error message and no further steps shall be taken.
When cd is invoked with -P option, this step is omitted; but then chdir() fails if one of the pathname components names an existing file that is neither a directory nor a symbolic link to a directory.
Besides, permitting that trick also allows inconsistent behavior in cd. For example, when run in a directory containing a regular file named bar, and a directory named foo containing another directory named bar, the following two commands do different things in a shell where cd ignores non-directory components preceding a dot-dot, despite that CDPATH contains the empty string (i.e. the current working directory) in both cases.
CDPATH= cd bar/..
CDPATH=:foo cd bar/..
Below transcripts visualize the difference between non-conforming and conforming implementations clearly.
$ tree -F
.
├── bar
└── foo/
└── bar/
2 directories, 1 file
$ ash
$ CDPATH= cd bar/..
$ pwd
/home/oguz
$ CDPATH=:foo cd bar/..
/home/oguz/foo
$ bash
$ CDPATH= cd bar/..
bash: cd: bar/..: Not a directory
$ CDPATH=:foo cd bar/..
/home/oguz/foo
bosh, gwsh, ksh93u+m, and yash are other actively maintained shells that implement the same behavior as bash.
| common-pile/stackexchange_filtered |
Convert a full address to a separated by, city, region, zip code, etc
I have been searched by the internet, however I didn't find a perfect solution, so I faith that someone already did something like this.
So my issue is, I'm using a webservice were you send the VAT number and if is valid you got the Company info. However the address received is the full address not divided by parts.
For example:
Google Ireland VAT is IE6388047V
I got:
Company Name: GOOGLE IRELAND LIMITED
Address: 3RD FLOOR ,GORDON HOUSE ,BARROW STREET ,DUBLIN 4
So what I need is something like this:
3RD FLOOR ,GORDON HOUSE ,BARROW STREET ,DUBLIN 4
Converts this to:
Address: Ringsend Post Office, Gordon House, Barrow St
City: Dublin 4
Country: Ireland
Someone can help me and make the day?
Thank you so much!
Have you tried this geocomplete jquery library. This example is similar to what you are looking for http://ubilabs.github.io/geocomplete/examples/form.html
@sabinadhikari yes I Has, but if you try put the Google IE (GOOGLE IRELAND LIMITED 3RD FLOOR ,GORDON HOUSE ,BARROW STREET ,DUBLIN 4 ), for instance, we don't receive any response. I think this could be a good solution however is not a perfect one...
If you search 'GORDON HOUSE ,BARROW STREET ,DUBLIN 4' only in geocomplete it will give formatted address. So for that you can split the whole string into two parts and search with the second part of the string.
@sabinadhikari you are right, but to do that I need to create a little brain to know which parts I should ignore. This feature is to deal with all world addresses. :\
if you are using php explode the string which will split the string into two parts.
@sabinadhikari yes this will for Ireland... but so how can I deal with Portuguese address: ESTR DA PORTELA N 9 PORTELA DE CARNAXIDE 2790-124 CARNAXIDE ?
Parsing addresses is challenging because of the many formats you will encounter, even within a single country. There are services that can parse the input and even verify whether the address exists. They usually return the address in components as well as a composed whole. Unfortunately, parsing international addresses is usually only available via a paid service. One such service is provided by smartystreets.com:
International API documentation
International output fields
(Disclosure: I'm a developer at smartystreets.)
You can separate your address with array using PHP function explode(",",$address). It will separate your address after ", " and store in array...
| common-pile/stackexchange_filtered |
VB 2010 play wav files randomly Windows 8 RP
I need 5 wav files to play randomly at the end of my program. I know how to get it to play one song, and I found a code on this site already but it doesn't work for me, it just plays the same song every time. Here is the code:
Public Sub PlayRandomTrack()
Dim trackNum As Integer = CInt(Rnd() * 5 + 0.5)
Select Case trackNum
Case 1
My.Computer.Audio.Play(My.Resources.CallingMonsters, AudioPlayMode.Background)
Case 2
My.Computer.Audio.Play(My.Resources.McclainSisters, AudioPlayMode.Background)
Case 3
My.Computer.Audio.Play(My.Resources.Mendler, AudioPlayMode.Background)
Case 4
My.Computer.Audio.Play(My.Resources.Pray, AudioPlayMode.Background)
Case Else
My.Computer.Audio.Play(My.Resources.WillowWhip, AudioPlayMode.Background)
End Select
End Sub
and then I use it as:
PlayRandomTrack()
What am I doing wrong?
From MSDN:
For any given initial seed, the same number sequence is generated
because each successive call to the Rnd function uses the previously
generated number as a seed for the next number in the sequence.
Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.
figured this out RIGHT after I posted this, but thanks a lot!
Try this for your random function:
Dim tempRnd As New Random(Now.Millisecond)
Dim trackNum As Integer = tempRnd.Next(1, 5)
can you try this instead and see if it work?
Dim trackNum As Integer = (New Random).Next(1,5)
| common-pile/stackexchange_filtered |
SQL query to count secondary keys
For a given table, if I count the keys (other then the primary key) which are having NOT NULL and UNIQUE, both the constraints, will that give me count of secondary keys for that table?
If not, how to get count of secondary keys for a table by using SQL query?
Can you add an example to illustrate what you asking?
No there may be columns where they are not part of any index yet they aren ot null
Primary key and secondary keys make up candidate keys. Since, as per my understanding, candidate keys need to be unique and not null, shouldn't that help us to get count of secondary keys?
Yes and no. As you said in your own comment, it gives you candidate keys (provided there are constraints / indexes on them).
Imagine a country table. You could use the natural key, i.e. the country name, as its primary key. Then you would have a primary key and no other non null unique index. Okay so far.
Now you add an id to your country table. No matter if you decide to use this as the primary key or stay with the natural key, you will have one primary key and one non null unique index. So you've found your secondary key.
However, if for some reason someone adds another index containing both the country name and the id, then you'd get another non null unique index. However, I wouldn't consider this another secondary key. It's only another index to speed up certain lookups.
So yes, you can look for non null unique indexes to find secondary keys, but you are not done with it. You must also check if a thus found index is just a combination of other non null unique indexes. Get rid of these and that should be it.
Hello, is there sql query to calculate number of primary and secondary keys? I dont want to count foreign keys.. only primary and secondary keys.... is this possible?
| common-pile/stackexchange_filtered |
Use one JavaScript function with two forms
I have a JavaScript function for checking form input which sends an AJAX request to a PHP script. Here is the HTML:
<form method="post" id="textform35" action="insert_text.php">
<textarea id="text" cols="80" rows="3" placeholder="forecast text"></textarea>
<input type=hidden id="text_old" value="">
<input type=hidden id="sin_type" value="short">
<input type=hidden id="den" value="0">
<input type=hidden id="grad" value="България-в">
<input type=hidden id="span" value="1">
<input type="button" name="Submit" value="Submit" onclick="validate_sendForm()">
</form>
<form method="post" id="textform70" action="insert_text.php">
<textarea id="text" cols="80" rows="12" placeholder=" >> "></textarea>
<input type=hidden id="text_old" value="">
<input type=hidden id="sin_type" value="short">
<input type=hidden id="den" value="0">
<input type=hidden id="grad" value="България-в">
<input type=hidden id="span" value="1">
<input type="button" name="Submit" value="Запази" onclick="validate_sendForm()">
</form>
As you can see, there are two forms with identical elements but with different ids.
The function validate_sendForm() is as below:
function validate_sendForm() {
var text=document.getElementById("text").value;
var y=document.getElementById("text_old").value;
if (text==y) {
if (y=='') {
alert("some text ");
return false;
} else {
alert("another text ");
return false;
}
} else {
var city_id = document.getElementById("grad").value;
var fore_code = document.getElementById("sin_type").value;
var date_for = document.getElementById("den").value;
var date_span = document.getElementById("span").value;
var xhttp = new XMLHttpRequest();
var params="grad="+city_id+"&den="+date_for+"&span="+date_span+"&sin_file="+fore_code+"&tekst="+text;
xhttp.open("POST", "insert_text.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("Content-length", params.length);
xhttp.setRequestHeader("Connection", "close");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.send(params);
}
};
How can I use the function with both forms? Now it takes the values of the first form and never looks at the second one. I suppose I have to use "this" but have no idea where or how. Please, don't suggest that I use jQuery because I can not.
You are using id attribute with same value...id should be unique
Yes, otherwise I won't be able to use the function. I think there is a way to point to the form which has a unique id. That is what I am looking for.
Does you have to submit both form separately ? Or both should get submit on click of any one button ?
Separately. No need to do it with one button.
I resolved my problem by passing the sum of two random numbers as a parameter to validate_sendForm(). Then I concatenated the number to all element id s in the form, thus making them unique.
I will mark this as "accepted answer" not because it is the most elegant or correct one, but simply because that is what worked for me.
First of all I suggest you to change the input's id to class because an id must be unique.
now, in your case a good solution would be passing as param the form id to the function:
onclick="validate_sendForm('textform35')" ,
onclick="validate_sendForm('textform70')"
and then, selecting it inside the function, get the form inputs.
function validate_sendForm(_id){
var formEl = document.getElementById(_id);
// if you changed the input's id to class..:
var inptEl_textOld = formEl.querySelector("input.text_old");
var inptEl_sinType = formEl.querySelector("input.sin_type");
var inptEl_den = formEl.querySelector("input.den");
// ...
}
An other way is to pass this (instead of the form id) to your function which is the reference of <input type="button" you clicked.
like: onclick="validate_sendForm(this)"
and then take the element you need browsing the element's parents:
function validate_sendForm(_btn){
var formEl = _btn.parentElement.parentElement.querySelector("form");
// ...
}
To select the form inside the function can I do : document.forms["textform70"]["text"].value ?
no, document.forms is an array, you have to browse it with indexes https://developer.mozilla.org/it/docs/Web/API/Document/forms
, anyway if you have the id you can just get it using getElementById
I tried your first suggestion. Changed all "id" into "class" in HTML then copied your code and added a simple alert(inptEl_text); to display the result. In console it says TypeError: formEl.querySelector(...) is null regardless of what I type in textarea.
$(document).ready(function(){
$('input[name=Submit]').click(function(){
var id = $(this).parents('form').attr('id');
// submit form as per the id
});
});
You can get the id of the form on click using jquery. on basis of that id you can get the fields of the perticular form. If you don't want to use jquery, you can pass parameter 'this' from the method as already suggested in one of the comment. With this parameter you can discriminate the forms.
| common-pile/stackexchange_filtered |
System.QueryException: List has more than 1 row for assignment to SObject3
In the test class I am getting the error as above one?
Class.TW_RestAPI.getTwiML: Class.TW_RestAPITest.testPostRestService
@istest
public class TW_RestAPITest {
static testMethod void testPostRestService() {
Account acc=new Account();
acc.name='Test';
acc.AccountNumber='';
acc.Site='';
acc.Owner_Phone_Number__c='';
Insert acc;
Profile p = [select id from profile where name='System Administrator'];
User u = new User(alias = 'utest'<EMAIL_ADDRESS> emailencodingkey='UTF-8', lastname='Unit Test',
languagelocalekey='en_US',
localesidkey='en_GB', profileid = p.Id,
timezonesidkey='Pacific/central time',
username='unit.test@cap.com');
System.runAs(u) {
Group g=new Group();
g.type='Queue';
g.name='Twilio Requests';
insert g;
QueuesObject q1 = new QueueSObject(QueueID = g.id, SobjectType = 'Case');
insert q1;
}
String JsonMsg;
Test.startTest();
//As Per Best Practice it is important to instantiate the Rest Context
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/TW_RestAPI'; //Request URL
req.addParameter('To', '+31234567890');
req.addParameter('From', '1390296387');
req.addParameter('Body', 'Hello');
req.httpMethod = 'POST';//HTTP Request Type
RestContext.request = req;
RestContext.response= res;
TW_RestAPI.getTwiML(); //Call the Method of the Class with Proper Constructor
Test.stopTest();
}
}
my twilio rest class
@RestResource(urlMapping='/inboundmsg/*')
global without sharing class TW_RestAPI {
public TW_RestAPI() {
}
@HttpPost
global static void getTwiML() {
RestRequest req = RestContext.request;
RestResponse resp = RestContext.response;
resp.addHeader('Content-Type', 'application/xml');
system.debug(req.headers);
String respon;
String toPN = req.params.get('To');
String fromPN = req.params.get('From');
String msgBody = req.params.get('Body');
String areaCode = fromPN.substring(2,5);
String prefix = fromPN.substring(5,8);
String last4 = fromPN.substring(8);
String formattedPhone = '(' + areaCode +')' + ' ' + prefix + '-' + last4;
System.debug('FORMATTED PHONE IS: ' + formattedPhone);
List<Account> lAcc=[Select id,Owner_Phone_Number__c,Business_Phone_Number__c from account where Owner_Phone_Number__c=:formattedPhone or Business_Phone_Number__c=:formattedPhone];
Id twilioGroupId=[select id from group where name='Twilio Requests' and type='queue' ].id;
datetime dt = System.now()-1;
List<Case> lCase=[Select id from case where accountid=:lAcc[0].id and createdDate > :dt];
Case c=new Case();
if ( lCase.size() == 0 ) {
if ( lAcc.size() > 0 ) {
c.AccountId=lAcc[0].id;
}
c.Issue_Detail__c=msgBody;
c.Origin='Text';
c.phone__c=formattedPhone;
c.ownerid=twilioGroupId;
Database.DMLOptions options = new Database.DMLOptions();
options.assignmentRuleHeader.useDefaultRule = false;
c.setOptions(options);
insert c;
respon='Thanks for creating the case. Your case number is'+c.casenumber;
resp.responseBody = Blob.valueOf(respon);
}
SMS__c s=new SMS__c();
if ( lCase.size() == 0 ) {
s.Case__c=c.id;
} else {
s.Case__c=lCase[0].id;
}
s.subject__c=msgBody;
s.message_date__c=system.now();
s.Type__c='Inbound';
if ( c.Phone__c != null ) {
s.phone_number__c=c.Phone__c;
} else {
s.phone_number__c=formattedPhone;
}
insert s;
// Build your TWiML here.
}
}
We don't have any way of knowing what lines numbers are. You need to mark that in your code.
I am guessing your error is in the TW_RestAPI class, if adjusting the profile query didn't help. Can you share the code here?
ashock, when you post code, after pasting it into your post, please select it and click on the {} pre-formatted text icon so that it's legible to anyone who reads it. It's always a good practice to look at the preview pane of your post to fix any problems before posting it. There was a great deal of your post that wasn't visible. that's why you have 4 people have voted so far to close it. I took the time to look before voting.
Without knowing what line it's on, I can only guess but my assumption is that it's on your Profile query. If you are going to assign it to an SObject instance, you need to make sure you limit your query. This is because even with your name='System Administrator' filter, you may get multiple results because name is not unique and you could have duplicates.
So just do this..
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
Or, alternatively you can query to a list and assign it.
Profile p;
List<Profile> profiles = [SELECT Id FROM Profile WHERE Name='System Administrator'];
if(!profiles.isEmpty()) {
p = profiles.get(0);
}
Edit: Now that we see more of your code, it can be any one of the queries that tries to assign to an SObject. Another example of this is the query to get the twilioGroupId. Try implementing either the LIMIT or querying out a list as implemented above.
You have a custom profile you've created also called system administrator. I'd recommend changing your query as follows:
Profile p = [select Id from profile where name = 'system administrator' order by createddate asc limit 1];
This will always return the default system administrator profile.
Thanks. After doing still I am getting the same error.This is my error in the developer console.
| common-pile/stackexchange_filtered |
Text messages no longer associated with contact
My neighbour has a Nokia Lumia 520 and accidentally linked an existing contact ("Person A") with a new contact that he created ("Person B").
This has had some side-effect where Windows Phone seemed to get confused about text messages associated with Person A (the original contact). If he goes into the text message app, then it shows Person A's text messages under the name of Person B. If he goes into Person A's profile and selects the "Text" option, then nothing shows up at all.
To try and solve this, we deleted the "Person B" contact, and the text message app now shows the correct name on the existing message threads. However, when going via the profile, it still shows up as there being no messages.
Does anyone know how to fix up the contacts so that the existing text messages are correctly associated with the original contact again?
Can he try a call too? Because I'm having similar problem with calling.
That sounds very strange indeed,
I would guess that that is a software bug. what i would recommend is contacting Microsoft support or Nokia Care, and see if they can help you.
Just fixed in my case. I had phone number with its international format so I changed to the number plus area code and it fixed it.
Do you have international assist turned on?
@VitorCanova: Thanks for the suggestion - we tried that but no joy. Going to try just deleting the contact completely from both the phone and from the synchronized Outlook contacts, then re-adding it from the phone and see what happens.
You sure you don't have more than one contact with same number? Have you tried change the number using all combination with area code and country code?
Where are the contacts saved in his Microsoft Account?
Bug still isn't fixed as I've just experienced this exact same behaviour on a phone running the latest Dev preview
If your contacts are synced from an account (google or Live), the only way to solve this as of now is by choosing not to sync contacts settings->email+account-> untick contact synching, then sync your account and then tick the contact synching and resync again. This way will clear all bad cache and enforce linking correct contacts to SMS. The problem is, you will lose all the linking of contacts you have done earlier.
Thanks HaLaBi, this sounds good. I haven't had a chance to verify it yet, but will come back and let you know if it solved the problem.
| common-pile/stackexchange_filtered |
How to convert datetime from decimal to “%y-%m-%d %H:%M:%S” given the time origin?
I did my search around but I couldn't find an answer that satisfies my problem.
I am using python 3.7 and I need to convert a series of decimal numbers into datetime object in the form %Y-%m-%d %H:%M:%S. While doing so I need to consider an origin point, for example:
t = 0.000000 equals to 2016-06-25 00:00:00
t = 0.010417 equals to ..... ?
and so on. I know that in my decimal time the integer part is day since start, decimal part is fraction of day.
I have found an answer using R here. I also think that I might need to use the class method date.fromordinal(ordinal)or something similar but I cannot figure it out how to do it.
This is what I have tried so far:
example t = 1.010416
import datetime as DT
from datetime import timedelta
day = int(x)
datetime_object = DT.datetime.strptime("2016-06-25 00:00:00", '%Y-%m-%d %H:%M:%S')
python_datetime = DT.datetime.fromordinal(day) + timedelta(days=datetime_object.day-1)
I get:
datetime.datetime(1, 1, 25, 0, 0)
But I cannot add the year 2016 nor the month. Also, for every case in which int(t) = 0, I get:
ValueError: ordinal must be >= 1
Thank you very much for your answers
@glibdud I have edited the question
Just to leave a clear answer here, taking into account my comments on the other answers:
from datetime import datetime,timedelta
base_date = datetime(2016, 6, 25)
deltas = (2.34857, 0.010417, 1.010416)
for delta in deltas:
print((base_date + timedelta(delta)).strftime('%Y-%m-%d %H:%M:%S'))
That code yields the following ouput:
>>> from datetime import datetime,timedelta
>>>
>>> base_date = datetime(2016, 6, 25)
>>> deltas = (2.34857, 0.010417, 1.010416)
>>>
>>> for delta in deltas:
... print((base_date + timedelta(delta)).strftime('%Y-%m-%d %H:%M:%S'))
...
2016-06-27 08:21:56
2016-06-25 00:15:00
2016-06-26 00:14:59
>>>
timedelta stores its data in this format: (DAYS, SECONDS) so you can calculate it easily:
import datetime
t = 2.34857
# Full days
days = int(t)
# Part of a day
part_of_day = t - int(t)
seconds = int(part_of_day * 24 * 60 * 60)
# Calculate the time delta
dt = datetime.timedelta(
days=days,
seconds=seconds
)
# Add t-delta to the first day
first_day = datetime.datetime(2016, 6, 25)
current_time = first_day + dt
current_time
will return:
datetime.datetime(2016, 6, 27, 8, 21, 56)
Then you can convert it to a string with this function:
datetime.datetime.strftime(current_time, '%Y-%m-%d %H:%M:%S')
'2016-06-27 08:21:56'
Edit 1: Instead of constructing the timedelta by days-seconds, one can use just float days as parameter (thanks to accdias!):
dt = datetime.timedelta(days=t)
There is no need to break t into the integer and decimal parts and the conversion stuff. Just pass it as days for datetime.datetime(), it will do the right thing.
@vumux, my pleasure.
Another point: current_time in your code is already an instance of datetime.datetime. With that in mind you just need current_time.strftime('%Y-%m-%d %H:%M:%S').
I used it to show the existance of datetime object. Of course my code can be shortened. But I prefer to write more for someone to understand more :)
@vurmux Thanks a lot! I noticed I was almost there with thinking about adding the timedelta but I just did not make it well. Also I like constructing the timedelta by days-seconds because this gives me flexibility in rounding the microseconds if needed
@StefaniaR, datetime.datetime() will take care of microseconds as well. There is no need for all that conversion stuff. To check that, add a .%f to strftime() and you will see it. :-)
If you need nanoseconds resolution, take a look at PEP564.
| common-pile/stackexchange_filtered |
Is there a proof of the Hawking bound for the efficiency of a black holes merger?
Consider two black holes with masses $m_1,m_2$ and zero angular momenta
merging to form a single one with the mass $m$ and the rotation parameter $a=J/m$. Hawking, in "Black Holes in General Relativity" Commun. math. Phys. 25 (1972), 152—166 proposed an inequality
$$m^2+m\sqrt{m^2-a^2}>2(m_1^2+m_2^2)$$
for this process (in fact, for a more general one, see p. 14 of the paper). I learned about this bound ages ago from the Lightman-Press-Price-Teukolsky relativity problem book and had no doubt about it. But now I think that the proof given in this paper is total rubbish despite being published in a supposedly mathematical journal.
The inequality is derived from what is now called an area theorem which sates that the area of the event horizon never decreases. There is nothing wrong with the theorem itself except the way it is formulated makes it completely useless for obtaining an inequality of this sort. (And probably for any other meaningful conclusion.) The fishy point here is the assumption that the area of a black hole event horizon is given by the formula (in geometric units $c=G=1$)
$$A=8\pi m(m+\sqrt{m^2-a^2}).$$
No doubt, this assumption is true for a Kerr black hole but there is a big problem. The event horizon as it is defined in the formulation of the area theorem depends on the (arbitrarily distant) future evolution of a black hole, so even it the thing looks exactly as a standard Kerr black hole now its event horizon may still well be very different from what one of a Kerr hole is supposed to be, with very different area. There is no formula for the actual area of this event horizon in terms of the mass and the angular momentum.
To see where the problem really lies it is convenient to consider a scattering of two black holes instead of their merger. This process has an inverse which is also perfectly physical even if not likely to ever happen in reality. (Because general relativity dynamics is,
of course, time-symmetric.) Then exactly the same argument as in the paper when applied to both processes gives two inequalities which contradict each other.
Admittedly, from reading more recent physical literature I have the impression that the problem is more or less known. However, it is never mentioned explicitly. Apparently, physicists believe that the inequality is true anyway and do not care much about gaps in its proof. A mathematician like myself would rather like to see an actual proof though. Is such a proof already known or, at the very least, was the problem ever considered seriously? This is my question.
as far as I understand, the only generally valid principle is the increase of entropy upon a merger, which implies the surface area inequality $A(m)>A(m_1)+A(m_2)$; all other inequalities depend on additional assumptions for how the area $A$ of the event horizon depends on the mass and other parameters (angular momentum, charge). Some of this is discussed in arXiv:0909.4827
A mathematical proof of Hawking's area theorem has been given by Chruściel, Delay, Galloway, and Howard, in Regularity of Horizons and The Area Theorem (2001). The proof identifies the conditions under which the area of sections of future event horizons in space–times satisfying the null energy condition is non–decreasing towards the future. The monotonicity is shown to hold without making requirements on the differentiability of event horizons.
The specific relation between the area of the event horizon and the angular momentum in the OP is model dependent, it does not have general validity.
Thank you. This is an interesting work but it is related to a ``good'' part of the Hawking's parer (the one I have no issues with) about the area theorem. It does not address the question I am asking.
| common-pile/stackexchange_filtered |
Ambush meeting for silly plan
This morning I was invited to a 9.30am meeting by my boss (I normally start work at 9am although I am perfectly permitted to start as late as 10am if I so decide on the day and I have no earlier meeting to attend as far as I know).
This meeting was to decide whether to move a system from a computer programme, for which I am author and caretaker, to Excel.
My boss is barely computer literate and this IS a horrible idea. (If relevant, think NASA moving flight path calculations to Excel. It is technically possible, but you would eat your own shoe before you actually did it).
I think scheduling the meeting for 9.30am was a ploy to put me on the backfoot (My boss starts at 7am
most days). I would have perhaps 15 minutes to prepare after setting up for the morning and searching through emails to find this meeting. I, being at least adequate at my job and understanding my code, its programming language and MS Excel, can easily defend against the notion that moving the system is in any way good.
In this meeting, my boss was aggressive, belittling and willingly dismissive of anything I had to say, having previously made up his mind that his plan was entirely sound and without fault.
Setting a meeting like this is pretty much without precedent. Unless time differences are present, a meeting before 10am is almost unheard of and a meeting on such short notice for something so minor has never occured. He is well aware I am busy with other things for the coming weeks so the timing is bizarre at best and nefarious at worst.
What recourse do I have for this behaviour? I think the timing of the meeting was slimy and deliberate. I think his actions in this meeting were aggressive and unprofessional. I would like him to know that I won't be manipulated and that I feel his actions are non-managerial and that he should be doing better.
Why the downvote?
@stuartstevenson I didn't downvote, but it's probably because this seems very specific to a single event. You might try to edit this down to be more generally applicable to anyone in this type of situation. People are also voting to close because questions require a goal they can address.
What exactly does "my boss" mean? Your manager? The CEO? The company owner?
By recourse I just mean any action I can take to try to stop it from continuing.
@stuartstevenson, where I work, such things aren't exceptional. I would be more worried about your boss being "aggressive, belittling and willingly dismissive"
For better or worse, this is the most normal thing in the world in software. Smile and take their pay while you find your next contract.
Send your boss some of the uk stories about how using excel lost thousands of covid tests data
@Neuromancer I am pretty tempted. There's a video from Matt Parker that's really good. Honestly, it would go over his head unfortunately.
What recourse do I have for this behaviour?
Not much. You could escalate this to any other stakeholders that there are for this computer programme, and explain why this is a bad idea, but that would involve bypassing your boss, who would undoubtedly wratchet up his wrath against you as a result. This would have negative repercussions for your future at the company.
I think the timing of the meeting was slimy and deliberate. I think his actions in this meeting were aggressive and unprofessional.
I agree, but being a bad boss is unfortunately not against the law. And you, as a direct report, have little power in this relationship. Even if some or all bad actions of a boss are literally illegal, recourse in those cases is not as straighforward as one would think.
I would like him to know that I won't be manipulated and that I feel his actions are non-managerial and that he should be doing better.
Your boss is not a reasonable person, and it would seem that any appeal to reason here would fail.
I believe your best response is to be professional and leave emotion out of it. Don't sink to his level. You might consider drafting an email that restates his position (to make sure you have that correct) and explains clearly and objectively your position as to why his is not the best course of action.
I would also mention that you are committed to support whatever decision he makes. Your boss may be thinking you don't want to make the switch simply because you made the programme and are therefore biased.
It's possible that in working with your boss, you may help him discover the downsides to his choice, and perhaps even change his mind, making sure, of course, that he thinks everything was his own idea all along.
@stuartstevenson thanks -- usually people hold off marking an answer accepted, to see if others weigh in with a better answer. But you can always change your mind. :)
"Being a bad boss is unfortunately not against the law" - this line should be in the obligatory README FAQ for workspace.SE. +100
“being a bad boss is unfortunately not against the law” In this case it probably isn’t, but sometimes it can be (e.g. sexual harassment, discrimination, constructive dismissal, etc).
@nick012000 Your examples would fall more into the "being a boss that does things that violate legal requirements" category than "bad boss" which just means that the boss does a bad job.
@nick012000 I started to say "short of unethical or illegal behavior," but I figured someone would challenge "merely unethical," and illegal would be (I hoped) an obvious exception. Hard to tell anymore.
@mcknz Yeah, common sense in understanding is no longer common. Or probably never was, since one needs a separate term for it to distinguish it from the case when it is lacking. For the other cases, we have common law.
It's completely normal that the situation arises where 1 single programmer creates a system and thus holds an Ungodly amount of power in a company. This is completely normal and happens - say - once a year or so during the career of almost every programmer. In every case, once they realize their f'up, the client/company gets really pissed. Solution - You just act all "pro" about it and "work with them to find a solution". You explicitly say things like "Let's work towards a better solution in case I fall under a bus, hah hah!" Clients love this and everyone will be happy.
Ultimately, there's nothing much you can do. You can't fire your manager. So your options are:-
Resign immediately (bad idea),
Find another job and then resign (much more sensible), or
Live with it and carry on doing your job.
I suspect your employer realised they have a problem. There is an important calculation being done in the company, and it's being done by a bit of software that one person wrote, and only one person knows how to maintain. If you leave, or get run over by a bus, the company is in trouble.
So they had already decided what the solution was before the meeting was even called. Microsoft Excel may be a rather tacky and error-prone way to do calculations, but at least anyone who is a regular Excel user can look at a spreadsheet and make updates to it.
I'm going to address the issue of how to handle the meeting timing, which doesn't seem to have been directly addressed by any other answer.
Obviously the time of the meeting is not of itself a problem. Meetings where you aren't given a chance to prepare can a problem, but are also very common. Lot's of people actually prefer that the first time they present their ideas they do it in person, rather than by email. I've done it myself. They only become a problem if you are both not given a chance to prepare and also required to make a decision on the spot.
The simple answer is don't allow yourself to be pressured into giving a decision on the spot. When the boss presents an idea, even if it is crazy and obviously wrong, resist the temptation to start saying "that's crazy" or "that's obviously wrong". Instead say you need time to think about it.
Use the time to prepare a detailed and reasoned response. Put together the very specific problems that the idea has. Then send them to the boss and anybody else involved. For example (and I'm just making these up):
Excel won't perform fast enough to handle the amount of data we deal with;
Excel won't give us the error checking and validation of input we need;
An Excel application can't be tested
We don't have anyone with the necessary skills to program something this complex in Excel
Excel is hard to keep under source code control
A malicious person could modify the copy of Excel they use to make calculations and thus fake data
In this specific case, it is perhaps already too late, but I would suggest some pointers for the next time your boss has "The Greatest Architectural Idea Ever" (aka a bad architectural idea).
1. Stay Positive
Your boss has clear organisation authority here. If it comes down to a straight argument between you and them, you will lose. So you have to avoid it coming to this.
They have an idea for improving your product / process? Great!
You're both on the same team, with the same goals, after all...
2. Emphasise the Importance of the Product / Process
"It's good that we're talking about how to improve the product, because: so many stakeholders are using it / it makes such a significant contribution to the company's bottom line / the auditors rely on it / it prevents the company getting sued / etc. etc." (delete as appropriate)
You want to make clear here why it's in the boss's interest that the product doesn't fail.
3. Agree where possible - but state concerns
You want to reassure your boss you don't think his idea is crazy (even if you do), and that you're open to the idea it might work (even if you aren't).
So list all of the ways you can see your boss's idea might make some sort of sense, before you get into the reasons why it could cause problems.
"Excel has low barriers to entry, and lots of people in the company know how to work with it and support it, but I have some concerns about stability and change control".
4. Trial, Don't Just Implement
With all of the above in mind, the importance of the product, the desire to see if it can be improved, the potential benefits and the potential concerns, push to give the new approach a trial, rather than jumping straight into a full migration.
You are keen to see if it could work, but at the same time you want to control the risk.
There are a few things to keep in mind here:
Set clear success criteria. Try to shape these around your concerns.
So, the stability of the process, ease of making changes,
scalability, etc, etc. (basically, make all of the reasons you think
this won't work the "success criteria")
Set a clear deadline when the project should be reviewed against the
success criteria
As this is a "trial", the existing process will carry on. So, you
legitimately have an argument to carry on working with the "old"
technology. Suggest trying to find additional resource to work on the
trial, which you will of course be happy to support when possible.
This limits the risk to the company, and your product.
It also means you aren't personally tasked with making the bad idea work.
5. Wait and Observe
You know it will be a disaster.
Wait and watch, review when appropriate, and hopefully, before too long the whole mistake will be quietly forgotten.
What recourse do I have for this behaviour?
Your boss is asking you to do something you know is a bad idea. It might hinder the success of the project and be harmful to the company. I can think of a few options:
Resign immediately
If your goal is to send a message, this would probably be the most effective way to do so. Your boss would be forced to reflect on his actions and, if you're a high performing employee, he might even face some repercussions. The down side is, you would be forced to job hunt while unemployed which can be considerably more difficult than finding a new job when you already have one, especially if you can't count on your previous employer to provide a reference.
Refuse without resigning
The outcome of this would likely depend on how valuable you're perceived to be. Most bosses wouldn't suffer a subordinate who doesn't follow instructions so unless you're perceived as particularly indispensable, there's a high likelihood you'll be fired either immediately or somewhere down the line.
Complete the request and then resign
This allows you time to search for a new job while continuing to receive a paycheck. Before beginning the work, send a followup email to your boss and any stakeholders involved in the project that summarizes what took place in the meeting, his request, and your objections. This way, he won't be able to blame you if the project fails as a result of his request. When you resign, whether it be weeks or months from now, you can make it clear that this was the reason.
Suck it up and do it
Pretty much the same as the previous option only without the resignation part. When the project fails, everyone will know that it wasn't your fault and you can hope that your boss will learn to trust your judgement going forward. This is probably what I would do.
You mentioned yourself that the request was minor so probably best not to make a big deal out of it. As far as the early morning meeting goes, I don't really see the issue. Are you saying if you'd had more time to prepare, you would've been able to put together an argument so persuasive that he would've had no choice but to listen to you? It doesn't seem likely that he thought that far ahead and if he had, it would also mean he knew ahead of time that his idea was bad and the only way to get people to go along with it is to catch them off guard.
Regardless, aside from resigning there's really nothing you can do to punish him or ensure that this type of behavior won't happen again. It's always frustrating to have a boss who's dismissive of your inputs. (I know the feeling all too well). If it remains a single incident, you should probably just let it go. If he makes a habit of it though, start looking for a new job.
| common-pile/stackexchange_filtered |
Face recognition in Android without opencv
I wanted to develop a face recognition app in android. While searching, all i come up with is, the Opencv method, which i think is using C or C++. Can someone post the code or method for android? I am a newbie, so trying new stuff. Thanks!
OpenCV indeed uses C and C++ (and also Python), however you can try and use a java wrapper for the opencv library. Here is a nice wrapper.
If you have a newer phone/tablet, you can use the face recognition API in Android 14+. Check out Camera.Face and Camera.FaceDetectionListener
Also make sure you call: getMaxNumDetectedFaces to make sure you device supports the API.
| common-pile/stackexchange_filtered |
How to query Metadata from a WebDAV server
I am trying to create an iPhone App that will talk to a WebDAV Server. I have no idea on this.
Specifically in reference to:
How to upload a file to the WebDAV Server
How to download a file from the WebDAV server
How to retrieve / Add MetaData on the WebDAV server
How to enumerate directories & files on a WebDAV server
The metadata part I too need some help finding out. I mean exif metadata, not basic file attributes.
The protocol is defined in RFC 2616 (HTTP/1.1) and RFC 4918 (WebDAV):
PUT
GET
PROPFIND/PROPPATCH
PROPFIND (Depth:1)
Some Code, specially for the iPhone would be really helpful. Things like what should the header look like to retrieve properties. Do you use a NSURLRequest or do you use a HTTPStream or an XML Stream and so on.
Jayant: it would be good to give it a shot first. People aren't going to write the code for you.
For all basic CRUD operations, use an existing library such as :
https://github.com/amosavian/FileProvider
https://github.com/Isvvc/WebDAV-Swift
Regarding EXIF metadata, I'm not aware of any mechanism able to access these through WebDAV protocol. For the time being, I recommend you to download the file and extract its metadata. For sure, this method does not work for searching and filtering several files on the server. It is only working in case you want to show these metadata for one particular file.
| common-pile/stackexchange_filtered |
Topological Embedding Which is Neither Open nor Closed
I'm having trouble coming up with an example of an embedding which is neither open nor closed.
My attempts have included trying to find such a map from $\mathbb{R}$ (given the usual Euclidean topology, of course) to some subset of $\mathbb{R}$, which I now believe impossible, and trying to find one from some topology on $\{1, 2, 3\}$ to some other topology on $\{1, 2, 3, 4\}$. Both of these attempts seem to have failed me. So what do I do?
Any inclusion of a subset is an embedding, so you just have to find a subset which is neither open nor closed.
@StefanHamcke oh, of course. Thanks!
Stefan has given a machine for generating counterexamples in the comments. But since this question seems to have gone unanswered for so long, I figured I'd point out to provide a standard, not-so-obvious, but fairly useful instance of Stefan's general result.
A somewhat stronger condition than what you've asked for is to construct an immersed submanifold which is neither open nor closed. The immersion map is not an embedding in general, but the inclusion map on its image will be.
The example is given by $f:\Bbb R\to \Bbb R^2/\Bbb Z^2$ (*) defined as
$$f(x)=(x,\alpha x) \mod 1$$
for some irrational $\alpha$. It's fairly straightforward to see that this map is continuous, but the topology induced by $f$ on its image is different than the topology induced from the ambient $\Bbb R^2$.
[To be clear, $f$ is the immersion of manifolds— not a topological embedding. The topological embedding is the inclusion map im$(f)\to\Bbb R^2$.]
(*) If this is not familiar, it is just a torus: take the unit square $[0,1]^2$ and identify the top with the bottom, and the right with the left.
It seems like you just created a (particularly interesting but also rather complicated) subset of the torus that is neither open nor closed, then used the inclusion mapping as Stefan suggested in the comments.
An upshot of the complicated example is that this is a weakly embedded submanifold of the torus that is not embedded.
@mlg4080: This is precisely what I've done; I'm sorry if the second paragraph did not make this clear. I've updated the first paragraph to avoid any confusion.
| common-pile/stackexchange_filtered |
Django model filter avoid join when filtering by relation id
Django ORM query
projects = Project.objects.filter(category__id=1111)
This generates following sql query, [join used]
""""
select *
FROM "project"
INNER JOIN "category" ON ( "project"."category_id" = "category"."id" )
WHERE "project"."category_id" = 1111
""""
Is it possible to avoid join and get result like this?
""""
select *
FROM "project"
WHERE "project"."category_id" = 1111
""""
The underlying db column is called category_id (with a single underscore); you can filter on that directly:
projects = Project.objects.filter(category_id=1111)
| common-pile/stackexchange_filtered |
how to detect circles of symbolic links in haskell
i understand that i can find circles in symbolic links with the
find . -follow -printf ""
command (and other similar methods on the command line as previously previously suggested. but i cannot find a command in haskell to achieve the same.
there are several operations in System.Directory (eg createDirectory, renameDirectory) to return the ELOOP error from the OS (for linux), but none to simply check a filepath for a circle of symbolic links. but none to simply to check a filepath.
So you mean cycles in file systems?
You can use the unix package's readSymbolicLink to implement this check.
This is currently beyond what I am used to do in Haskell - I have not yet touched FFI yet. May come.
@user855443 The unix package author already did all the necessary FFI work -- you don't need to touch the FFI yourself to use this.
thank you - on first reading, I did not realize it was already on hackage
| common-pile/stackexchange_filtered |
Oracle LogMiner Results Inconsistent
I'm working on a LogMiner-based solution for capturing changes and I've uncovered what appears to either an unusual set of expectations when attempting to mine redo events that pertain to CLOB or BLOB operations.
In my use case, I've inserted record into a table that contains 3 CLOB fields where one of the CLOB fields value is small while the other two CLOB fields must be set using LOB_WRITE operations.
When I set a starting LogMiner SCN range that starts before and ends after the transaction commit, I get the full expected rows in V$LOGMNR_CONTENTS, which are:
0a00070084220000 37717288 START
0a00070084220000 37717288 INSERT
0a00070084220000 37717312 SEL_LOB_LOCATOR
0a00070084220000 37717312 LOB_WRITE (several of these as expected)
0a00070084220000 37717331 SEL_LOB_LOCATOR
0a00070084220000 37717331 LOB_WRITE (several of these as expected)
0a00070084220000 37717332 INSERT (sets the smaller clob data values)
0a00070084220000 37717334 COMMIT
The unusual bit occurs when starting the mining session with certain start/end SCN ranges.
For example, when I mine from 37717239 to 37717289, I expected LogMiner to provide both the START and the INSERT in the table; however only the START operation was present.
Additionally, when I mine from 37717290 to 37717340, I expected LogMiner to provide all the SEL_LOB_LOCATOR, LOB_WRITE, and subsequent INSERT and the COMMIT; however only the subsequent INSERT and COMMIT were present.
The only assertion I can make from this is that LogMiner seems to have trouble when you split a transction where certain redo events represent various synthetic operations as they relate to LOB operations and therefore the only way I've been able to actually always reconstruct the series of events has been to mine from 37717288 forward to force LogMiner to have the full scope of the transaction available when it materializes the rows in the contents view.
Why does LogMiner behave like this? Why does it not correctly materialize when splitting the transaction with the SCN ranges I presented above?
For Logminer any single command is atomic by definition.
In this case it starts at 37717288 and ends at 37717332.
It cannot be split. If you will ask any range that splits it - Logminer will not fetch it on purpose (so you won't have partial results of a single command).
This is also right for large non-LOB commands, like DDL that generate many internal commands (e.g. alter table modify column default value)
Besides that, pay attention that fetching the values of LOB from Logminer is not reliable. just play around with the values and you will see that it is highly inconsistent. (I have somewhere tests to prove it, so if you are interested I can provide them).
Here is the test: define a table with 2 lobs, create 2 rows - first with single lob and second with two lobs.
drop table sample1.clobs2;
create table sample1.clobs2 (id number not null, clob1 clob not null, clob2 clob);
--start
select current_scn from v$database;
insert into sample1.clobs2 (id, clob1) values (3, 'abc');
insert into sample1.clobs2 (id, clob1, clob2) values (4, 'abc', '2abc');
commit;
update sample1.clobs2 set clob1='def' where id=3;
update sample1.clobs2 set clob1='def', clob2='2def' where id=4;
commit;
update sample1.clobs2 set clob1=rpad('ghj',30000,'Z') where id=3;
update sample1.clobs2 set clob1=rpad('ghj',30000,'Z'), clob2=rpad('ghj',30000,'Z') where id=4;
commit;
--end
select current_scn from v$database;
Start the logminer:
exec DBMS_LOGMNR.end_LOGMNR;
exec DBMS_LOGMNR.ADD_LOGFILE('put here any logfile(select MEMBER from v$logfile), logminer will do the rest');
begin DBMS_LOGMNR.START_LOGMNR(
STARTSCN => put here the scn from the above test,
ENDSCN => put here the scn from the above test,
OPTIONS => -- I leave all the possible parameters here just for you to play
--DBMS_LOGMNR.DICT_FROM_REDO_LOGS +
--DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG +
DBMS_LOGMNR.CONTINUOUS_MINE +
--DBMS_LOGMNR.COMMITTED_DATA_ONLY+
--DBMS_LOGMNR.DDL_DICT_TRACKING+
DBMS_LOGMNR.NO_ROWID_IN_STMT+
DBMS_LOGMNR.NO_SQL_DELIMITER
);
end;
/
Check the results:
select scn, (XIDUSN || '.' || XIDSLT || '.' || XIDSQN) AS transaction_id, operation, seg_name, ROW_ID, rollback, csf,SQL_REDO, c.*
from v$logmnr_contents c
where 1=1
(seg_name='OBJ# put here the object id of the table sample1.clobs2' or operation='COMMIT');
You will see:
large lobs behave differently from small ones
in case when only one lob is updated - it is impossible to understand which one was it (the first or the second)
In addition, this behaviour changes between different Oracle versions.
Hi @Michael thank for this informative answer. I would most definitely like to see those tests if possible as it might be worth expressing that this exploration is simply moot in the end for us. We didn't notice any concerns with splitting transactions when dealing with basic DML statements using basic column types until we explored LOB. Re splitting, I had hoped that if we provided the start function with an SCN before & after the transaction that LogMiner would fetch those needed if the query's SCN range was too small, but it doesn't seem to do that either. Is there any workaround?
I'll take a look at your tests but we do have several tests in our suite where we do updates against multiple LOB fields at once and we're able to resolve which is which by parsing the SQL fragments that are part of the SEL_LOB_LOCATOR operation btw.
@Naros - Regarding your questions about SCN ranges: when COMMITTED_DATA_ONLY is enabled - then the "commit" should be in the range.
Right but at least for now we're not using that option, we found that option was equally as much of a pain since you also would need to the start scn in the range to get a full picture of the transaction when it does commit.
| common-pile/stackexchange_filtered |
ESC Control with PS3 Controller using Python
I have connected my PS3 controller to the raspberry pi using a bluetooth dongle. I am not sure about how to structure the code to control the ESC with the left joystick (axis 1). Could anyone advise me on tutorials or information which can aid the coding for this.
I want to structure the code in a way that 2 motors start up simultaneously with a single joystick input.
TJ
You need to focus on one step at a time and ask specific questions. If you have problems with python, ask on Stack Overflow. This isn't a discussion forum, so very vague/broad or open-ended questions aren't appropriate. We expect you put in a minimum of effort yourself. E.g., you should be able to find tutorials as easily as anyone else, and you know better than anyone what's appropriate for you. If you then have a specific question about the material, that's fine.
You can use triggerhappy to map buttons on a controller to commands, however not axis...
There are plenty of tutorials such as https://docs.python.org/2/tutorial/ which will help.
Just search for one you are happy with.
| common-pile/stackexchange_filtered |
How to automatically create virtual methods from inherited class in Qt Creator?
I am using QT4.8.4 + Qt Creator 2.8.1. Now I need to create several classes Child_X that inherit from another class Parent. In Parent I have several virtual methods.
Now I have to implement them in all of my Child_X classes. To save editing time, I'd like Qt do that for me automatically. When I remember right there is the possibility to have Qt create all the virtual methods. Does anybody know how?
Thank you
Sorry, I did not formulate correctly: I did not mean that Qt will automatically write the body of the methods. ( To invent that would probably make you very rich :-) )
I was talking about Qt writing all the headers of the virtual methods in the newly created (inherited) class. This saves a lot of writing/copying classnames etc.. The body would be empty in all the virtual methods.
Thank you
itelly
you need different implementation in each child class for your virtual methods ?
Why don't you just implement the method in your Parent class, if it's simple enough that Qt could auto-implement it?
Are those abstract methods that you want to implement? Each implementation of each of these methods in the derived classes is different than the others?
I hope you already found it, but maybe for others:
Right click on the class name in the editor.
In the menu, click on 'Refactor' and then on 'Insert virtual functions of base classes'.
You can choose to directly make the functions in the implementation file (as well as in the header file).
careful if you use that, it still doesnt insert template members properly, for instance: YourClass : public ISomething {...} -- refactoring and inserting members of ISomething where members return type T -- they likely will not be replaced with the type you specified with T but instead just get inserted plainly.
| common-pile/stackexchange_filtered |
Create an Image of a disk having software raid partitions
I want to create a bootable backup image/clone of my centos7 server "A" having software raid partitions and use this backup to create new servers with same configurations.
my partitions are
sda
--> sda1
----> md120 /
--> sda2
----> md121 swap
--> sda3
----> md122 /boot
--> sda4
----> md123 /var/images
sdb
--> sdb1
----> md120 /
--> sdb2
----> md121 swap
--> sdb3
----> md122 /boot
--> sdb4
----> md123 /var/images
sdc
I have used dd command to take backup of sda parttion (containing boot and swap, root and /var/images )
dd if=/dev/sda of=/dev/sdc bs=512 conv=noerror,sync
but when i restore the image on another server "B" (bare metal with same configuration) sda partition.
I was hoping that i will automatically boot up the server and raid sync will start on the other sdb drive.
But unfortunately it is not working.
Could anyone please suggest me the way to take backup of software raid partitions. And do i need to take backup of both drive ?
Thanks
I'm not aware of your constraints, but I would strongly suggest that you study the kickstart install method, followed by an ansible playbook to configure your system. You will save time, believe me.
Your approach is wrong, first of all an idea to do backup of swap is bad.
Anyway, IIUC you want to have a kind of template for your servers. I would suggest to use kickstart with install option with liveimg parameter - this way you could create an image with all your files which would be "populated" into your new installed server during kickstart-based unattended installation.
See: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/installation_guide/sect-kickstart-syntax#idm140037269828320
If you do not want to have 100% equal machines, just use kickstart with nfs or url parameter pointing to either public Centos repo or your mirror.
You can create all storage kung-fu in kickstart, see documentation.
I agree. IMO is better to create a new empty raid and then copy when the system image you need.
To create similar servers with an unattended installation, you should look into kickstart like the other answers suggest.
However, if you want to go the dd way, the idea is to create/restore an image of each RAID device rather than the underlying disks or partitions. You would also have to create an image of the boot/partition area of each disk. To restore the backup, you boot the target system with a "live" Linux system (e.g. http://www.system-rescue-cd.org/), then restore the boot/partition areas, create and assemble the RAID devices and finally restore the backup images to the RAID devices.
Your original approach of creating a full clone of the sda drive could also work (although it's not very efficient). But on the new server you have to manually create the partitions on the 2nd drive and then add them to the RAID arrays to start the re-sync.
| common-pile/stackexchange_filtered |
Do dogs "understand" breeds or size among other dogs?
In posts where people look for a dog walker I often read things like "my dog is afraid of big dogs" or "my dog is afraid of (e.g.) German Shepherds". Does science support these claims? I.e., that dogs understand the size of other dogs and can distinguish between (human created) breeds?
My anecdotal experience regarding size, from having small dogs like Toy Poodle and Pomeranian to medium/large dogs like Golden Retriever, and a variety of dogs inbetween these sizes, is that e.g., the GR was afraid of/respected the Pomeranian despite the GR could kill the Pomeranian with one bite (a typical example would be if I gave them a marrowbone each, the Pomeranian would steel the GR's bone and the GR would just sit watching the Pomeranian having both bones, clearly unhappy with the situation but not doing anything about it).
My personal belief is that dogs, instinctively, can distinguish between sex, age (adult/puppy) and (some) health status when they meet other dogs, but NOT size and breed. If a dog reacts to size and breed it is because its owner reacts to certain sizes and breeds and the dog has learned from the owner, not because the dog itself understands the difference, but what does science say about this?
Edit: with size I refer to that humans usually don't pick a fist fight with someone twice their size, so to speak. If a human has a conflict with someone, they usually consider the other parties physical capabilities before starting a fight. Dogs, OTOH, frequently can be seen as being submissive to another dog that is much much smaller, which, from a human perspective, doesn't make any sense, from a pure physical perspective.
Dogs have no concept of breed. Seeing a Poodle or German Shepherd is for them like seeing a brunet or a bald person is for us. They just look different.
Size is not automatically understood as a measure of power or respect, either. Properly socialized dogs who learned natural dog body language as puppies usually negotiate their rank and respect towards each other within the first minute of meeting.
However, dogs who were not properly socialized and didn't have many opportunities to practice dog communication struggle with this process. Due to Covid lockdowns we are faced with an entire generation of poorly socialized dogs right now. And if they have a tendency to be aggressive or dominant, a bigger size helps them bullying other dogs, for example by towering over them or physically pushing them to the ground.
On the other hand, if a dog (of any size) had made bad experiences with a certain dog of a certain breed, they might connect the look (size and breed) of any dog they meet with that bad experience and be afraid of all German Shepherds.
And lastly, as you correctly mentioned in your question, dogs do react to their human's behavior. If an elderly lady with a small dog is afraid that any bigger dog may attack "her baby" and acts fearful whenever she sees a big dog at a distance, her own dog learns from her nonverbal clues that it should be afraid of big dogs.
...or the small dog tries to protect it's old lady.
We suspect our dog, Mickey, had an incident or two at dog daycare because he has a stereotype against a couple specific breeds. Regardless of how sweet they are his ruff will go up.
@ChristopherKlaus Have you verified that with a double blind test?
@d-b It happens regardless if me or my wife are walking him. That said, no double blind test. ;)
| common-pile/stackexchange_filtered |
How can I fetch the data from PHP backend making a HTTP get request from angular
I have PHP on server side, and angular at frontend. I need to make a HTTP get request from frontend by passing one parameter fetched from a form. Using that parameter there are couple of third party API calls happening in backend which will prepare the response data. This process is taking a while and in the mean time the http get request is getting Gateway timeout.
what is the correct way to execute this scenario? Can I make a separate post call first to start the backend process by passing the required parameter and then prepare the response and keep it ready. Then receive the response data using another GET request.
Is this possible then how or do I need to follow other approach?
I faced similar issue in one of my project, our backend system query execution time was around 50 -60s and by that time, it trigger time out issue.
So we tackled this issue by asking backend team to share a reference-id when we hit API first time and when we received this reference-id, from second time on wards we make call the API using this reference as GET API input.
In backend when API have no reference-id in Input they have a temp table where they will create an entry with a unique UUID(which is the reference-id), and a status to progress save it in temp table.
The backend will return the API response with reference id. After that they trigger function to get data from external sources, once they got data from external sources, they will save in the temp table against that reference id and make the status ready.
When ever api hit came with reference id they will just query this temp table and until status is in ready the API will response the same reference id telling the data is not ready.
By using this approach Backend system also aware that when reference-id in input they need to just check the status of previous execution and if no references-id they can call their external API.
this seems to have some logic, let me think over it. If we can also implement similar logic.
Will the temp table which we will create in first API call be available for the second API call? Will not it get dropped automatically when the first request is closed?
table need to be there always ,
insert data/a row with reference id and status pending on first api call,
when data ready from external source is ready update status to complete along with data from external source
on second API call don't need to do any CRUD operation just fetch from that temp table and return API response based on status
| common-pile/stackexchange_filtered |
Mutual fund rating predictions
I am working on a dataset with aim to predict the MF ratings. There are cols like, 10 yr, 7 yr, 5 yr etc returns. I also have commencement date of MFs, the question is there are MFs with commencements dates only 3 yrs back, so would it be prudent to impute the returns for them for 10 yrs and 7 yrs period?
In my opinion that would be wrong, but then one of the requirements for ML models is to have no missing values in the data, and adding a 0 would be wrong too.
Need suggestions.
To put it very bluntly: The requirements of ML models are irrelevant to the principles of financial analysis.
Imputing the returns is fundamentally extremely unsound.
The best you can do is trim the dataset down to the smallest timeframe (in your case, 3 years). Or you can consider only those funds for which you do have sufficient data.
Thanks mate, i do agree to that.
| common-pile/stackexchange_filtered |
Recommended build system for latex?
I'm trying to figure out the best build system for latex.
Currently, I use latex-makefile, editing in vim, and viewing changes in Okular or gv. The major problem is that it sometimes gets hides errors on me, and I have to run latex manually. The major advantages are that it does all the iteration I need, and offers both pdf and ps simply.
If you have experience with
latex-mk
vim-latex
kile
lyx
miktex
latex-makefile
the ultimate latex makefile
rubber
any others I havent come across
Would you recommend them, and why/why not?
I see a vote to close as 'Not programming related'. It seems to be fairly established that latex questions are appropriate here. A build system question is, if anything, more appropriate to programming than other latex questions.
I like latexmk, I run it with MacTeX. It runs latex enough times to get the cross refs. right, takes care of bibtex, and makeindex as well. Miktex is mostly for windows, so its probably not applicable to you, but there is a beta for it on linux. lyx is wysiwyg for tex, I never liked it b/c i'm comfortable working with the source. Kile is a pretty nice graphical front end for KDE, though I don't use most of the buttons... so it's a bit pointless. :)
LaTeX is Turing complete, and dependency controlling build systems are a programming concern. This stuff belongs here and no mistake.
You can find an entire community on the TeX StackExchange, where no TeX-related question is too small. See for instance this question
See also http://tex.stackexchange.com/questions/40738/how-to-properly-make-a-latex-project
After considering all these options for some time, I have settled with the following solution.
Set vim to write continuously as I type.
Run a script in the background to build continuously, refreshing the pdf as it goes. latexmk is nearly good enough, except that it builds in place, which gets reloaded at a bad time in okular (my viewer).
The script is available at https://github.com/pbiggar/texbuild.
Use rubber-info to get the errors and warnings from the log file. The script above saves the log file in t.log. In vim:
autocmd FileType tex set makeprg=rubber-info\ t.log
autocmd FileType tex set errorformat=%f:%l:\ %m
Could you post your code again. It's quite weirdly formated as some is in code blocks, and some are not. Meanwhile, some are in headlines etc.
@martiert: I posted it a few times, and I think I got it right at the end (works for me). Is it OK for you now?
@PaulBiggar I know this thread has been dead for a while now but I hope you see this. How do I use your script? I don't know Python or Vim very well and there doesn't seem to be any documentation on how to get it to work.
I ran into similar scenarios when "pdflatex" from my windows cmd prompt takes too long and I have to wait. I did try your code with Python, though I did not use Vim. Later, I realize the build system in Sublime (ctrl B) does what I want: I am using Sublime + Latexing plug in + sumatraPDF (for not locking the pdf). If a compile fails, the pdf won't go corrupted, which I think is what you are after. For me, hitting ctrl S + ctrl B once in a while isn't interrupting. And I like the fact that when the compile fails, I can see error msgs in a somewhat informative dialog box.
I've just tried out latexmk. If you do
latexmk -pvc file.tex
Then it will auto preview (DVI by default).
Handles dependencies
DVI, ps or pdf
Iterates fine.
Very configurable, see man latexmk
Downsides:
It doesnt condense errors, which isnt hugely useful (workaround: use rubber-info separately)
Bug in the man file: "Sometimes a viewer (gv) tries to read an updated .ps or .pdf file after its creation is started but before the file is complete. Work around: manually refresh (or reopen) display.". It would be better if it built it via a temporary .pdf file to avoid this.
Not hugely user friendly.
latexmk doesn’t support XeTeX and there’s apparently no way of changing this short of hacking the hard-coded value of the pdflatex executable. Very annoying.
I agree with Paul's answers re: Rubber and Latexmk.
I tried Rubber before, it does present build errors nicely, but it's 2-3 years old and doesn't seem that maintained.
Latexmk is my current builder of choice.
The latest release is from 3 weeks ago, it has quite powerful configuration possibilities (e.g. I have it automatically generate PDF figures from the OmniGraffle files), maybe XeTeX support in even on the author's todo list?
FWIW, Latexmk works just fine with XeTeX now.
if using vim, checkout latex-box
I haven't used it myself, but I've heard of Rubber as a good alternative.
From their website:
Rubber is a program whose purpose is
to handle all tasks related to the
compilation of LaTeX documents. This
includes compiling the document
itself, of course, enough times so
that all references are defined, and
running BibTeX to manage bibliographic
references. Automatic execution of
dvips to produce PostScript documents
is also included, as well as usage of
pdfLaTeX to produce PDF documents.
I tried this before, and I don't remember what problems I had that made me look elsewhere. I just tried it now and it seems to work very well. Thanks.
I moved my comments about rubber into their own answer: http://stackoverflow.com/questions/1240037/recommended-build-system-for-latex/1321905#1321905
Ok, so this question is a bit old, but it came up when I googled "latex build system" so I thought I'd add my two cents. I tried the Makefile based solutions, but found the output a bit verbose and unwieldy. I figured someone might have built a scons extension for latex, but was pleasantly surprised to find that scons already natively supports latex! All you need to do is create a SConsctruct file like this:
env = Environment()
env.PDF(target="report.pdf", source="report.tex")
To build just run scons report.pdf. Scons will automatically build .tex files included by report.tex, handle bibliographies and perform repeated builds in order to resolve all references - simple!
You can create DVI and PS files in the same way. For more info on these builders check out http://www.scons.org/doc/2.0.1/HTML/scons-user/a8524.html .
For more info on scons (a make replacement), see http://www.scons.org/
This is great, especially because you can pass in PDFLATEXFLAGS, which is not possible with rubber. Did you find a way to make the build output less verbose though?
Scone also has built in dependency scanning which is nice. You don’t have to explicitly tell it about included files or index’s or the like.
I posted a detailed answer using Scons on tex.stackexchange.
Basically, you put this in a file called SConstruct:
# make sure scons finds tex executables:
import os
env = Environment(ENV=os.environ)
# target and source:
pdf_output = env.PDF(target='main.pdf', source='main.tex')
# make sure that the pdf is reloaded properly (e.g., in Skim)
env.Precious(pdf_output)
You can build the pdf simply by running
scons
Amazingly, scons will detect the changes in the files \included in the main.tex file and also the bibliography file!
I use Eclipse with the TexEcplise add-on for editing my TeX-files. It has syntax highlight for LaTeX. When you ask a preview of a non-altered and already compiled tex file, it open the file in the viewer. When the tex file was altered, then it compiles the tex file prior to viewing it. It does the necessary iterations, but only if needed.
Another advantage is that all errors and warnings are summarised in a box and they are highlighted in the tex file! This is a screenshot from the TexEclipse homepage.
I'm trying rubber for a while. I'll condense the results here:
Rubber will automatically convert .eps files into .pdfs for pfdlatex. However, it seems to only do this for includegraphics macros. If you have your own macro, it wont.
rubber-info is great, which is magic. It is certainly better than anything else I've seen at getting error message and lines. And you don't actually need to use rubber to build to use it.
It doesn't seem to know when to stop iterating, often stopping early.
It overwrites your PDF as it builds, which is irritating (it lacks a nice feature from latex-makefile where it builds it in a temp file).
I wanted to use the script you posted in your final answer.
Unfortunately, it didn’t work with my setting (MacVim with vim-latexsuite, Skim as the viewer and XeTeX). I also use forward search (i.e. I use the feature that pressing \ls in Vim will jump to the corresponding point in the PDF document in the open viewer).
Furthermore, my document isn’t called thesis.tex (big surprise; it’s not a thesis). I’ve therefore done some more configuration work that I’d like to share. Attention, my bash skills are horrible.
#!/bin/bash
set -x
ulimit -t 10 # sometimes pdflatex gets stuck
if [ "$1" = "" ]; then
echo "No target name specified"
exit 1
fi
TARGET=$1
SOURCE=$1.tex
TMPSOURCE=_$TARGET.tex
TMPTARGET=_$TARGET
while [ 1 ]; do
# Compile a different file ($TMPSOURCE.pdf) so that it doesn't reload mid-compile
cp $SOURCE $TMPSOURCE
# better than running pdflatex manually, as this wont rebuild if there's nothing there.
latexmk -pdf -silent $TMPTARGET > /dev/null
# For rubber-info
cp $TMPTARGET.log $TARGET.log
if [ -e $TMPTARGET.pdf ]; then # Check the compile succeeded first
# No output file yet.
[ ! -e $TARGET.pdf ]
HASNOPDF=$?
# ignore if it's unchanged.
# OS X diff doesn't consider binary files. Single-line output, return value 2
diff $TARGET.pdf $TMPTARGET.pdf
OUTPUTDIFFERS=$?
if [ $HASNOPDF -eq 0 -o $OUTPUTDIFFERS -ne 0 ]; then
# Do NOT RM since Skim cannot deal with this.
cp $TMPTARGET.pdf $TARGET.pdf
fi
fi
sleep 1 # give it time to be killed by a CTRL-C
done
This compiles a temporary file and copies it back to whatever name was given (instead of the other way round as your script does); usage of the script:
./scriptname project
Where project is the name of the TeX file, without file extension.
I’ve also changed the rubber-info line:
autocmd FileType tex exe "set makeprg=rubber-info\\ _" . expand("%:t:r") . ".log"
And I needed to patch my latexmk to use XeTeX since the name of the executable was hard-coded.
Unfortunately, this still destroys the output PDF file when I’ve saved my document before completing a statement, since latexmk seems to always produce a PDF file, even on error – and its return code is always 0, which sucks.
(To clarify this, say that I’ve just typed emph{ into my document and save it. The background script will promptly compile the document, and fail. But it will still produce a (largely empty) output file).
Additionally, forward search no longer works properly; it basically jumps to a wrong point in the document. I suspect that this has something to do with my copying the document before compilation.
So, this is still a completely unsatisfactory solution, even though I didn’t even enable continuous saving on typing in MacVim yet.
Actually, I rewrote the script over the last while. I'll post it later.
(This is a work in progress)
I'm trying vim-latexsuite at the moment. It basically turns vim into an IDE for latex.
Learning curve:
Very unintuitive, but after the tutorial, it seems OK.
It redefines some keys I like, and I can't seem to fix them.
Autocomplete:
Makes using some built-in macros simpler
Adding <<+>> to for user macros is very annoying.
Replacing " with `` and the like is nice until you want " for some reason, then its an exercise in frustration.
Its autocomplete can be annoying too. I have to reprogram myself for working in latex.
Build system:
Awful
quickfix doesn't work - it often puts me in the wrong file
When latex reports errors with the result split over 2 lines, it doesn't detect it.
Much the same experience here, but I now use it all the time and it works quite nicely for editing. I like the macros, after some getting used to.
Trying to get this thing working with xetex and biblatex. The best I got is three consecutive runs with dependencies. But it was forever! let g:Tex_FormatDependency_pdf = 'bcf,bib,pdf'\n let g:Tex_CompileRule_bcf = 'xelatex --interaction=nonstopmode $*'\n let g:Tex_CompileRule_bib = 'biber -q $*' let g:Tex_CompileRule_pdf = 'xelatex --interaction=nonstopmode $*
AUCTEX & preview-latex with Emacs another option.
You can also have emacs open up the resultant dvi, or pdf file, and if you turn auto-revert-mode on for that buffer, the changes will be rendered everytime you recompile the document.
"Better" is a very relative term... what else do you want to do? It seems like this makefile handles quite a bit, and it makes me wish I was running a *nix at work instead of windows... if there are more things you need to handle with the makefile, why not add them in?
To make it "better" you would need to provide more details on what exactly you're doing.
For instance, you could have it parse the .log file with grep, search for errors or warnings, dump them into another file, then open the new file so you can read through the errors.
It all depends on what you want to do...
OK, I've clarified "better" in the question.
What is your end goal? "More productive" is still quite relative... If your major headache is errors and having to run latex manually, I might suggest moving away from vim and onto something like Kile, which will spit out errors in the bottom pane... do you have the latex vim plugin? You could tell latex to run in non-stop mode (i.e. not stop on errors) by adding the -r flag to your makefile.
Again, it all depends on what you want to do, since latex is pretty flexable. Thus, if you do not have anything really specific in mind, you probably are not going to get great answers :D
Mica S.: I'm trying to get suggestions as to potentially better ways to do it. I'll clarify better.
I've been using the latex-makefile for a while. Its pretty good if you're trying to use an edit-compile-preview cycle:
Takes almost zero configuration.
Builds .ps or .pdf.
Handles all the necessary iteration. I literally have to write nothing else.
Quite robust, but occasionally the errors and warnings get mangled.
It doesn't kill the old pdf until the new one is built.
It builds other files, like generating eps from gnuplot. I havent found this hugely useful though.
The author is very quick to respond to feature requests.
I can replicate the advantages of latexmk fairly easily with:
while [ 1 ]; do /usr/bin/make; done
Some downsides:
It only allows pdf generation via dvi -> ps -> pdf, instead of directly via pdftex.
Its error output isnt the same as the standard latex one, so vim isnt moving to the correct line.
It doesnt always recompile on changes in bibtex and other non-tex sources.
If I remove a file, it doesn't remove the dependency without a make clean.
I'm using MikTeX in combination with TeXnicCenter. It works fine for my purposes. I've never ever had the system hiding errors or warnings. Custom build scripts are easy to create and configure.
Nope, seems to be windows only
TexMaker is all you want/need.
ltx claims to be a wrapper to latex to speed up the compilation of latex documents. I couldn't make it work though (some problems with initex).
Link is 404 now.
Have a look at TeXMaker. :-)
features (from wiki):
In-line spell check.
A unicode editor to write LaTeX source files (syntax highlighting,
undo-redo, search-replace, spell
checker...)
LaTeX tags and mathematical symbols can be entered with a mouse
Document and section templates
LaTeX-related programs can be launched
BibTeX database management
An outline or "structure view"
Logfiles during LaTeX compilation and the ability to "step through"
source errors that are discovered by
the compiler
An integrated LaTeX to HTML conversion tool
features (from me):
useful wizards for inserting tables, citation, referencing
bidirectional support
useful keyboard shortcuts
Auto Complete words (specially is useful with referencing)
define your own instructions
Make sure to additionally check out TeXMakerX ( http://texmakerx.sourceforge.net/ ) - it's a fork of TeXMaker with some more useful features.
| common-pile/stackexchange_filtered |
Probability Density of Returns of Bonus Certificates
Could anyone please help me with the following?
I need to generate a histogram (resp. probability density) of returns of a bonus-certificate.
A bonus-certificate can be replicated by an underlying and a down-and-out-put option.
I tried to do that with Matlab but not by calculating the right PDE using conditional probability. Instead I've chosen a far easier way. I derive the wanted histogram (BC-histogram) from the histogram of stock returns. At first log-returns (that are normally distributed) are considered only. Then a transformation of log-returns to simple returns generates the BC-histogram of lognormally distributed returns.
To achieve that following steps had to be made:
divide the probability density of stock returns in a certian amount
of bins (so the histogram gets a certain bin width),
sum up all the bins that are between the bonus-level and the
barrier-level and remove them from the generated BC-histogram,
mirror the bins at the point of the barrier to take into account
that if the stock touches the barrier the investor gets the exact payment
as someone would get by simply buying the underlying stock
and finally subtract the sum of the mirrored bins in point 3. from
the sum of point 2. to get the bin height of the bonus bin.
In order to transform from log- to ordinary returns simply calculate
the exponential of log-returns and subtract one.
Finally in addition to 5. subtract the premium payed for the
down-and-out-put and divide by the Premium (in percent of the
underlying stock) plus one to account for the decrease in return
because of the option component of the bonus-certificate that had to
be payed.
I've generated a plot that shows BC-Returns for various barrier- and bonus-levels.
Could anyone please verify the validity of the plot and the steps I've mentioned above?
Link to the plot:
http://s7.directupload.net/images/121016/x37oi9ro.png
Perhaps someone could post a plot he has generated using his own solution, like PDE-solution for instance. I would like to compare the results of the plots especially for a given bonus-level of 1.22 (i. e. 222% of current underlying price) and a given barrier-level of -0.01 (i. e. 99% of current underlying price).
Any useful help will be greatly appreciated.
| common-pile/stackexchange_filtered |
Optimise javascript and css requests for wordpress plugins
I'm building several WordPress themes in which I like to use a number of plugins like Jetpack and Gravity Forms, unfortunately they add a number of extra javascript and css requests to the site. Which causes a fair amount of added loading time to the server on slower connections.
Obviously as these plugins are updated regularly it would be very impractical to compile them into single js and css files by hand and keep them up to date. Is there anyway of automatically compiling these requests into one without manually editing the files?
Maybe a plugin of a simple piece of code that preloads the files into a cache and sends them as one request?
Considering you are using Wordpress I would suggest leveraging the plugins that exist to help you to solve this issue and save you time.
You can use this wordpress plugin for minifying and combining your static assets. https://wordpress.org/plugins/bwp-minify/
Some further reading around this plugin: http://betterwp.net/wordpress-minify-javascript-css/
I would also recommend compressing your files when they are served using Gzip. The implementation would depend on your web server.
I'm not affiliated with the developers of this plugin but it works well for me. Hope that helps.
| common-pile/stackexchange_filtered |
Why couldn't Snape and McGonagall prevent what Fudge did at the end of Goblet of Fire?
In Goblet of Fire (The Parting of the Ways), Dumbledore says to Snape:
“Then go down into the grounds, find Cornelius Fudge, and bring him up to this office. He will undoubtedly want to question Crouch himself. Tell him I will be in the hospital wing in half an hours time.”
Later, in the hospital wing:
“You should never have brought it inside the castle!” yelled Professor McGonagall. “When Dumbledore finds out–” […]
Snape:
“He insisted on summoning a Dementor to accompany him into the castle. He brought it up to the office where Barty Crouch –”
And McGonagall:
“I told him that you would not agree, Dumbledore! I told him you would never allow Dementors to set foot inside the castle, but –” […] “The moment that – that thing entered the room,” she screamed, pointing at Fudge, trembling all over, “it swooped down on Crouch and – and –”
Snape and McGonagall both saw the Dementor before he came into the room, knew that Dumbledore would disapprove and knew what a Dementor could do. Both knew how to do a Patronus charm and it seems to me that at least McGonagall saw the Dementor executing the kiss. McGonagall had orders to protect Barty Crouch, she and Snape had time to talk to Fudge about the Dementor but nobody did something about it. For starters, they could have insisted on talking to Dumbledore before letting a Dementor in the school (especially since Dumbledore didn't even let Dementors in the castle when everybody thought Sirius Black was running amok in there in the third year).
So why didn't they do anything to stop it?
I think GoF was published a sufficient enough time ago that you don't have to put everything in spoiler tags
Because of the kind of power structure underlying the Wizarding World.
As Pharnabazus outlines in his amazing essay on the patron/client dynamic in Harry Potter, Dumbledore and Fudge have a complicated history of influence and struggle. While originally Fudge allied himself with Dumbledore, the Minister slowly tried to cultivate his own patronage. During the events of the Harry Potter novels Fudge found his tenuous power base threatened by the rise of Voldemort and so distanced himself from Dumbledore's camp. We see the progression much more clearly later on in the series, but the ending of GoF is a crucial turning point:
Before the end of GoF, Fudge still appears to respect Dumbledore. He enjoys the alliance of Dumbledore's power base, even if he's not part of it himself; they are a lopsided team. Fudge has great resources but little influence and a tenuous power base, while Dumbledore has enormous influence and a very wide and deep power base.
Silencing Crouch was a deliberate move to consolidate Fudge's power at the expense of Dumbledore's. If Dumbledore used Crouch to prove Voldemort's return, Fudge's promises of normalcy would crumble and his clients would flock to Dumbledore. On the other hand, if Dumbledore were made to look like a paranoid old man...
So while it was appalling to watch, Dumbledore's clients were politically unable to stop Fudge without Dumbledore's explicit authorization --regardless of their magical or physical ability to do so-- because Fudge was a valuable ally of Dumbledore. When Dumbledore removed his support from Fudge because of this action, it is a visible blow to the Minister (who as of CoS had been running to Dumbledore for advice regularly) and goes a long way to explain his apparently irrational behavior in the following years.
Thanks! I'm currently halfway through that essay and it makes sense to me; very interesting… Though I find it hard to believe that McGonagall would see someone suffer the kiss and not act because of political reasons, especially when Dumbledore has personally told her to guard Crouch. But maybe the second half of the essay explains that…
This essay is incredibly good. I still find it hard to believe (especially because of the reason stated above), but I'll accept it as an answer. Thanks!
Neither McGonagall or Snape had any reason to expect that the dementor was actually going to kiss Crouch. Their objections to the dementor had nothing to do with Crouch per se; they were simply objecting to the very idea of allowing a dementor into the castle, something which Dumbledore was adamantly opposed to.
However, as Dumbledore was not present, they had no choice but to accede to Fudge's demands, as he was the Minister of Magic. So they allowed him in with the dementor, but still never suspected that the dementor would actually kiss Crouch. In general dementors were well behaved enough that they wouldn't kiss someone without explicit orders. Throughout Prisoner of Azkaban there were dementors guarding every entrance to Hogwarts. People must have been passing by the dementors on a regular basis yet no one ever got kissed.
Once the dementor actually attacked Crouch, there would probably be little that McGonagall or Snape could have done. We don't know precisely how long it takes to administer the Dementor's Kiss, but the way McGonagall describes it makes it sound like it was pretty instantaneous. If they hadn't been expecting it they would have been unprepared. They likely did not even have their wands out, and for all we know they may have been behind Fudge so did not have a clear shot right away. By the time they would have been able to cast a patronus (i.e. realize what was happening, take out wand, move into position, think of happy memory, cast spell, have patronus chase down the dementor) Crouch would have already had lost his soul. For all we know they might have cast patronuses, but they were too late to stop the dementor.
While I still believe that @BESW's answer above is and will remain the best in-universe explanation, I found an out-of-universe explanation that is, somehow, more satisfying to me:
If Barty Crouch Jr. would have repeated his confession to the Ministry of Magic, J.K. Rowling wouldn’t have been able to write the “Ministry denies the return of Voldemort”-storyline in the next book. My personal guess is that Rowling liked the Veritaserum-induced confession scene too much to cut it, and then the Kiss was the most believable way to get rid of Crouch Jr. afterwards.
The answer is more simple than that. She is simply a weak person who lacks judgement and any degree of character and courage despite her outward appearance.
There are examples in every book. Here are just a few:
She allows Harry to be tortured in Book 5 and tells him to keep his head down.
She always defends Snape and doesn't protect Harry or what is right.
She doesn't support Harry in protecting the stone.
She consistently demonstrated the opposite of Gryffindor courage and nobility and fails to act on her own to defend others or pursue justice. She is the deputy headmaster and Harry's head of house (his parent/guardian while at school). She is a terrible at all of her various jobs.
Harry doesn't tell anyone about his hand. And she was also somewhat restricted; she even explains this to Harry.
She is just as strict as Snape except that she doesn't favour her house. The reality is Harry did break a lot of school rules and even Dumbledore says so.
She didn't believe the stone was at risk and what could she do anyway? Dumbledore was gone and the entire point of the set up was to prevent not only adults but also kids from breaking through the defences.
She is in fact a strong person with sound judgement and courage; you're just missing the evidence.
A good example of her courage: when Dumbledore's Army is uncovered she tells Fudge and the aurors that they'll have to fight her, too; Dumbledore insists that the school will need her while he's gone. And the Battle of Hogwarts? Telling Slughorn they will fight to the death if he hinders them? Fighting Voldemort himself? And those are only physical acts of bravery and there are many more examples. Besides, you ignored the issue of Severus Snape.
This is so unbelievably wrong in every respect. It’s hard to believe anyone could read the Harry Potter series and come out of it with this impression.
| common-pile/stackexchange_filtered |
N-Epsilon proof
I was working on the questions seen below. Namely question 7 and 8. I was able to figure them both out but noticed that in question 7 we do not include the absolute value sign after where it says "implies, $0 \lt $ ..." as per the definition.
Now I know that $\sqrt[n]{a} -1$ is always positive, but so too is $\sqrt[n]{n} -1.$ So why do we not omit the absolute value as well in question 8.
Additionally, how do I visualise and/or understand $ 0 \lt \sqrt[n]{a} - 1 \lt \epsilon$ since the neighbourhood is not the same distance from the limit on both sides.
$a^{1/n} -1$ is "always" (more precisely: if $a>1$) positive. "Why do we not omit the absolute value as well in question 8": you are right, we could. 2) $a^{1/n}\in(1,1+\epsilon)\subset(1-\epsilon,1+\epsilon)$.
@AnneBauval thank you. Why are we allowed to take (1, 1 + ε) if it’s not the entire range we are after? Doesn’t that go against the definition?
The definition wanted $a^{1/n}\in(1-\epsilon,1+\epsilon)$. We obtained $a^{1/n}\in(1,1+\epsilon)$, which is stronger, so we won.
That makes sense now. Thank you. I didn’t realise you replied.
Please do not use pictures for critical portions of your post. Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers.
The first one seems where we invert $n(\sqrt[n]a -1) <a$ so $\sqrt[n]a-1 <\frac an$ gave use a positive upper bound but "left us hanging" on the lower bound. But that's okay we had an immediate hack. We know $\sqrt[n]a - 1>0$ so that gives us $0$ as a lower bound. Now if we needed to be strictly formal we could have gone $-\epsilon < 0 < \sqrt[n]a - 1 < \frac an = \epsilon$ but there's no need to make trouble. The second one with an even power yields "naturally" to absolute values. So we weren't left hanging and we don't need to do the extra work of noting $\sqrt[n]n -1$ is always pos.
"Why are we allowed to take (1, 1 + ε) if it’s not the entire range we are after? Doesn’t that go against the definition?" We arent after the entire range. To get the exact range and nothing but the range would be difficult and maybe impossible and absolutely not nesc. But if we can get something that covers everything we need and then some and be a bit more than we need it is fine and great.
| common-pile/stackexchange_filtered |
Getting errors on Generate Signed APK in Android Studio 2
When I try to run project it works fine but when i try to generate signed apk i got this error.
I was try to clean project and rebuild it but none of them works for me.
My Problem is not related to duplicate libraries in Build:Gradle
> Error:warning: Ignoring InnerClasses attribute for an anonymous inner
> class
> Error:(edu.emory.mathcs.backport.java.util.concurrent.locks.FIFOCondVar$1)
> that doesn't come with an
> Error:associated EnclosingMethod attribute. This class was probably produced by a
> Error:compiler that did not target the modern .class file format. The recommended
> Error:solution is to recompile the class from source, using an up-to-date compiler
> Error:and without specifying any "-target" type options. The consequence of ignoring
> Error:this warning is that reflective operations on this class will incorrectly
> Error:indicate that it is *not* an inner class.
> Error:The number of method references in a .dex file cannot exceed 64K.
> Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
> :PersianCalendar:transformClassesWithDexForRelease FAILED
> Error:Execution failed for task ':PersianCalendar:transformClassesWithDexForRelease'.
<br/>
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
I'm using the latest version of android studio and gradle.
also try build.gradle:
lintOptions {
abortOnError false
}
have you set dex enable option ?
No give me sec to try it
Not working for multiDexEnabled true
Are you using proguard ?
then there may be some rules need to be done in proguard file
Possible duplicate of Java finished with non-zero exit value 2 - Android Gradle
I also try to use -keepattributes InnerClasses -dontoptimize in proguard but not effective
I didnt duplicate any libraries :(( Really dont no whats problem ...
| common-pile/stackexchange_filtered |
WebServer - moving MySQL to another server on LAN for gaining more processing power?
I have website with high traffic hosted on dedicated machine. This machine running out of resources.
Will moving MySQL database to another dedicated machine on LAN give more resources to website (considering that MySQL queries are fulfilled by entirely other computer) or will it actually slow down more because data has to travel over network?
This depends on a lot of facts.
First of all queries will incur a slight penalty as it now has to travel through the network.
If the 2 machines are linked with a low latency and high enough bandwidth this should probably not effect it too much, which means it might improve performance.
Secondly if most of the resources are being used by MySQL and the new machine is not better then the old one, you might get a slower result.
In general, if your performance is bad at this moment and you are moving the MySQL server to a other machine which has better specifications (speed,memory,disk) and is linked with a fast connection you should expect speed up.
| common-pile/stackexchange_filtered |
node.js email doesn't get sent with gmail smtp
I'm trying to send the email gmail smtp but I'm getting the error:
My email and password is correct I'm using the nodemailer for sending the mail;
var nodemailer = require('nodemailer');
// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
admin: 'myuseremail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'sender address', // sender address
to: to, // list of receivers
subject: 'Password Reset', // Subject line
html: 'Your one time password is : <b>' + temporaryPassword + ' </b>' // html body
};
transporter.sendMail(mailOptions, function (error, info) {
console.log(error,info);
}
in log i'm getting the error:
{
[Error: Invalid login]
code: 'EAUTH',
response: '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/answer/14257 k5sm20957041pdo.48 - gsmtp',
responseCode: 535
}
I try some link but that doesn't work:
https://laracasts.com/discuss/channels/general-discussion/help-email-doesnt-get-sent-with-gmail-smtp
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user<EMAIL_ADDRESS> pass: 'password'
}
});
Try the above, and do the following which worked for me.
Login to https://www.google.com/settings/security/lesssecureapps and TURN ON Access for less secure apps.
I hope it will work for you too.
Thank you.
In case you have 2F authentication enabled, then the 'less secure apps' feature is disabled. You need to generate an app password. To do that, follow these steps: https://support.google.com/accounts/answer/185833
I got the same error and the less secure apps tip was the solution.
btw you can also login via smtp://email<EMAIL_ADDRESS>
First of all, you have to enable the settings to allow less secure apps for the gmail account that you are using. Here is the link : https://myaccount.google.com/lesssecureapps
Secondly, Allow access for "Display Unlock captcha option" (Allow access to your Google account). Here is the link : https://accounts.google.com/DisplayUnlockCaptcha
https://myaccount.google.com/lesssecureapps
Click on this link, On your Less secure app access. so after that gmail will send email to your device , confirm that it is you. You are done happy coding
In case you're using OAuth2 and you're facing the issue above, configuring my transporter as shown below resolved my issue.
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: process.env.MAIL_USER,
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_CLIENT_REFRESH_TOKEN
}
});
the link in that post is broken, follow this https://thepandeysoni.org/2016/06/12/nodemailer-service-in-node.js-using-SMTP-and-xoauth2/
Google don't allow you to send direct e-mail to other's. First of all you have to create a app password .For that thing please follow below steps to get it done
Go to your manage account section.
Then click on the security link in left side.
In the signing in to the google click on app password and it will ask you to sign in again after sign in
It will ask "select app", for mail purpose "select mail" and after that select device from which you want to send mail.
After all these steps, it will generate password for that thing and insert that like this
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user<EMAIL_ADDRESS> pass: "password"
}
That's it.
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user<EMAIL_ADDRESS> pass: 'password'
}
});
Try this.
For me
secure:true was giving ssl errors.
I changed
secure:false as below and worked for me.
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, //<<here
auth: {
user<EMAIL_ADDRESS> pass:'your gmail pass'
}
});
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: true,
auth: {
user<EMAIL_ADDRESS> pass:'your gmail pass'
}
});
While it seems to be a solution, it'd be nicer to provide some explanation for why it solves the problem. There are inexperienced users visiting SO who might not immediately understand what's the game changer here.
it gives me an error like this :
Error:<PHONE_NUMBER>97472:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:827:
| common-pile/stackexchange_filtered |
Election vs Poll
Can election be used in place of poll? Like when you vote for your favourite actor for the best actor of the decade can it be called an election? Or does election strictly mean a formal appointment of a politician for a position for example? Would it sound too weird if I called it an election?
Here is the thing: I have an app where people can vote for some stuff similar to some twitter polls: "Which one of these movies is better?" type of polls. But I don't want to label these things as polls for some aesthetics reasons what if I labeled these polls as "Elections". I can see technically it is wrong but would a native english speaker be weirded out and be like "What do you mean elections?" or would they just roll with it because it doesn't feel unnatural? Or I am open to any other suggestions.
Already asked and closed on ELU
Since Astralbee was kind enough to answer your question, you might do them the favour of accepting it.
Although they may appear to be used interchangeably when people talk of 'election day' or 'polling day', the words 'poll' and 'election' do not mean the same thing.
An election is where someone gets elected to fill an office or position. In a democratic election, the person is usually elected by the result of a poll. But polls can be done for various other things.
You would not use 'election' to describe a poll of people's favourite actors as nobody is being elected. If you really have an objection to the word 'poll', why not call it a 'vote', or a 'survey'?
@Astralbee thank you for response, could you have a look at the edited question i provided some more details.
@khatara I've read your edit and I don't see any significant change. Basically, if nobody is being elected, it isn't an election. If it's a poll, call it a poll.
A poll is any count of preferences. See Merriam-webster sense 4a
the casting or recording of the votes of a body of persons
and sense 5a:
a questioning or canvassing of persons selected at random or by quota to obtain information or opinions to be analyzed
Both ultimately derive from sense 1 "Head". A poll is in this original sense, a head-count.
The word "poll" can be used for a formal election. (I believe that it is more common in that sense in the UK.) but can be, and now mor often is, used for an informal opinion servery. That kind of poll is not usually called an election. So one might say that all elections are polls, but not all polls are elections.
UPDATE based on additions to the question:
A selection by votes among users of an app for questions such as "Which one of these movies is better?" is not likely to be cvalled an election, and if that term is used it may cause confusion, or be thought odd. Such a choice is most likely to be called a "poll", but it might be called a "vote". Calling it an "election" would, in my view, be unwise.
Elections, in addition to usually being for official or at least well-defined positions, generally have a limiterd and defiend electorate (set of possible voters). A choide in which any random person can participate, and no accoutn is kept of who does participate, is not likelyn to be called an "election".
The answer by fertilizerspike mentions the choice of a "prom king" and "prom queen" at many US high schools. This choice is indeed called an election, or least it sometimes will be so called. It is true that these are not official positions. But they are fairly well defined and recognized positions, at least within a given school. They generally have actual function, althoguh not very important ones: the "king" and "queen" appear at a particular time and place, in that role, and no one else does so. Once the vote is held and the results tallied, there is normally no debate about who in fact holds the position. In all these ways this choice is more like an election, and less like an opinion poll, and so it might well be called an election, whereas an expression of opinion on "who is most sexy" or "who is the best actor" has none of these characteristics, and would nor normally be called an election.
thank you for response, could you have a look at the edited question i provided some more details.
Unsure why this answer mentions me at all, least of all why it attempts to refute my answer.
They are interchangeable in most cases. Many speakers might prefer to reserve "election" to describe the process of picking politicians or board members and so on but a common exception is "prom king and queen" election, a routine practice at high school dances in many places. There is no "prom king" office or authority, people just vote for who they like and watch them dance. The "viewer poll" seems to be a marketing invention and an idiosyncratic one, as most selections based on polling are called elections in which participants vote. Whenever a population is polled to select individuals for any reason it may safely be called an election.
A commonly used construction is "voted", eg "that celebrity was voted most sexy", which has the same meaning as "elected most sexy" but is more commonly used. The dictionary definitions might not suggest this usage of "vote" is valid, but it is commonly used without complaint and sounds natural to many English speakers.
In the example given, many native speakers would prefer calling such a poll a "vote", eg "Let's have a vote to decide which is the best movie."
Thank you very much for your response. Here is the thing: I have an app where people can vote for some stuff like the one I mentioned in to original post, similar to some twitter polls: "Which one of these movies is better?" type of polls. But I don't want to label these things as polls for some aesthetics reasons what if I labeled these polls as "Elections". I can see technically it is wrong but would a native english speaker be weirded out and be like "What do you mean elections?" or would they just roll with it because it doesn't feel unnatural?
Or I am open to any other suggestions.
-1 I would not say that "poll" and "election" are "interchangeable in most cases." Poll is a wider term. Most elections are polls, but many polls would not be called elections. A survey, to determine what random people, or people in general thought was their favorite actor, or the best player in a particular sport, would not usually be called an election. Nor are "elected" and "voted" interchangeable. A fluent speaker would not say that X was "elected the most sexy" although "voted the most sexy" would be likely. A choice among a group of people for such a purpose might be called a vote.
@khatara If you listen to this answer then you're clearly open to any suggestion.
@DavidSiegel, Astralbee Thanks vote seems to be the most viable option.
| common-pile/stackexchange_filtered |
Questions about ruby's nil class and rescue
Ruby Koans exercises has a file about_nil.rb. Below is its code:
def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
begin
nil.some_method_nil_doesnt_know_about
rescue Exception => ex
assert_equal NoMethodError, ex.class
assert_match(/undefined method/, ex.message)
end
end
What does ex.class mean? What is ex (the error type class)? Why does ex have a class? Also What's the difference between assert_equal and assert_match? Why does the error message need to be between / /?
What does ex.class mean?
It is the class of ex.
What is ex (the error type class)?
Any potential error is captured by the rescue keyword. The rescue Exception => ex line receives that and assigns it to a local variable ex.
Why does ex have a class?
Because ex is an exception object. Every object in Ruby has a class.
What's the difference between assert_equal and assert_match?
Whether they apply equality == or regex match =~ to check the test.
Why does the error message need to be between / /?
To make it a regex, as a substring would not match a string containing it.
| common-pile/stackexchange_filtered |
Author with email in tikzposter with affiliation index in name
I am customizing a theme using as base tikzposter. My authors here have each one some shared affiliations and the emails will not look good with the affiliation since would be confusing the relation between affiliation markers and the email (an email might be related to two authors and that is not desired). If I put the email after name with a linebreak the affiliation symbol will be in the email and not in the name. My current MWE is below. ¿How can I still have emails in authors but marker affiliation right after the name?
\documentclass[a0paper, landscape]{tikzposter}
\usepackage{authblk}
\makeatletter
\renewcommand\TP@maketitle{%
\hspace{3em}
\begin{minipage}{0.7\linewidth}
%\centering
\color{titlefgcolor}
{\bfseries \Huge \sc \@title \par}
\vspace*{1em}
{\LARGE \@author \par}
\vspace*{1em}
{\LARGE \@institute}
\end{minipage}%
\hfill
}
\makeatother
\makeatletter
\def\maketitle{\AB@maketitle}
\renewcommand\AB@affilsepx{\quad\protect\Affilfont} % put affiliations
into one line
\makeatother
\renewcommand\Affilfont{\Large}
\usetheme{Wave}
\title{ \begin{minipage}{\textwidth}
Super long long long long long long long long long long long long long
long long title
\end{minipage}}
\author[1]{Homer Simpson \\<EMAIL_ADDRESS>\author[1,2]{Marge Simpson}
\author[3]{Lisa Simpson}
\author[4]{Bart Simpson}
\affil[1]{\normalsize University of North}
\affil[2]{\normalsize Scientific Center of the north}
\affil[3]{\normalsize The University of Love}
\affil[4]{\normalsize University of Life}
\begin{document}
\maketitle
\block{hi}{example}
\end{document}
As I mentioned in chat, it's not entirely clear to me exactly what kind of layout you want. Can you try to clarify, or make a visual representation of what you want?
| common-pile/stackexchange_filtered |
Opening QFile fails when path is dynamically generated
Im currently working on a project in QT Designer and I'm totally confused when it comes to file paths.
Im using a QString to save my directory/file path,
QString filePath;
fill it with a QFileDialog and then I generate the filename in a stringstream, convert that into QString and add the two togehter.
std::stringstream name;
name << "/" << now->tm_mday << now->tm_mon << now->tm_year + 1900;
name << now->tm_hour << now->tm_min << "rec" << ".csv" << std::endl;
QString fName = name.str().c_str();
filePath = filePath + fName;
But when I try to open a QFile with it like this, the programm crashes.
out = new QFile(pathQ);
The weird thing is, when I print the path to the console and copy paste and hardcode that into filePath it works perfectly fine.
std::cout << filePath << std::endl;
and
filePath = "C:/Users/Me/Desktop/Recordings/6120211616rec.csv"
It also works when I just hardcode the "/6120211616rec.csv" and add it to filePath.
Does it make any sense that there is a difference in the path, even if it looks the same if printed to the console?
Thanks for your much needed help :)
I imagine filePath and pathQ are the same thing, right? Could you make a small main to replicate the issue?
Appending std::endl at the end of name makes out->open(QIODevice::ReadWrite) fail. Try withouth it
That sounds logical. And that explains why hardcoding the string works. I'll try that later when I get home
For what it's worth, when I have weird issues like this, the first thing I do is print the entire string I'm opening and make sure it makes sense.
| common-pile/stackexchange_filtered |
'npm' is not recognized as an internal or external command, operable program or batch file after installing Node.js - Windows
I was looking for this topic but none of the founded solutions works for me.
I'm working on a Laptop with Windows 10 OS, where I do not have admin rights.
I'm trying to run my Angular + NodeJS app on this machine after cloning the repository from GitHub.
After installing Node.js from the official site (admin put his credentials to do that) I can not run 'npm' command anywhere (cmd or VS Code terminal). Always received same error:
'npm' is not recognized as an internal or external command, operable program or batch file
In "Control Panel" I can see that Node.js is installed.
Any help will be useful!
You need to add the node command to your path (i. e. C:\Program Files\nodejs\npm.cmd).
If you are not able to add something to the path, open your command line, go to the node folder and start npm.cmd from there.
add ;C:\Program Files\nodejs\ in your environment path
| common-pile/stackexchange_filtered |
how to BOLD a fragment of the linkText in an Html.ActionLink?
I have this:
<li><%:Html.ActionLink(user.Email.Replace(Model.SearchString, "<b>" + Model.SearchString + "</b>"), "LoginEdit", "Admin", new { area = "Staff", webUserKey = user.WebUserKey }, null)%>, last login: <%:loginString%></li>
As you can see, I want the portion of the Email string that matches the Model.SearchString to be bolded. I can't figure out the syntax to make this happen, given the context of my code.
Any ideas?
The goal is something like this (assuming user searched for "john"):
<a<EMAIL_ADDRESS>
can you show what your "final" markup needs to look like?
I have posted the final markup goal.
what is the actual markup that is being rendered?
Whenever I encounter a situation likes this, I try my best not to embed HTML inside HTML helpers. In addition, I think breaking up your code will help in future maintenance - you're doing a lot in a single function call.
I would prefer doing it this way:
<li>
<a href="<%: Url.Action("LoginEdit", "Admin", new { area = "Staff", webUserKey =user.WebUserKey }) %>">
<%: user.Email.Replace(Model.SearchString, "") %>
<b><%: Model.SearchString %></b>
</a>
last login: <%: loginString %>
</li>
It's a few more lines of code, but it makes it much easier to decipher what's going on.
I think the issue is that the output of <%: %> is HTML encoded. So your <b> tag is probably encoded and you see the actual tag in the rendered HTML instead of the bold text.
If user.Email is a trusted value you could skip HTML encoding the output.
<li><%= Html.ActionLink(user.Email.Replace(Model.SearchString, "<b>" + Model.SearchString + "</b>"), "LoginEdit", "Admin", new { area = "Staff", webUserKey = user.WebUserKey }, null)%>, last login: <%:loginString%></li>
For more information see: http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx
and if it's not trusted, you can encode it in the ViewModel before passing it to the View.
| common-pile/stackexchange_filtered |
How to prevent UILabel to fill the entire screen?
I am trying to display a UILabel that may take up multiple lines but I'm having problem with how the height is resized.
Here is what it looks when I have text over a single line, displaying correctly:
When the text spans multiple lines however this happens:
Here's the interface builder settings I'm using:
Ideally I'd like the text view to remain at athe top of the screen and just take up as much space as it needs to diaplay the text but I really can't tell where I am going wrong.
The text view is a bit tricky to handle with automatic layout. If possible use an UILabel. If not then there are several issues with the text view and the most manageable solution is to add the height constraint which is then manipulated in the code.
The height of the text view content can be determined as:
let height = textView.sizeThatFits(textView.frame.size).height
It is also possible to use
let height = textView.contentSize.height
But the results are sometimes incorrect.
You do need to then set the delegate for the text view so that on change you will refresh the size of the text view.
What do I do with that size once I have it? Setting a new frame to the UILabel does nothing.
Sorry, this was meant for the UITextView. Your issue must be somewhere else. As for the usage of this you need an outlet to the height constraint of the text view and set its constant to the value of retrieved height.
Well you did give it permission to do so based on your constraints. Any height > 0 as long as it's 20 from the top margin. Since you don't have any other views to base your height off of you can hook up an outlet to your label and use this:
@IBOutlet weak var label: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
label.sizeToFit()
}
The label already does that by itself. It has a content hugging priority which should be set to 251 by default. It means that if no constraint is set to restrict the size then it will shrink as much as its content (text) allows. The problem is using a text view like this.
I set up constraints as in his example and ran this code. It fixes the issue. Also, the OP is asking about UILabel, not UITextView.
That did not fix the issue for me. Neither calling sizeToFit() nor setting the label's frame programmatically.
@Frankie My bad. Actually this should work. There must be another another thing that is wrong here overall.
@spacitron Is the outlet hooked up correctly? If you are setting the text programmatically, are you calling sizeToFit after setting the text?
@Frankie yes, I'm calling it after. I also tried setting a height constraints and setting it to 50 but that also does nothing.
Uncheck the "Preferred Width" explicit checkbox(In Size Inspector)
Remove the height constraint on you UILabel.
It will definitely work.
| common-pile/stackexchange_filtered |
Why did the Soviet Union name their strongest bomb Tsar Bomba?
The Soviet Union has/had the most powerful (Hydrogen) Bomb ever, the Tsar Bomb.
Why did they name it Tsar Bomb, when they had freed themself from the Tsars before, and even executed Tsar Nicholas II?
Welcome to History:SE. That looks like an interesting question. What has your research shown you so far? Where have you already searched? Please help us to help you. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].
The King of the Bombs, naturally. I see no relation between executing a ruler and using a word that what his title.
Why would Americans call their beds "king sized" and "queen sized" even though they fought a war hundreds of years ago to keep King George out of their business? And why are Burger King and Dairy Queen still things in America?
Presumably they named it that to participate in Tsar Wars... (gets coat) (leaves)
@EricLippert Obviously because "Washington-sized" is ambiguous between the man, the city and the state, and these are significantly different sizes.
@David Why not "President-sized"? ;)
@EricLippert - I think Dairy Queen is a sterling example of how little regard Americans hold for the idea of royalty.
When you design the largest bomb ever built, manufacture it to half that scale, and it's still the largest bomb ever built; call it whatever you want.
The official designation for that particular device was the RDS-220. The nickname Tsar Bomba was an appellation applied by the West, rather than the designers of the bomb (who - according to the site linked above - apparently referred to it as Big Ivan, or simply the Big Bomb).
According to the information on nuclearweaponarchive.org,
The nickname Tsar Bomba is a reference to a famous Russian tradition for making gigantic artifacts for show. The world's largest bell (the Tsar Kolokol) and cannon (the Tsar Pushka) are on display at the Kremlin.
The only reference to the device that I could find made by a member of the design team simply refers to the RDS-220 as the "Big Bomb":
"... Krushchev was already familiar with the test program, and in particular with our program to explode a device of record-breaking power, the "Big Bomb"."
Andrei Sakharov, Memoirs, New York, 1990, p218
(It's worth noting that "Big Bomb" is the English translation from the original Russian. It would be interesting to know if there is an alternative translation if anyone has access to a copy in Russian).
In any event, since Sakharov headed the design team, the fact that he doesn't use the term Tsar Bomb in his memoirs would seem to support the idea that it is a western designation for the device.
Andrei Sakharov, Memoirs, New York, 1990 - The curious thing is that the Russian version does not seem to not any sentence like this (I can't even find what chapter/period this text from the English version may correspond to - both versions seem to be quite different from each other - there's no even any "bomb" in quotes - it's all just a/the bomb(s) w/o any quotes or nicknames).
@seven-phases-max According to Google Translate, Chapter 15 has the terms "product" and "Big product", rather than "Big Bomb".
Aha, I see now - so it's "большое" изделие (i.e. roughly "Big" product) used several times. Which means Sakharov's nickname for the developed device is roughly just "The Big" (). Изделие was often used for things you could not or should not name explicitly (e.g. Изделие №2 was used instead of condom).
@seven-phases-max That would make sense. Since the "products they were making were atomic weapons, The Big Product, _The Big One", "The Big Bomb" etc. might all just be variations on a theme. I found a number of sites claiming (without citing a source) that the project was code-named "Ivan", which - if combined with "большое" изделие - could explain the origin of the "Big Ivan" claim. Either way, as far as the original question goes, it seems that the "Tsar Bombe" moniker was a Western name, rather than a Russian one.
For the "Big Ivan", the ru.wikipedia refers to http://www.militaryparitet.com/nomen/russia/aviabomb/data/ic_nomenrussiaaviabomb/3/ saying "Ivan" was used for two projects, but it's difficult to say what sources are used there (though counting the other names - e.g. at least three popular female names there, it does not look strange or weird... ) After all "Катюша" was one of most famous things and most likely was used as an inspiration for the later nicknames.
It seems that Khruschev called it "Kuzka's Mother.
In Russian Language the word "Tsar" has also another, non-literal meaning.
Examples are: "Tsar-pushka" (king of the guns), the largest
(in caliber) existing gun, and "Tsar-kolokol" (king of the bells), the largest bell in the world. Both the gun and the bell are currently in the publicly accessible part of the Kremlin, (and were there during the last two centuries), they are popular tourist attractions, many
Russians have seen them, and all Russians know them. The analogy is clear: Tsar bomb was the largest
(most powerful) bomb ever exploded. Anyway, it seems probable that the name
"Tsar bomba" is of Russian (not US) origin.
http://mos-holidays.ru/tsar-pushka-tsar-kolokol/
Remark. Neither the gun nor the bell were ever used (the bell cracked when they were casting it). Hopefully this will apply to the bomb as well.
But if the other answer is correct, the use of “Tsar” in Russian is completely irrelevant, isn't it?
@DaG I would say that both answers are more like supplemental rather than conflicting. This is neither official nor original name, but just a nickname that became in use much later. But even in Soviet times, words like "tsar" or "tsarskiy" were absolutely fine to use in everyday life (as synonyms for "rich"/~"incredible"), there was nothing royalist in them (unless stated specifically as in "Tsarist Regime"). Though, when it comes to the Bomb, the more widely-used nickname among the Russians since the end of 1980s is probably Kuz'kina Mat'.
Thanks for further explaining, @seven-phases-max, but if Russian-language people didn't call that bomb in a Tsar-related way, the use of “tsar” and derived words in Russian, while very interesting, is irrelevant to the name of this particular device.
@DaG Ah, I see what you mean now. Indeed. Though since the question itself arises from the fact that for an English speaker the word Tsar is solely associated with something Royal (while in Russian it has much wider meaning), I think this answer does a good job in explaining of how that nickname might appear and get in use.
The bomb was "used" in the sense that it was exploded in a test in 1961.
Information only (if that :-) ) : As designed the bomb was capable of about twice the yield actually achieved. The full capacity was well above what was required for its intended purpose (which was to act as a "statement" by Kruschev wrt international 'talks') and would have produced massively more fallout and have been incapable of being 'dropped' without destroying the drop aircraft. SO the yield was halved by use of a lead 'tamper' in place of what would usually have been a Uranium tamper - intended to be driven into fission by neutrons from the prior fusion stage.
Interest only" A "nice' albeit apocryphal story is told re a US monitoring aircraft. The 'test' was pre-announced by Russia and the drop site was near international airspace. A US monitoring aircraft was nearby at the time of the explosion. At the time of detonation the US craft is said to have been closer to the bomb than the fleeing Russian drop craft and the US aircraft came home with scorched paint. The tale may even be true :-).
@seven-phases-max Why not make an answer out of that? Both the information that "tsar" and "tsarskiy" were used in Soviet times, and the widely-used Soviet nickname for the bomb.
@SQB I think the existing answers are OK in general (I'd like to answer too but as a freaking perfectionist I'd had to put too much time to make an answer making myself happy).
@seven-phases-max well, I found your comment to be the most useful asnwer, as it demonstrated the false premises. A) it wasn't called the Tsar Bomba by the Soviets, and B) using "tsar" in everyday speech was quite common, despite having executed the Tsars during the revolution.
http://slovarozhegova.ru/word.php?wordid=34652 and https://www.efremova.info/word/tsar.html
This sounds like a Russian analogy to the way Americans use the idiom "Mother of all ...".
@Barmar: I am not a native English speaker, and I never thought that this expression is "American". Can you give an example? The first time I've heard this was when Saddam used: "The mother of all wars". But Saddam was not American:-)
@Alex U.S. Drops ‘Mother of All Bombs’ on ISIS Caves in Afghanistan
1. (As already mentioned in other answers/comments) The literal meaning of Russian Tsar Bomba is The King of the Bombs. Just that, not The Bomb of a/the King/Tsar or something like that (i.e. there's no specific "royalist" connotation there or any ideological connection to a monarchy as a form of government in general).
2. Tsar Bomba neither was the official name of the device nor it was an unofficial nickname used by its designers. This nickname came in use much later (80s?) and it's not even clear if the Soviets started to use this form first or it came from the West.
(For more details on the (nick)names of the device and origins of the "Tsar Bomb" nickname, please see other answers here).
---
And finally even if such name was (but yet again it wasn't) invented by the bomb designers, there would be nothing strange:
3. As already mentioned the Russian word tsar is basically an equivalent of the English word king having almost the same wide connotations/meanings (probably even wider). I.e. just like eating Burger King does not make you a royalist in your place, use of Tsar word did not make you a royalist in the USSR.
Idioms involving tsar and its derivatives are quite common in Russian and, unless stressed specifically (e.g. as in "Tsarist Regime" or "Tsarist Henchmen"), the word brings no ideological/political context.
In short: it is/was often used just as a synonym for (roughly) exceptional/rich/incredible:
царь зверей - lion
царица полей - infantry (or maize)
царский подарок - royal gift
etc. and so on. And it was nothing special about using this word(s) in Soviet times either (except maybe the very first years right after 1917).
4. In fact, even when it comes to the primary monarchy government meaning of Tsar, there was no taboo or a sort of either.
Soviets did not deny or try to diminish the historical achievements of Russian Tsars (where it was applicable). Often it was quite in opposite actually (obviously stressing the achievements belong more to the people rather than to the ruler himself).
E.g. notice the two most epic Soviet movies of 40s: Alexander Nevsky (1938) and Ivan Grozniy (1944). Both are named of knyaz'/tsar.
Tsar, also spelled Csar, or Czar, is derived from the Latin title for the Roman emperors, "Caesar". Usually considered by western Europeans to be equivalent to "king".
Tsar Bomba would simply mean "King of Bombs" or "King Bomb" "Emperor Bomb" etc.
There seem to be a lot of answers explaining "Tsar" as being equivalent to "King", which true-ish, but a bit of a simplification. It could be argued "Tsar" is closer to "Emperor".
The word is a Russification of "Caesar", which of course was the patronym of the founder of the Roman Imperial system, Julius Caesar. The word "Kaiser" is the German equivalent.
Many of the Emperors after Julius Caesar were made heir-apparent via adoption, at which point they picked up the "Caesar" patronym. Eventually it just became a title the later Roman Emperors used. The Byzantines afterward took it up to designate the Emperor's heir-apparent.
The Russians in their early days did nearly all their trade with Constantinople, and looked to that city as their model for civilization. So when their own domains became worthy of the title of "Empire", the ruler naturally had to be a "Tsar".
English monarchs during their own imperial period didn't chose to take up that title, and were instead just styled as "Emperor" or "Empress". So that's probably the closest equivalent we have in English. However, we're more apt to describe the best of something as "King of the...". The only metaphorical "Emperor" I can think of in English is the Emperor Penguin.
So in this particular case "King of the Bombs" is indeed probably the best translation. Its just not a literal translation. But of course in this case it was English-speakers making a mock back-translation into Russian.
In perhaps his only positive contribution to the world, Saddam Hussein bestowed upon English the alternative phrase "Mother of all...". So in modern English you could instead argue that this is equivalent to "Mother of all bombs". Which of course the Americans do have one of - the B MOAB.
You forget that Russian Tsars starting from Peter The Great called themselves "Emperor". This was their official title (Tsar then became more like unofficial title + "ruler of some local territories" subtitle). So yes, there're nuances (like a tsar may be considered like someone having more power than a king), but even if Tsar cames from Ceasar, "King" is still the closest translation in either literal or non-literal meaning.
E.g. notice the full title by 20 century includes "... Tsar of Kazan, Tsar of Astrakhan, Tsar of Poland, Tsar of Siberia, Tsar of Chersonese Taurian, Tsar of Georgia ...". We barely would consider these as Empires (and then go with Tsar -> Emperor).
@seven-phases-max - It is kind of tough, since the Russian rulers went from "Prince / Grand Prince" (or Duke / Grand Duke depending on translation) straight to Tsar, and then to Emperor (but still informally called Tsar). So it could be argued that to them "Tsar" is more equivalent to "King" than "Emperor". Mapping Russian titles to the ones used by the rest of Europe has always been a challenge.
Well, speaking of "Prince" it is/was very rough translation from Knyaz' - we just (still) don't have any better (Technically Knyaz' is usually considered to have the same roots as Germanic König, i.e. basically it's the King again). Sure you are absolutely right about original intentions of the Grand Princes to switch to Tsar to emphasize the amount of their power but apparently it did not work well hence later switching to Emperor (and then the meaning of the word also starts to fade down).
But, doh, why could it matter? After all I can't see any significant difference between King of Bombs and Emperor of Bombs, so I'm sorry for spoiling it (that was supposed to be just a minor remark as always :). For those who interested there's a few details on modern Tsar usage at https://russian.stackexchange.com/questions/15879.
Well, one's a thing that is said (or a "Snowclone" according to Wikipedia), where the other is not. As I said in the answer, "Emperor of" isn't a metaphor we usually use in English.
There is an actual & old Russian Khrushchev/Nixon allusion to this 'mother-angle': Мы вам покажем кузькину мать!
| common-pile/stackexchange_filtered |
The 'pattern' parameter (undef) to DateTime::Format::Strptime::new was an 'undef', which is not one of the allowed types: scalar scalar
I'm currently running into an issue getting perl cgi script browser display on my local machine (http://localhost:8080/Monitoring/www/user_status.xml.pl?user=xxxxxx). As it was a first install of Perl I understand there might be missing libraries so I make it up by pulling the required "pm"s across to my local machine (from company Ubuntu server where the cgi runs fine) and restart Apache to pick up the latest fixes. All looks fine as I work through "Can't Locate ..." problems until I stuck on the following issue.
The 'pattern' parameter (undef) to DateTime::Format::Strptime::new was an 'undef', which is not one of the allowed types: scalar scalarref
at C:\xampp\htdocs\Monitoring\lib/Params/ValidatePP.pm line 653.
Params::Validate::__ANON__("The 'pattern' parameter (undef) to DateTime::Format::Strptime"...) called at C:\xampp\htdocs\Monitoring\lib/Params/ValidatePP.pm line 497
Params::Validate::_validate_one_param(undef, HASH(0x26e646c), HASH(0x26e68d4), "The 'pattern' parameter (undef)") called at C:\xampp\htdocs\Monitoring\lib/Params/ValidatePP.pm line 356
Params::Validate::validate(ARRAY(0x26e8b24), HASH(0x26e6514)) called at C:\xampp\htdocs\Monitoring\lib/DateTime/Format/Strptime.pm line 131
DateTime::Format::Strptime::new(undef, "pattern", undef) called at C:\xampp\htdocs\Monitoring\lib/Geo/DateTime.pm line 47
require Geo/DateTime.pm called at C:/xampp/htdocs/Monitoring/www/user_status.xml.pl line 10
main::BEGIN() called at C:\xampp\htdocs\Monitoring\lib/Geo/DateTime.pm line 0
eval {...} called at C:\xampp\htdocs\Monitoring\lib/Geo/DateTime.pm line 0
Compilation failed in require at C:/xampp/htdocs/Monitoring/www/user_status.xml.pl line 10.
BEGIN failed--compilation aborted at C:/xampp/htdocs/Monitoring/www/user_status.xml.pl line 10.
Looks to me like the Perl libraries are having internal issues and complaining on its own code. Did a search on Google, couldn't find any resolution / suggestions around the issue described in the Title. And doesn't look to me like a missing libraries problem.
Anyone know what is the problem here and what can I do to fix it?
Cheers
Dale
Looks to me like you passed undef as the pattern parameter to DateTime::Format::Strptime::new.
Thanks Matt, what you said does remind me of something I changed that makes my local perl script different to the one on server. I'll revert it back and see how it goes. Thanks
We could probably provide more accurate help if you post the actual code.
At line 47 of C:\xampp\htdocs\Monitoring\lib\Geo\DateTime.pm, you have something equivalent to the following:
DateTime::Format::Strptime::new(undef, "pattern", undef)
This reveals two bugs:
You called new as a subroutine rather than as a method (since the invocant is undefined).
You provided an incorrect value for the pattern.
| common-pile/stackexchange_filtered |
Change frame caption forecolor
I have a radio button within a frame (frame1). On frame 2, I have a number of checkboxes. This frame (frame2) becomes editable when the radio button is selected from frame1. How can I modify my code so the Caption of frame2's forecolor changes also?
I've tried adding the following to the logic already in place for enabling the frame, but doesn't work.
frame2.ForeColor = vbRed (should work?)
frame2.Caption = vbRed
I've also tried the Hex color code with no look.
Can anyone advise?
Im using a enum to assign the radio buttons.
(Found in global declaration)
Private Enum
ExampleRef optB1_blah = 1
etc...
optB5_blah = 4
End Enum
(This code is found in a function)
If Example(ExampleRef.optB5_radiobtnchoice).Value Then
'//bug fix -
frame2.ForeColor = vbRed
'//If Not statement with unrelated logic
If vblnShowErrors Then
Err.Raise 10000, VALIDATION, "error, you cant make this choice."
End If
blnDataFail = True
End If
End If
blnMinData = Not blnDataFail
End If
frame2.ForeColor = vbRed should work, I just tested it out right now.
Also, what event are you using for the radio button? Click? GotFocus? Something else?
If optExample(ExampleRef.optB5_radiobtn5).Value '//Then carry out some logic
@LittleBobbyTables I've added to my question.
That doesn't tell me when the code is called. Is it called in a function, a subroutine, an event, what? Post your code.
@LittleBobbyTables added code example
Poor practice anyway. The whole thing assumes that users are using default system colors that let "red" text even be visible. See Raymond Chen's remarks http://blogs.msdn.com/b/oldnewthing/archive/2007/12/12/6648399.aspx
Fixed this, I was looking in the wrong function, long day! The frame.ForeColor = X syntax was fine.
| common-pile/stackexchange_filtered |
HTML5 hide code like Flash
I was wondering, if I have a proprietary flash code (e.g: some cool animation which is really just client side stuff, its just example), and about to rewrite it using HTML5, is it possible to hide the code? or at least make it harder to see (unlike right click, view source, then you can just copy paste the code).
e.g: to get to see or maybe reuse flash, u have to reverse engineer it.
As a general rule, people are a lot less interested in stealing your "cool animation" than you think they are.
@ceejayoz well.. it's not really animation.. It's just an example to make the question clear :)
My point applies to more than animation.
No there is no way to do this. Also reverse engineering swf files is trivial with programs like swf-decompiler and trillix, so it doesn't really matter too much. The main point is don't put anything important in the client side code that you wouldn't want compromised. Anything sent from a server to a client to do processing on the client side can be intercepted by a proxy running on said client and de-compiled/disassembled. As the other user here stated you can use .htaccess to restrict access to server side scripts (ones executed on the server) but you cannot completely "hide" anything that is going to be executed on the client machine.
Possibly the best attempts I've seen at doing this were done by Google for their flash maps api where they give you a swc in their SDK to use that has only interfaces then the implementation is fetched at run-time in the form of another swf, problem is that swf can also be intercepted and then de-compiled. There is no hiding when it comes to something executed on a persons machine assuming they have admin privileges on the machine that the code is executing on. (this is not a fallacy of HTML or Flash it's true of any language, C creates assembly, which with the right knowledge can be reverse engineered).
You can obfuscate your code so that people have a hard time reading it
use this http://javascriptobfuscator.com/default.aspx
for exemple this:
var a="Hello World!";
function MsgBox(msg)
{
alert(msg+"\n"+a);
}
MsgBox("OK");
will become this:
var _0xb75d=["\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21","\x0A","\x4F\x4B"];var
a=_0xb75d[0];function MsgBox(_0x4338x3){alert(_0x4338x3+_0xb75d[1]+a);}
;MsgBox(_0xb75d[2]);
To protect swf files from decompilation you could use:http://www.kindi.com/
If your code is anyhow complex, and you use any minification - that would be enough to put away 99.99% of people who might have wanted to steal your cool animation.
| common-pile/stackexchange_filtered |
VB - Excel checking previous value give an error
I am trying to learn a bit of VB and there is an exercise to change a value and check the previous value and if it is different do something. I eventually found a solution I could understand and get to work from : How do I get the old value of a changed cell in Excel VBA? - solution 4.
My code is:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Variant
For Each cell In Target
If previousRange.Exists(cell.Address) Then
If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
cell.Interior.ColorIndex = 36
End If
End If
End If
Next
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cell As Variant
Set previousRange = Nothing 'not really needed but I like to kill off old references
Set previousRange = CreateObject("Scripting.Dictionary")
For Each cell In Target.Cells
previousRange.Add cell.Address, cell.FormulaR1C1
Next
End Sub
The next exercise was to add a button and perform an action depending on the user's response. So I added:
Private Sub CommandButton2_Click()
Dim currentValue, message As Integer
currentValue = Range("C3").Value
message = MsgBox("Click OK to add 1, cancel to leave", vbOKCancel, "Addition")
If message = 1 Then
Range("C3").Value = currentValue + 1
End If
End Sub
The problem I have is that the button adds one to C3 but then falls over at the If previousRange.Exists(cell.Address) statement on the Worksheet_Change sub.
All the code is defined on Sheet1, but I do not seem to have a previous value generated for my button value(C3). How do I generate the previous value, or what am I missing?
Regards
J
As I seemed to have made things worse I have created a new spreadsheet with just the change events code and nothing else to try and simplify the problem. So the complete code I have now is:
Option Explicit
Dim previousRange As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Variant
For Each cell In Target
If previousRange.Exists(cell.Address) Then
If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
cell.Interior.ColorIndex = 36
End If
End If
End If
Next
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cell As Variant
Set previousRange = Nothing 'not really needed but I like to kill off old references
Set previousRange = CreateObject("Scripting.Dictionary")
For Each cell In Target.Cells
previousRange.Add cell.Address, cell.FormulaR1C1
Next
End Sub
Now if I change the B12 cell, the previousRange As New Dictionary code is highlighted, and a message states "Compile error:User defined type not defined".
This code used to work before I introduced the message box and made a subsequent change. Must be user error. Can you help?
Regards J.
The .Exists method is used on dictionary objects, like the example you've cited. But I don't see where you've declared a dictionary object in your code. Maybe you're missing a declaration statement for it?
Dim previousrange As New Dictionary
Please note that, like the solution you've cited, you'll need to declare this before the sub routine. Also, you'll need to enable the Microsoft Scripting Runtime. Here's how:
In the VBA editor, go to the Tools menu and click on References...
In the Available References list box, scroll down until you see Microsoft Scripting Runtime. Make sure its check box is checked.
Click OK.
Now you're able to use Dictionary objects.
Aaron, I think I have gone backward. I tried adding your code and I still got an error. Just incase I got it wrong i deleted what I had added (which is didn't recognise and included a comment) and tried again. I am now getting 'User-defined type not defined'. I am concerned I have delete the generic directory class and I am not sure how to add it back? J
Hmmm, not sure what's going on. Maybe you could add what you currently have, to the end of your original question? You can do this by editing your question.
Good deal - could you mark the answer as "answered" by clicking the check box below the voting? Thank you.
| common-pile/stackexchange_filtered |
Emscripten SDL Compilation faliure
I'm new to emscripten; several days ago I've downloaded it just to try to make a port of a game to JS.
Anyway, after some steps, I'm having this issue now (on Ubuntu 16.04 STL).
By following build steps here, first of all, I've set environment variables with
source ./emsdk_env.sh and then I've tried to configure the project with emconfigure ./configure in the project directory. When checking for tools emscripten needs, I've got this error:
checking for SDL... no
configure: error: Package requirements (sdl2 >= 2.0.1) were not met:
No package 'sdl2' found
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
Alternatively, you may set the environment variables SDL_CFLAGS
and SDL_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
ERROR:root:Configure step failed with non-zero return code 1! Command line: ['./configure'] at ...
So I've tried to set that variable with the following command:
export PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig/
This is where actually sdl2.pc is located on my machine, but it didn't help.
So then I've set the following variables that emconfigure needed:
export SDL_PATH=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDL_LIBS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDL_CFLAGS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDLNET_LIBS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDLNET_CFLAGS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDLMIXER_LIBS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
export SDLMIXER_CFLAGS=/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h
and relaunched emconfigure ./configure which has completed well.
So the next step is emmake make that gives me the following error:
make all-recursive
make[1]: Entering directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0'
Making all in textscreen
make[2]: Entering directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen'
Making all in fonts
make[3]: Entering directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen/fonts'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen/fonts'
Making all in .
make[3]: Entering directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen'
CC txt_conditional.o
Traceback (most recent call last):
File "/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/emcc", line 11, in <module>
python_selector.run(__file__)
File "/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/tools/python_selector.py", line 38, in run
sys.exit(run_by_import(filename, main) if on_allowed_version() else run_by_subprocess(filename))
File "/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/tools/python_selector.py", line 13, in run_by_import
return getattr(importlib.import_module(os.path.basename(filename)), main)()
File "/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/emcc.py", line 1345, in run
assert header.endswith(HEADER_ENDINGS), 'if you have one header input, we assume you want to precompile headers, and cannot have source files or other inputs as well: ' + str(headers) + ' : ' + header
AssertionError: if you have one header input, we assume you want to precompile headers, and cannot have source files or other inputs as well: ['/home/ustym/Documents/Projects/emsdk/emscripten/1.37.38/system/include/SDL/SDL.h', 'txt_conditional.c'] : txt_conditional.c
Makefile:447: recipe for target 'txt_conditional.o' failed
make[3]: *** [txt_conditional.o] Error 1
make[3]: Leaving directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen'
Makefile:467: recipe for target 'all-recursive' failed
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0/textscreen'
Makefile:585: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/ustym/Documents/Projects/chocolate-doom-3.0.0'
Makefile:438: recipe for target 'all' failed
make: *** [all] Error 2
that means, I assume, that SDL_PATH, SDL_LIBS, SDL_CFLAGS... variables weren't set correctly. Or maybe I just need to precompile that headers in the SDL directory.
One last thing: if I skip setting SDL variables and the configuration step and just launch emmake make, the compilation goes well, but then, emcc command gives me
WARNING:root: .o is not valid LLVM bitcode
for all generated .o files. And that actually makes sense.
So I'm pretty stuck here. Somebody can tell me how to set correctly PKG_CONFIG_PATH for emscripten or if i really need to precompile those headers in the SDL directory? Thanks!
First of all, setting PKG_CONFIG_PATH, include or, even worse, library directories (-I and -L) to host libraries' ones looks like awful idea to me: Emscripten object files contain LLVM bitcode (and not host machine code), its .so files AFAIK contain bitcode as well. It is that bitcode that gets translated to JS, not host machine code. So you need to build your program's dependencies with Emscripten by yourself (and should most probably not install them to the host system). Fortunately, there are some official Emscripten ports (see here) for details.
Emscripten has its own implementation of SDL v1 (that you probably tried to use manually), but your program seems to require SDL2. Good news: you probably just need to pass -s USE_SDL=2 to CFLAGS and LDFLAGS when configureing (see later on the link above for information on SDL2 port). Bad news: something may not be fully ported. But I successfully used it to some extent.
When you have configured on host and make with emmake you probably had compiler paths among other parameters adjusted by emconfigure and emmake already baked into generated Makefile by ./configure not controlled by emconfigure, so host gcc/clang just generated machine code.
| common-pile/stackexchange_filtered |
Whatever happened to Hiroko Ai in Kim Stanley Robinson's Mars Trilogy?
After her disappearance, Sax thought he saw her in a blizzard (or maybe sandstorm), and remains convinced that he really has. But she is never seen by anyone again. What really happened with her?
I think that what happened to Hiroki is that she becomes one of the Mars myths. This is the real intention of the author.
The difficulty to assert if something is real or myth is, in a sense, what science is about. In my opinion this is an important theme for K.S. Robinson. This is especially obvious in his book Icehenge.
In other words, my interpretation is that nobody knows what happened to Hiroki (even Robinson) because, he was searching to elicit in his readers this feeling of legend mixed with real character that makes you to ask the question in first place.
Given the extreme circumstances that Sax found himself in, it is likely that he was simply hallucinating. The accounts of the Zygote survivors all indicate that Hiroko and a number of her inner circle were killed by the metanational forces.
Still - there were other rumours and apparent sightings, but as Mars became more populated no evidence of a new hidden colony was ever found. The first hidden colonies could only get away with hiding in the unpopulated south pole, so it seems unlikely that they could continue hiding once the Martian population started to grow and spread.
I think it might be a bit easier with more people around, after all, if they find a colony, there's really no telling who it'd be...
but the other colonies - even the demi-monde - would be registered.
true, but even in countries with strict central control like China there are millions of people who're unknown to the government yet live out in the open.
I think it's safe to say Robinson intentionally left it unanswered, though he I believe he had a most likely outcome in mind and tipped it off. It is significant that Hiroko had reached mythic status, sometimes being seen in two places at once. I don't think the Asian woman referenced at the end could be Hiroko, because she would have been recognized. She might have been a nod to the other false Hirokos like the one on Earth. To be honest, I am not sure where he was going with that, because it was hard to read it and not think of Hiroko (one final tease for the reader perhaps).
My own view, sadly, is that Coyote had it exactly right. Hiroko was killed in the initial attack and "disappeared" the way secret police have done time and again. No mystery to solve, just a grim and abrupt end. Sax hallucinated her and his later enhanced memory was just an echo of the hallucination. I would add as supporting evidence the fact that she did not even attempt to reconnect over a long series of funerals for the first hundred.
I find this ending unsatisfying but realistic. It is how I would read the same account laid out as non-fiction and see no reason to apply different logic here.
I would also make the case that Coyote's statement marks a significant development in the book. In the following passage, Robinson is tipping off the reader that "Mars exceptionalism" doesn't always hold, and sometimes the explanation can be as simple and brutal as any earth-bound banana republic. He does this through a high-credibility character (Coyote) who finally comes out with the point everyone else is afraid to voice (from Part Nine, Natural History):
Coyote shook his head violently. “No. I am the exception that proves
the rule. Anyone else, when they are reported in two places at once,
that means they are dead. A sure sign.” He made a stop thrust to
forestall Sax’s next remark, shouted “She’s dead! Face it! She died in
the attack on Sabishii! Those UNTA storm troopers caught her and Iwao
and Gene and Rya and all the rest of them, and they took them to some
room and sucked the air or pulled the trigger. That’s what happens! Do
you think it never happens? Do you think that secret police haven’t
killed dissidents and then disappeared the bodies so that no one ever
finds out? It happens! Fuck yes it happens, even on your precious Mars
it happens, yes and more than once! You know it’s true! It happened.
That’s how people are. They’ll do anything, they’ll kill people and
figure they’re just earning their keep or feeding their children or
making the world safe. And that’s what happened. They killed Hiroko
and all the rest of them too.”
This seems well thought out, but what does it add that the existing answers do not already cover?
I feel that my answer has better supporting evidence, and I have expanded it. The only compelling reason to believe that Hiroko is still alive is Sax's memory, and even he does not trust it fully. Coyote, on the other hand, has come to a conclusion after years of scouring the planet. He makes an Occam's razor case for the simplest explanation of why she has never been seen. I don't think the passage would be written that way--unless Hiroko really came back to contradict it--if the reader was expected to believe she was still alive.
The quote is a good addition, could you edit in the book and chapter it comes from?
In the very end of the entire series - very end - Ann comes near to death, and then sees an older Asian woman flying a kite at the sea's edge.
This is only speculation, but there seemed to me an enormous significance of birth to the closing being a combination of:
1) New birth (Ann & Sax together with children),
2) Blue Mars realized,
3) The horticulturist 'mother' of Mars Hiroko flying a kite (was it her?).
It seemed to be poignant to the author to point out the ethnicity and age of the last stranger seen in the last pages of the last book, by a couple who fought at extremes, to be in fact a very older Asian woman from Earth who was flying kites with kids. Life, birth, growth - that was Hiroko Ai.
Since there's no concrete answer, this is my speculation. I see Hiroko when I read those last couple pages. Flying a kite while Ann and Sax are at the beach.
| common-pile/stackexchange_filtered |
Doctrine 2: multiple tables - one entity
How can I map multiple tables with identical structure to entity?
For example we have these tables :
Object_001 (id, name, lat, long)
Object_002 (id, name, lat, long)
Object_003 (id, name, lat, long)
..........
Object_41000 (id, name, lat, long)
..........
Object_xxxxx (id, name, lat, long)
Object Defination
class Object {
private $id;
private $name;
private $lat;
private $long;
}
I found similar problem: Doctrine 2.1 - Map entity to multiple tables and one of answer is physically merge the tables together in MySQL, but in my case I need seperated tables
Help would appreciated.
Thanks.
Short answer: You don't. You might try creating a view which merges your tables together but I doubt if that will work for you.
@SeantheBean, questions are completely different, so this question is not a dublicate. The question you mention is about merging multi table data into a single entity. However, what is asked here is he has n identical tables and he asks whether it is possible to map those tables into a single entity so that they are represented by that single entity independently.
Ah, sorry. I misunderstood the question. I don't think that's something Doctrine supports, so your best bet would be a workaround like what @Cerad suggested.
| common-pile/stackexchange_filtered |
How to design an optimistic/eager multi-step form?
An app that I'm building has a comprehensive onboarding process, involving a multi-step form with 5 steps. It's already a pretty boring process to fill out 5 forms with a bunch of image attachments, and the users also have to wait for each step to submit before moving on to the next. The backend's API is also designed to accept form submissions at each step.
Is there a way to let the user move on to the next step instantly after pressing the "Next" button, without having to wait for the form to be submitted at each step? If I make the submission in the background, I also want to be able to gracefully handle the scenario of when the submission fails. What would be a good UX for this?
One suggestion I found here was to go to the next step immediately and show a loading interface there instead of on the current step, but this only solves part of the problem and still leaves the user waiting for some time before being able to fill up the next form, especially if they are on a flaky connection (which would be the case for many users on the app that I'm building).
Thanks in advance!
Hi Ashwin, note that ux.stackexchange is strictly about UX and not about implementation. I think a good UX would be if the user is not blocked while the data is transmitted and validated. You could display a small status icon that shows what the current progress is and if a validation fails (similar to the save label that google sheets shows while it is saving).
Are there forms on one step that depend on input from another step?
Hey @Nash, sorry about the nature of the question, how can I reword it to make it more about UX? I'm just trying to make the form-filling process feel as snappy as possible, and am open to suggestions. To answer your question, the form inputs are not dependent across steps, they're completely separate. And about the status icon, an indicator would surely help (perhaps a small spinner that turns into a green check on success and a red exclamation on failure), but it might also be confusing for the user to have to guess how to take action in the event of a failure, which is where I'm stuck atm.
Depending on what you're willing to change, you could have your whole form on one page and after the user fills in an input box or uploads an image it would automatically validate the input and, if there is an error, display it in a box on the corner with errors in the form. So by the time the user reaches the end, most errors will have already been found, and clearly marked for completion.
Instead of a small red exclamation mark you would have a box with each error clearly labeled so the user can see and interact with each error. Additionally, you could have a dynamic form of which it's elements are composed of the inputs that failed validation. This would go at the end of the form and he prefilled with what the user already inputted
One common pattern that seems to work is to present this similar to a wizard where the list of steps is always present, either down the side or across the top, but with the modification that users can return to a previous step without resetting the process.
Then each step can be Incomplete, Processing, Failed, or Success independently of the others and error messages can be displayed on Failed pages close to the fields that need to be modified.
| common-pile/stackexchange_filtered |
How do I merge many similar tables?
I have many tables that all have identical structure and similar table names and am looking for a way to merge a few columns from them all into a new table with two additional columns: an auto-generated integer PK, and the name of the source table. e.g.,
UniqueID SourceID, Xcoord, Ycoord, Zcoord, SourceTable
I managed to create a table containing a list of all the tables I want to use, but don't know what to do next.
SELECT [name]
INTO PointTables
FROM [Surveys].[sys].[tables]
where [name] like '%CoordDB'
you are getting table name by using sys.tables but what about columns join with sys.columns
How many tables do you have? When I faced a similar situation I used union operations and then inserted that query into a new table. In my case the two new columns were an identity column and a calculated column.
Not very clear about the problem.
Are the columns name of those tables are same?
You want to insert to the PointTables?
You can create the table:
create table PointTables(
UniqueID int identity
, Xcoord int
, Ycoord int
, Zcoord int
, SourceTable varchar(50)
After that, you can insert table with help of sp_executesql command and concatenation
declare @command nvarchar(max)
select @command = 'insert into PointTables(Xcoord,YCoord,ZCoord,SourceTable)
select [Xcoord],[YCoord],[Zcoord],'''+name+''' from '+name from sys.tables where name like '%CoordDB%'
execute sp_executesql @command
Thanks - this gets me close but only grabs the data from the first table it finds. After searching around I found mention of cursors, but dont know how to use them yet.
Well, actually you can do some workaround with looping. Create a table that contain 2 columns: id and tablename. Id column is autoincrement, used for looping. Looping has better performance and easier syntax than cursor.
Thanks. Performance will become an issue when I start working on real data, so I will try that on the next round.
The answer from Charlie Lukman was a good start but for some reason only worked on the first table. I looked at several other posts and discovered cursors which allow you to work on one line at a time using a WHILE loop to build / concatenate several INSERT INTO commands. While this works in my test of 5 tables, I am concerned about performance when I get to 100's or 1000's of tables.
declare @command nvarchar(max)
declare @tblname varchar(50)
declare TableCursor Cursor
FOR SELECT name FROM sys.tables where name like '%%DB_COORD'
SET @command = ''
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @tblname
WHILE @@FETCH_STATUS <> -1
BEGIN
select @command = @command + 'INSERT into MasterPoints(SourceID, Xcoord, Ycoord, Zcoord, PtCode, SourceTable) SELECT UPTNUM, EAST, NORTH, ELEVATION, CODE,''' + @tblname + '''from "' + @tblname + '" '
FETCH NEXT FROM TableCursor INTO @tblname
END
CLOSE TableCursor
DEALLOCATE TableCursor
execute sp_executesql @command
SELECT distinct [SourceTable]
FROM [Manifold].[dbo].[MasterPoints]
| common-pile/stackexchange_filtered |
How do I see the cost of a specific Dataflow streaming job in GCP?
I have multiple streaming jobs running in the same project, and the GCP billing page isn't very granular - I'd like to break things out per job. Is there a way to do this?
Currently, the dataflow UI does not provide a per-job breakdown of costs. You can calculate the cost of a job using Dataflow's pricing rules, and multiplying those by the metrics in the Resource metrics section of the UI.
what do you mean by Resource metrics? I see the area where I can check each VM instance details, is that it?
I've added a screenshot of the job summary in the UI. The bottom of the image contains Resource metrics, such as Total vCPU time, Total PD Time, and Total memory time; which you can multiply by the dataflow rules to figure out the price of your job.
| common-pile/stackexchange_filtered |
convert data frames in nested lists to large data frame
I have a large nested List with 3 levels:
the elements are data frames with the same name.
List:
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
"name1" "name2" "name3" "name4" "name5"
numeric1 numeric2 string3 string4 string5
[[1]][[1]][[2]]
"name1" "name2" "name3" "name4" "name5"
numeric1 numeric2 string3 string4 string5
[[1]][[1]][[3]]
"name1" "name2" "name3" "name4" "name5"
numeric1 numeric2 string3 string4 string5
How I can rbind all data frames to one large data frame?
manually it works this way:
rbind(list[[1]][[1]][[1]], list[[1]][[1]][[2]],....)
Please provide a reproducible example.
(Why we need a reproducible example?) Because it's unclear whether your list has all of its values in the first sub-sublist of the first sublist. Might be a simple as do.call(rbind, listName[[1]][[1]] ), .... but maybe not.
@dom Take a look at this Converting nested list to dataframe
ldply(do.call("c",do.call("c",list)), data.frame)
Your answer would benefit immensely if you added some comment about what your code is doing and proof that this is indeed the correct solution.
| common-pile/stackexchange_filtered |
Mysterious "undefined is not a function"
I'm pulling my hair out trying to resolve this error. This is causing a Uncaught TypeError: undefined is not a function:
trange[abs][i] = BENTON(e1, z1, pa1, pI_pot, pz2, pa2);
Here's my function:
function BENTON(e1f, z1f, a1f, I_potf, z2f, a2f) {
//my stuff
BENTON_return = ((a1f / TAU) / (z1f * z1f)) * (prnglo[q] + bzz * cz[n]);
return BENTON_return;
}
There is this, which didn't shed any light on this issue. I know variations of this question have been asked before, but I'm hoping the generic instance of this error will be of some use to others that are also learning JS. Any input will be appreciated.
Update
In the interest of clarity, here is some code that will hopefully put this problem in better context:
function Dreamweaver() {
"use strict";
...
trange = new Array(1);
for (i = 0; i < trange.length; i = i + 1) {
trange[i] = new Array(MAXE);//create a new 2-D array
}
...
i = 0;
do {
e1 = tenerg[i];
trange[abs][i] = BENTON(e1, z1, pa1, pI_pot, pz2, pa2);
i = i + 1;
} while (tenerg[i] < 8.0);
...
}
function BENTON(e1f, z1f, a1f, I_potf, z2f, a2f) {
"use strict";
...
//a lot of mathematics
bzz = (31.8 + 3.86 * Math.exp((5.0 / 8.0) * logi)) * (a2f / z2f) * 1.0E-06 * Math.exp((8.0 / 3.0) * Math.log(z1f));
BENTON_return = ((a1f / TAU) / (z1f * z1f)) * (prnglo[q] + bzz * cz[n]);
return BENTON_return;
}
JSLint responds with the complaint that 'BENTON' was used before it was defined. I've done this kind of thing successfully before, where I constructed the JS equivalent of a subroutine. Here I'm wanting to employ functions that return single values. I know it's probably a small error, but I just don't see what I'm doing wrong. Any feedback would be great.
Where is that function declared? It doesn't seem to be in scope. Please show a complete example.
Is BENTON within the current scope when you're calling it?
Since this is an execution error we will need a demo, for instance we have no idea whether half those variables like prnglo, cz, TAU etc are defined..
If BENTON() is in the scope, there's probably a syntax error in it, which has prevented the function being parsed.
Edited original post with code that will hopefully clarify the issue.
You are using "use strict" but you are not actually making your code strict. You can all kinds of undefined variables (e.g. trange, i). Post code that actually demonstrates the problem.
This is the code that actually demonstrates the problem. JSHint and JSLint come up clean with the exception of the aforementioned error. So yes, I'm being strict. It is a very long script, so I've posted only the relevant portions.
You should stop using global variables
To resolve these issues I have procedures that behave like functions pass a single-valued array that is overwritten for each subsequent call. So the call goes from:
trange[i] = BENTON(e1, z1, pa1, pI_pot, pz2, pa2);
...to...
BENTON(e1, z1, pa1, pI_pot, pz2, pa2, reichweite);
trange[i] = reichweite[0];
My function goes from:
function BENTON(e1f, z1f, a1f, I_potf, z2f, a2f) {
//my stuff
BENTON = ((a1f / TAU) / (z1f * z1f)) * (prnglo[q] + bzz * cz[n]);
return BENTON;
}
...to...
function BENTON(e1f, z1f, a1f, I_potf, z2f, a2f, reichweite) {
//my stuff
reichweite[0] = ((a1f / TAU) / (z1f * z1f)) * (prnglo[q] + bzz * cz[n]);
return reichweite;
}
On the other hand, for procedures that behave like subroutines I pass a multi-valued array [] that is actively populated and not overwritten.
Hopefully this will help those that are new JS.
| common-pile/stackexchange_filtered |
How do I prevent duplicate entries in my Access database?
I am a first time coder with VBA and I am creating a database for data entry at a Psych Lab I work at. Currently the database is created, but I want to prevent duplicate entries from being put into the database (namely by have a code look for the participant number right after it is entered). I have been trying to fix this code for quite a while and I just recently hit a wall. It displays the correct error message when I enter the participant number, however it says that every number has been entered already (even though they actually haven't). Here is the code:
Private Sub Participant_Number_BeforeUpdate(Cancel As Integer)
Dim Participant_Number As Integer
Dim StLinkCriteria As Integer
If (Not IsNull(DLookup("[Participant_Number]", "Entry Log", "[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
MsgBox "Participant Number has already been entered in the database."
Cancel = True
Me.Participant_Number.Undo
End If
End Sub
Any help is greatly appreciated. I have never used VBA before and I am self-teaching how to code.
I guess your Participant_Number field is a number. You shouldn't enclose the criteria with single-quotes ', these are used with fields of text type. Try changing the criteria field from
"[Participant_Number] ='" & Me.Participant_Number.Value & "'"))) Then
into
"[Participant_Number] = " & Me.Participant_Number.Value))) Then
Thank you for the suggestion, but this did not fix the problem. I can get the error message to appear, but it appears for every number I enter regardless of whether or not it has already been entered.
@BreannaWallbaum this syntax is correct. You should check your data (are you sure the numbers were already entered? ), also check the field names and table names.
I am positive that the field names and table names are correct. I have already checked them. The numbers were not already entered and that is the problem. I would know because I just entered arbitrary data to test the database and have only entered 2 sets of data.
IF you have not used VBA you may try to do this by opening the table in Design view. This method is easy and a good choice. You may have a look here: https://support.office.com/en-us/article/Prevent-duplicate-values-in-a-field-b5eaace7-6161-4edc-bb90-39d1a1bc5576?ui=en-US&rs=en-US&ad=US&fromAR=1
I have already done that, however I need the user to get an error message saying that it has already been entered. Also, the way that I am setting up the database for entry will not give the raters access to the ribbons at the top of the screen. All they will do is hit enter to be taken to the next form (so the index option will not work). Thank you for the help, though.
is there a way to make an error message appear when say the raters hit the next button?
| common-pile/stackexchange_filtered |
Custom search filter in the react-admin
I have some data presented in List (react-admin component). I can add SearchInput into my Filter component that is used as filter in the List, type source in it and then data will be filtered by full match of the "source" field with text typped into the SearchInput. Is it possible to construct regular expression using text from the input and filter data based on regular expression, not the full match?
I have already tried dumb way - to change filters manually (i.e. set onChange prop for the SearchInput with my method which do the change) but it resulted in some unwanted side effects.
So the question again is, whether it is possible to filter data in based on regular expression that is constructed based on user input?
Can you show a snippet of your code before?
| common-pile/stackexchange_filtered |
FindNextPrinterChangeNotification misses events?
I am using FindFirstPrinterChangeNotification and FindNextPrinterChangeNotification to catch printing events. However I have noticed that FindNextPrinterChangeNotification does not reliably returns all the events. I have found a guy with the same problem in this article.
Basically, when I debug my program, or put Sleep command like his suggestion when processing an event, FindNextPrinterChangeNotificationskips a lot of events. Also, most of the time I get a lot of SPOOLING status events but miss the DELETED status event (sometimes I get it, but most of the time I cannot), even though I already push the jobs to a Queue for later processing.
Does anyone have this problem too? Also, I am trying the Microsoft PDF Printer, The NumberOfPages increases as the SPOOLING events come, but the NumberOfPagesPrinted does not. Is it intended?
EDIT After some investigation, the events are not actually gone. If I call another print job, the previous events are fired (including the DELETING/DELETED status of previous print job). Can you please suggest what is the problem?
Here's the code for calling FindFirstPrinterChangeNotification:
//We got a valid Printer handle. Let us register for change notification....
_changeHandle = FindFirstPrinterChangeNotification(_printerHandle, (int)PRINTER_CHANGES.PRINTER_CHANGE_JOB, 0, _notifyOptions);
// We have successfully registered for change notification. Let us capture the handle...
_mrEvent.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(_changeHandle, true);
//Now, let us wait for change notification from the printer queue....
_waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true);
And this is for the FindNextPrinterChangeNotification:
_notifyOptions.Count = 1;
_notifyOptions.dwFlags = PRINTER_NOTIFY_OPTIONS_REFRESH;
int pdwChange = 0;
IntPtr pNotifyInfo = IntPtr.Zero;
bool bResult = FindNextPrinterChangeNotification(_changeHandle, out pdwChange, _notifyOptions, out pNotifyInfo);
What parameters are you passing to FindFirst and FindNext? Are you requesting ALL notifications? Check https://msdn.microsoft.com/en-us/library/windows/desktop/dd162723(v=vs.85).aspx
@bizzehdee I have included the code in my question. I request for PRINTER_CHANGE_JOB only.
I also added setting the flag PRINTER_NOTIFY_OPTIONS_REFRESH, and I received a lot more events, but there is still no consistent DELETING Status.
The answer from alital is likely correct. By telling RegisterWaitForSingleObject not to reset the event, you're going to miss any events that occur during your callback.
I had the same issue then I tried:
_waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true);
with:
_waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, false);
(false arg in the end)
and seems to work now
I believe you copied the wrong line of code. I don't think you meant to say you replaced FindFirstPrinterChangeNotification with RegisterWaitForSingleObject.
| common-pile/stackexchange_filtered |
Should Vow of Enmity or Hexblade's Curse be deployed first?
Imagine an Oath of Vengeance Paladin 3 / Hexblade 1. This is the big boss, and the character wants to use both Vow of Enmity and Hexblade's Curse on the same target.
Vow of Enmity gives advantage on all attack rolls against the target. Hexblade's Curse gives +2 (proficiency bonus) damage on all attacks, and crits on 19-20. Assume the character will close to melee distance in the first round of combat. Since both features require a bonus action to activate, the character must activate one during the first round of combat, and one during the second round.
Which one should the character activate first?
Does the answer change if the character has Extra Attack?
Does the answer change if the extra damage (i.e. proficiency bonus) from Hexblade's Curse is higher?
I assume you are asking which will cause most damage?
We need more information. The more the better. You character’s ability scores and weapon of choice are probably necessary. Even better would be the boss’s armor class and hit points.
Well - obviously I thought this question was possibly to usefully answer in the general case, so I think it could be reopened. A very specific answer could of course be produced if the OP gives us an exact build, though I think my analysis shows that at the low level given in the question it is unlikely to make a practical difference to the answer.
@Carcer We can't really answer a question where we don't understand the goal — we don't even know if they want to optimise for damage. We could instead also answer from a resource management standpoint entirely valid.
Vow of Enmity at low levels, eventually shifting to Hexblade's Curse at the highest levels
Firstly, a few observations about how these two abilities compare to each other in various circumstances.
The easier it is to hit the enemy, the less benefit we get from advantage - so Vow of Enmity becomes less useful as our attack bonus increases or enemy AC decreases
The more damage our attack does normally, the less relative benefit we get from a couple points of extra damage - so Hexblade's Curse becomes less useful if we use a bigger weapon or have a higher damage modifier
Our chance to crit is slightly better with Hexblade's Curse - a 10% chance with expanded crit range vs. a 9.75% chance with advantage - so it has a very slight edge in terms of producing crits we can use to nova a divine smite on, but only slightly so
Advantage will tend to make our damage more reliable since it usually greatly reduces the chance of whiffing entirely
How many attacks we have (due to extra attack or any similar feature) is irrelevant to this damage analysis since each individual attack is affected the same way
The healing benefit of Hexblade's Curse almost certainly won't be relevant in the first round of combat and we'll have it active by the second round either way, so for that purpose it doesn't really matter which order we activate them in
Now, some numbers! I used this anydice script to calculate expected damage - hopefully it is obvious how you would modify it to change the parameters of the attack.
Basic Hexadin
Let's say our vengeful hexadin is using a longsword one-handed, has +2 proficiency and a +3 charisma modifier. That means a base damage of 1d8+3 and a +5 attack modifier. Running the numbers in my script against enemies of various ACs, the following values for expected damage fall out:
Enemy AC
Normal Damage
Vow of Enmity
Hexblade's Curse
5
7.35
7.92
9.475
10
6.225
7.639
8.05
15
4.35
6.42
5.675
20
2.475
4.264
3.3
25
0.6
1.17
1.4
As we can see, when the enemy is extremely easy to hit the benefit of advantage is smaller and the damage bonus from Hexblade's curse is greater. However, as the enemy AC increases, the greater reliability of hitting with advantage overtakes the benefit of the bonus damage. In this case the exact crossover point is AC 12; then it becomes better to use Vow of Enmity. It also seems extremely unlikely that a boss-type enemy will have an AC worse than 12, so absent any other information, we'd have to assume that Vow of Enmity is the appropriate first move.
However, there is an inversion when going up against an extremely high AC; once it becomes so difficult to hit that we only hit on a crit (AC 25 in this case), Hexblade's Curse becomes the better option again, since the hit chance improvement is nearly identical and the hit just does more damage.
Critical Hitadin
What about if we add a special proviso that if we critically hit, we'll throw in a 1st level divine smite for a delicious 4d8 extra damage? (In my script, you can do this by adding 4d8 to the CRITDAM parameter.) Expected damage goes up a bit:
Enemy AC
Normal Damage
Vow of Enmity
Hexblade's Curse
5
8.245
9.675
11.275
10
7.125
9.394
9.85
15
5.25
8.175
7.475
20
3.375
6.019
5.1
25
1.5
2.925
3.2
But the relative value of each approach stays similar, and in fact even in this scenario the crossover point is the same. The 0.25% difference in crit chance between the two features is just so small that it makes nearly no difference to the calculation of which is better.
Optimal Hexadin
Now consider a different set of parameters; our more-optimised vengeful hexadin is using their longsword two-handed and has a +5 charisma modifier, so they're doing 1d10+5 base damage and have a +7 to hit. Does this change the outcome?
Enemy AC
Normal Damage
Vow of Enmity
Hexblade's Curse
5
10.25
11.01
12.425
10
9.725
10.931
11.8
15
7.1
9.75
8.675
20
4.475
7.256
5.55
25
1.85
3.45
2.42
30
0.8
1.56
1.8
As it turns out, no. Obviously our damage is higher overall, but the same relationship holds that once the enemy has a reasonable AC, advantage is better. In fact, the crossover point in this case is still AC 12, and it remains true that Hexblade's Curse only takes over again once we need a crit to hit at AC 27.
Mid-tier Hexadin
Let's add a few levels and some magical equipment to our character. How about a +4 proficiency modifier, a +5 charisma bonus and a +1 magic longsword? Now we're doing 1d10+6 base damage and have a +10 to hit.
Enemy AC
Normal Damage
Vow of Enmity
Hexblade's Curse
5
11.2
12.008
15.275
10
11.2
12.008
15.275
15
9.475
11.576
12.95
20
6.6
9.708
9.075
25
3.725
6.401
5.2
30
0.85
1.658
2.1
Because of our high attack bonus, for ACs of 10 or lower we only miss on a crit so those rows in the table will be the same, but above that we see a similar relationship play out. This time the break point has moved to AC 18 - below that, Hexblade's Curse is better, but above that, the Vow of Enmity wins out, with the caveat again that once we only hit on a crit the Curse regains the upper hand.
AC 18 is in the range of what you would expect for a boss monster at that tier, so at this point without actually knowing what the enemy's AC is, we're hard-pressed to guess which ability to activate first. If it looks particularly well-armoured then go for the Vow of Enmity, if not then pop the Hexblade's Curse. It will be useful to have allies who attack before we do so we have a chance at figuring out the enemy's AC before we have to act.
Epic Hexadin
Let's go wild. Now our vengeful hexadin is level 20, has a +3 magic longsword they're wielding two-handed, a +6 proficiency modifier and has somehow arranged for themselves a +6 charisma modifier, so they've got 1d10+9 base damage and a +15 attack bonus. Let's say they've even taken the 11 paladin levels required to get Improved Divine Smite, for an extra 1d8 base damage on all attacks. How are the numbers now?
Enemy AC
Normal Damage
Vow of Enmity
Hexblade's Curse
5
18.55
19.928
24.75
10
18.55
19.928
24.75
15
18.55
19.928
24.75
20
15.7
19.215
21
25
10.95
16.128
14.75
30
6.2
10.665
8.5
35
1.45
2.828
3.5
This time the crossover point is AC 23, which is extremely high for 5e; a search of D&D Beyond indicates there are only 8 published stat blocks with an AC of 23 or higher. If we're fighting Tiamat or the Tarrasque, the Vow of Enmity is more useful; but for a foe in the more likely 19-21 AC range, the Hexblade's Curse is better.
If we tune down our parameters a bit, by dropping to a +1 weapon and a +5 charisma bonus, the breakpoint only goes down to 21, which is still higher than the majority of monsters (the DMG's guidance indicates that an AC of 19 is typical for monsters at CR 17+). If we instead alter our level distribution to favour the Warlock side and lose the bonus 1d8 base damage from Improved Divine Smite, the breakpoint increases to AC 25! (recall that Hexblade's Curse provides a relatively larger benefit when our attack has less base damage.)
Conclusion / TL;DR
The relative value of these two features will change as you level, partly because the Hexblade's Curse bonus damage improves as you level while the Vow of Enmity does not change, and partly because your attack bonus will probably scale up faster than enemy AC does. For any given build there is an enemy AC breakpoint above which the Vow of Enmity is best and below which the Hexblade's Curse is better.
At low levels, in any realistic combat encounter you will see the biggest improvement in expected damage from using Vow of Enmity; since the bonus damage from Hexblade's Curse is so small, the improved reliability of damage from advantage trumps it. The AC breakpoint will be so low that you would expect any significant foe you face to have an AC higher than that.
At the mid-tier, it becomes harder to judge which is most useful, since the break-even point between the two will be inside the range of ACs you expect your foes to have.
At very high levels, the increased damage from Hexblade's Curse has become significant enough that it is likely the superior option in most encounters; the AC breakpoint is high enough that it is probably above the AC of your enemy.
For any given build, though, you can use a script like mine to work out what the actual enemy AC breakpoint is. The assumptions I've made in my calculations above seem reasonable for establishing a rule of thumb, but once you're out of the low levels, which option is actually best for you will depend on the specifics of your character and the enemy you face.
I love how you addressed the tier / advancement examples to answer the question beyond the 3/1 MC ... bravo.
Very useful analysis, and thanks for the link to the anydice script.
@RedGeomancer no worries. If you're so inclined, editing your question to clarify that you're interested in damage optimisation (as I have essentially assumed in my answer) should satisfy those stackizens who felt the question need more clarity and lead to a reopening.
@Carcer After a couple of unsuccessful recent attempts to fix questions to get them reopened I would rather bash my head against a wall. Even though the question is closed, I was able to select this as the correct answer. I doubt we will get a better one, so there is not much value in reopening.
| common-pile/stackexchange_filtered |
Why the values are continuously getting printed since no loop or no next call is given to the PHP file?
Following is an demo example of 'Server Sent Events(SSE)':
HTML code(index.html) :
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
PHP Code(demo_sse.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: $time\n\n";
flush();
?>
The output I got is as follows :
Getting server updates
The server time is: Sun, 31 May 2015 15:27:00 +0530
The server time is: Sun, 31 May 2015 15:27:05 +0530
The server time is: Sun, 31 May 2015 15:27:10 +0530
The server time is: Sun, 31 May 2015 15:27:15 +0530
The server time is: Sun, 31 May 2015 15:27:20 +0530
The server time is: Sun, 31 May 2015 15:27:25 +0530
The server time is: Sun, 31 May 2015 15:27:30 +0530
The server time is: Sun, 31 May 2015 15:27:35 +0530
The server time is: Sun, 31 May 2015 15:27:40 +0530
The server time is: Sun, 31 May 2015 15:27:46 +0530
The server time is: Sun, 31 May 2015 15:27:51 +0530
The server time is: Sun, 31 May 2015 15:27:56 +0530
The server time is: Sun, 31 May 2015 15:28:01 +0530
The server time is: Sun, 31 May 2015 15:28:06 +0530
The server time is: Sun, 31 May 2015 15:28:11 +0530
The server time is: Sun, 31 May 2015 15:28:16 +0530
The server time is: Sun, 31 May 2015 15:28:21 +0530
The server time is: Sun, 31 May 2015 15:28:26 +0530
The server time is: Sun, 31 May 2015 15:28:31 +0530
The server time is: Sun, 31 May 2015 15:28:36 +0530
.
.
.
and so on....
So my question is I've written a PHP code to print the server time once then why after certain irregular time interval the output is keep on printing?
Thanks.
Why do you have the flush(); in demo_sse.php?
@nhee: To flush the output data back to the web page. To push the message out to the client as soon as possible.
From the manual EventSource
The EventSource interface is used to receive server-sent events. It connects to a server over HTTP and receives events in text/event-stream format without closing the connection.
and
reconnection time
This is a time, in milliseconds, used to determine how long to wait after a failed attempt to connect before trying again.
When you look at the server's log file, you will see that the client connects every few seconds to reestablish the connection. This happens, because the PHP script closes the connection, when it finishes.
When you add a sleep to the end of the script, e.g.
$time = date('r');
echo "data: The server time is: $time\n\n";
flush();
sleep(600);
the connection stays open for some time. Then, the client just waits for new messages and doesn't try to reconnect to the server.
| common-pile/stackexchange_filtered |
How to register DI services for specific Interface type?
I have interface IServiceHandlerAsync<T> and I have following service registrations
services.AddScoped<SoftwareTestService>();
services.AddScoped<SoftwareTestCaseService>();
services.AddScoped<SoftwareTestCaseStepService>();
services.AddScoped<SoftwareTestCaseStepResultService>();
where each of these services are inherited from interface IServiceHandlerAsync<T>
is it possible to resolve and register aforamentioned services without specifying every service explicitely by using interface (I am thinking that reflection may do the work) ?
Algorithmic example would be
foreach (var service in .getResolvedServices<IServiceHandlerAsync>)
{
services.AddScoped(service);
}
Like this? https://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface
I ended up with the following solution.
System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(mytype => mytype.GetInterface(typeof(IServiceHandlerAsync<>).Name) != null)
.ForEach(appCoreService => services.AddScoped(appCoreService));
Thank you for your time
Quick answer: No
Long answer: No - not using functionality provided out of the box by Microsoft.Extensions.DependencyInjection.Abstractions. These packages provide very basic functionality and were originally built to make use of the early version of the dotnet standard (like 1.1 - ~1.5) which contained hardly any reflection functionalities. Thus they force you do declare your dependencies in an explicit way:
services.AddScoped<SoftwareTestService>();
services.AddScoped<SoftwareTestCaseService>();
services.AddScoped<SoftwareTestCaseStepService>();
services.AddScoped<SoftwareTestCaseStepResultService>();
A more important question for me is - If you register multiple implementations of your IServiceHandlerAsync interface, how do you decide which one you are going to get/need?
You see IServiceprovider.GetService<IServiceHandlerAsync> will only return one of them (and there is no specification as to which one of the 4 you registered you're going to get) while IServiceprovider.GetServices<IServiceHandlerAsync> will return all of them, leaving you with the task of sorting out which one you´ll be needing - which is exactly something that dependency injection is supposed to take off your shoulders.
I am using generic Interface for crud operations, and I know that all inherited members of IServiceHandlerAsync<T> needed to be registered as service. I ended up with solution which can be seen below.
| common-pile/stackexchange_filtered |
Webcam software for "work area"
How can I produce a time-lapse video of a workarea (mostly of a project board).
The post Time-lapse software for Windows 7 pointed at some software, but they generate too much video or are images only.
Willing Webcam (http://www.willingsoftware.com/) meets most of what I am looking for, but tends to crash my XP machine (sorry, that's a work restriction).
What I want to do is
detect motion
when motion stops, add a frame to a video
block detection for a time period
Basic time-lapse may be the best solution in the end (and various tools support that) but does end up with a surprising number of people wandering through.
Useful features, but not essential
add a date and timestamp in the image
zoom into the portion of the Image I want to keep
Although I would rather a video file were produced, images that could be strung together would do.
Not going to post as an answer (yet) but take a look at WebCamXP (http://www.webcamxp.com/download.aspx) and see if this is OK.
Webcam XP seems reliable (probably best menu settings of the many apps I have played with), but unfortunately security mode records the motion - and seems to create new files (the latter may be my fault)
Alright. Only really used as a webcam server so don't know about the other features that well, but thought it would be worth pointing out.
Have You tried out Vitamin d. http://www.vitamindinc.com
I think it will cover everything you need.
Unfortunately, although I can set it to monitor people... it records all of the event. This is another good tool though and the people identification was very good.
| common-pile/stackexchange_filtered |
FIX API quickfix multithreading
What is the proper way of connecting to mulitple servers/acceptors using quickfix?
Create a thread for each session under the fix application
Create a seperate application for each session, create multiple initiators, start each initiator in a seperate thread
And another related issue -
How does MultiThreadedInitiator class fits in...?
Quickfix already allows multiple sessions. They just have to be defined in your configuration file. From then on you can track messages using SessionID.
I think MultiThreadedInitiator ensures each session is created in a different thread.
| common-pile/stackexchange_filtered |
Trying to parameterize a connection, parameters not displaying
I am trying to parameterize a connection, but when I go to 'use existing parameter' none of my parameters are showing up (it is empty).
What is the reason for this?
Note: This package was using package configuration before
Steps:
Right-click on one of connections in the 'connections managers' tab, select 'parameterize...'. I then select the radio 'use existing parameter'. The dropdown list is empty.
@billinkc I updated my question with the steps thanks!
what is the setup of the parameter that you have created, and I hope not to offend with this next question but are you confusing parameters with variables?
| common-pile/stackexchange_filtered |
if i inside an if statement checks if a method returns true, will the actual code in the method be executed?
Okay so.. i have a method that basically checks if the player can buy the field and if he can then sets him as the owner and return true. the method i am referring to is buyFieldFromBank in the if statement.
But i want to check if my method returns true, and if it do, ask the user if he wants to buy it. can i actually do it like this? or will the code allready have set him as owner in the if statement? Or does it only "check" if it turns true, without actually executing the code?
if(landRegistry.buyFieldFromBank(currentPlayer, newPosID)==true){
if(GUI.getUserButtonPressed(currentPlayer.getName() + ", vil du købe " + newPosition.getFieldName() + "Ja", "Nej")=="Ja"){
landRegistry.buyFieldFromBank(currentPlayer, newPosID);
It has to execute the code to actually know if it returns true. Also, for that second if-statement, note that you almost certainly do not actually want to compare strings using ==. See http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
You're calling the landRegistry.buyFieldFromBank method twice.
Thanks a lot. That is exactly what i was worried about. :)
Comparisons to boolean values (==true) are redundant. You already have a boolean value; you don't need to use == to create a boolean.
Couple of obvious issues:
1) You're using == instead .equals to compare Strings in the 2nd if, well tread debate covering that issue here: Link
2) By calling landRegistry.buyFieldFromBank you are executing that method, so it will already be done. You need a method like landRegistry.isUserEligible(currentPlayer,newPosId) to check in that first if statement. Then if it passes both the first & secondary conditions it should call the buyFieldFromBank method. Also it may be worth considering if that 2nd if should belong in the isUserEligible method call; if it's part of the logic of determining eligibility it might fit best there.
3) The == true part of the first if is redundant if the method you're calling returns a boolean. So you can drop that part and just have the method call itself.
The == is just a brainfart.. i did know that :D.... But thanks! with practice i wont make these dumb mistakes (hopefully :D)
And with regards to the method in the if statement, i was unsure, so it is nice to know i cannot do it like that.
Good idea with the method that checks if player is elligible.
@SryImStillNewb Glad to help! Keep at it and always focus on the 'Why` aspect of the answers to these kinds of questions instead of just what works.Practice makes perfect with these kinds of things.
Yea you are definately right. the "Why" aspect is important. I'll keep that in mind!
The part about == true being redundant blew me away lol. That i did not know! But i can see it now. Clever!
If you call a method with . you're executing that method always. How else can it work? You should change your design.
| common-pile/stackexchange_filtered |
i18next best practice
I've successfully implemented i18next, which by the way is a great library! Though I'm still in search for the "best practice". This is the setup I have right now, which in general I like:
var userLanguage = 'en'; // set at runtime
i18n.init({
lng : userLanguage,
shortcutFunction : 'defaultValue',
fallbackLng : false,
load : 'unspecific',
resGetPath : 'locales/__lng__/__ns__.json'
});
In the DOM I do stuff like this:
<span data-i18n="demo.myFirstExample">My first example</span>
And in JS I do stuff like this:
return i18n.t('demo.mySecondExample', 'My second example');
This means I maintain the English translation within the code itself. I do however maintain other languages using separate translation.json files, using i18next-parser:
gulp.task('i18next', function()
{
gulp.src('app/**')
.pipe(i18next({
locales : ['nl','de'],
output : '../locales'
}))
.pipe(gulp.dest('locales'));
});
It all works great. The only problem is that when I've set 'en' as the userLanguage, i18next insists on fetching the /locales/en/translation.json file, even though it doesn't contain any translations. To prevent a 404, I currently serve an empty json object {} in that file.
Is there a way to prevent loading the empty .json file at all?
Have you considered using a custom loader?
Or allow the 404! This is what happens when it cascades through the fallbacks anyhow. An expected 404 isn't going to break the application unless you set some sort of global handler to "halt execution on any 404 errors."
Maybe I'm missing something here but couldn't you simply do this:
if (userLanguage != 'en') {
i18n.init({
lng : userLanguage,
shortcutFunction : 'defaultValue',
fallbackLng : false,
load : 'unspecific',
resGetPath : 'locales/__lng__/__ns__.json'
});
}
That way your script i18n wouldn't be initialized unless you actually needed the translation service.
That'll work for the DOM labels, but in that case I don't think the i18n.t(key, defaultString) method will process properly.
@RonaldHulshof: You could also create a dummy i18n object with the t method that simply returns defaultString. var i18n = { t: function(key, value){ return value; }}
i18next-parser author here, I will explain how I use i18next and hopefully it will help:
1/ I do not use defaultTranslation in the code. The reason is that it doesn't belong in the code. I understand the benefit of having the actual text but the code can get bloated quickly. The difficult part consists in defining intelligible translation keys. If you do that, you don't really need the defaultTranslation text anymore. The translation keys are self-explainatory.
2/ If you have a 404 on the /locales/en/translation.json, then probably that you don't have the file in your public directory or something similar. With gulp you can have multiple destination and do dest('locales').dest('public/locales') for instance.
3/ If there is no translation in the catalog, make sure you run the gulp task first. Regarding populating the catalog with the defaultTranslation you have, it is a tricky problem to solve with regexes. Think of this case <div data-i18n="key">Default <div>translation</div></div>. It needs to be able to parse the inner html and extract all the content. I just never took the time to implement it as I don't use it.
In regard of 3/ Populating the catalog: Text labels in good semantic HTML should not contain <div> tags, only tags like <em> and <strong>. If someone intents to use non semantic HTML, he/she is better of not to use the auto-population feature. For anyone else, it could be a great, great, great feature. Now that I have been using the text inline as described for roughly 9 months, I am still very pleased with the choice I made back then. In my development team, this way of working with translation, works very very well.
I understand, though I don't think "good semantic HTML" justifies not parsing all scenarios. If you make a PR that covers all scenarios (div in div) I will review it but at the moment I can't spend time on this library.
See http://i18next.com/pages/doc_init.html under "whitelist languages to be allowed on init" (can't fragment link on those docs...):
i18n.init({ lngWhitelist: ['de-DE', 'de', 'fr'] });
Only specified languages will be allowed to load.
That should solve your problem. Though I suppose a blacklist would be even better.
This actually blocks loading i18next when I define 'en' as the userLanguage. Or better said, it'll even crash i18next.
@RonaldHulshof That's weird. I can't imagine that's the intent of the whitelist option. Is one of your init options conflicting with it?
No, the above configuration is the one I actually use.
| common-pile/stackexchange_filtered |
What is the range of expectation value in quantum machine learning
If I want to build a quantum circuit to solve a regression problem in machine learning, and the target value is 200~300. In qiskit, we can use VQR to easily implement it, and it will output the expectation value as the prediction, but I found the expectation value is usually around -1 ~ 1, which is far away from the targeted value. How can we understand this issue? Or can we say quantum circuit is not a good choice for regression in machine learning? And I tried to normalize the y_value before training, and observed a better performance, in this case, can we say that in terms of regression, we have to scale the y_value into the expectation value range for good performance?
And I noticed the training of this quantum circuit took much longer time than classical machine learning,like xgboost, simple neural network, is it normal? My understanding is that each data point in the training dataset has to be passed into the circuit one by one, and this is why it takes so long time. If this is true, it seems like quantum machine learning is not a good choice for large dataset. At least in classical neural network, we can feed batch data into the model and do the training in parallel, but in quantum circuit, it seems impossible. If it is correct, then how can we show the efficiency of quantum machine learning?
def create_qnn(n_qubits: int = 4):
feature_map = ZZFeatureMap(n_qubits, reps=2)
ansatz = EfficientSU2(n_qubits, reps=1)
qc = QuantumCircuit(n_qubits)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True)
return qnn
qnn4 = create_qnn()
regressor = NeuralNetworkRegressor(
neural_network=qnn4,
loss="squared_error",
optimizer=COBYLA(maxiter=200),
callback=callback_graph)
#x_train.shape is [1000,4]
#y_train.shape is [1000,]
regressor.fit(x_train, y_train)
| common-pile/stackexchange_filtered |
Sorting list in java and looking for max percentage
In my task I need to sort list in Java but I only sorted list by population. In class City I also have number of obese people. How to return perctentage.
class CovidSorter implements Comparator<City> {
@Override
public int compare(City o1, City o2) {
Integer compareInt = o1.numberOfPeople().compareTo(o2.noOfPeople());
return compareInt;
}
}
Input:
New York People: 10000000 Obese: 50000
Seattle<PHONE_NUMBER>
Las Vegas 2000000 12345
New York: 0.5%
Seattle: 0.75%
Las Vegas: 0.61725%
So highest number has Seattle.
My problem is how to properly call it in main so sorter could work and implement (numberOfCitizens/obesePeople)*100. In my task I had set but I casted it to a list.
You could do it by implementing that logic inside your comparator:
cities.sort(Comparator.comparingDouble(
c -> ((double) c.getNumberOfPeople() / c.getObesePeople()) * 100.0));
See Comparator.comparingDouble docs for further details.
EDIT: As you say you need to do it inside your class, here's a way:
class CovidSorter implements Comparator<City> {
@Override
public int compare(City o1, City o2) {
double p1 = ((double) o1.getNumberOfPeople() / o1.getObesePeople()) * 100.0;
double p2 = ((double) o2.getNumberOfPeople() / o2.getObesePeople()) * 100.0;
return Double.compare(p1, p2);
}
}
Thanks for answer, but I need to do that in my class:
Integer compareInt = (o1.getNoOfCitizens()/(float)o1.noOfObese())*100). COMPARE here wont work
I made 2 local variables and then just compared them:
public int compare(City o1, City o2) {
float max1= (float) ((o1.getNoOfObese() / (float)o1.getNoOfCitizens()) * 100.0);
float max2= (float) ((o2.getNoOfObese() / (float)o2.getNoOfCitizens()) * 100.0);
if(max1>max2)
return 1;
else if(max1<max2)
return -1;
else
return 0;
But Comparator.comparingDouble is simplier way but my taks was to made it in class. Thank you for your help :D
| common-pile/stackexchange_filtered |
How to prevent landscape orientation in phonegap(html)?
I am using following code to prevent landscape orientation in phonegap(html) not pure android.
1.First i am installed "cordova-plugin-screen-orientation" plugin in my project folder and then i am include cordova.js and in my program i am include the following line.
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js" type= "text/javascript"></script>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
</head>
<body>
<h3>hello</h3>
</body>
<script>
screen.lockOrientation('landscape');
console.log('Orientation is ' + screen.orientation);
window.addEventListener("orientationchange", function(){
console.log('Orientation changed to ' + screen.orientation);
});
</script>
</html>
To compile my program, it gives the following error.
E/Web Console﹕ Uncaught TypeError: Object #<Screen> has no method 'lockOrientation'
How to solve this error.
Just forget about the plugin and add this line to your config.xml
<preference name="Orientation" value="landscape" />
screen.lockOrientation('landscape'); <= where did you find this? Is it something you made up? You'll need to delete this line.
And technically, your preference in config.xml should be
<preference name="Orientation" value="landscape" />
I think that's from this plugin (https://github.com/gbenvenuti/cordova-plugin-screen-orientation). Anyway, I think his problem is he calls that method before device ready fires.
Cant you set orientation in manifest file
<activity
android:name=".Android_mobile_infoActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I am not using pure android. I am using html with cordova
| common-pile/stackexchange_filtered |
Does an explicit expression exist for the moments of the residuals in least squares regression?
Consider the linear regression model is
$$
Y_i = \beta_0 + \beta_1 X_i + \varepsilon_i,
$$
where $X$ is a random variable and the error has finite variance $\sigma^2$.
When we solve this with least squares we find $\hat \beta_0$ and $\hat \beta_1$. These variables can be used to define $\hat Y$ which gives us an estimator of $Y$:
$$
\hat Y_i = \hat\beta_0 + \hat \beta_1 X_i.
$$
The residuals are then defined as
$$
\hat e_i = \hat Y_i - Y_i.
$$
I want to compute the expectation of a Taylor expansion of a function $f$ of the residuals. Since the residuals have an expected value of zero I get
$$
\begin{align}
E[f(\hat e_i)] &= E[f(0) + f'(0)\hat e_i + \frac{f''(0)}{2}\hat e_i^2 + \frac{f'''(0)}{3!}\hat e_i^2 + \dots] \\
&= f(0) + \frac{f''(0)}{2}E[\hat e_i^2] + \frac{f'''(0)}{3!}E[\hat e_i^3] + \dots
\end{align}
$$
To ensure this expansion is valid I need to know the moments of residuals. Are there explicit expressions for these moments? I have looked at many books but could not find anything.
Let's take a classical linear regression model:
$$y_i = \boldsymbol{x}_i^T\beta + \varepsilon$$
where $\varepsilon_1, ..., \varepsilon_n \overset{IID}{\sim}\mathcal{N}(0, \sigma^2)$ and $\boldsymbol{x}_i^T = (1, x_{i1}, ...x_{ip})$.
This model can be written in matrix form as:
$$Y = X\beta + \boldsymbol{\varepsilon}$$
where $Y\in\mathbb{R}^n$ is the vector of the responses, $X\in\mathbb{R}^{n \times p}$ is the design matrix and $\boldsymbol{\varepsilon} \sim\mathcal{N}(0, \sigma^2 I_n)$ is a multivariate normal vector.
The least square estimator is given by $\hat\beta = (X^T X)^{-1}X^TY$ and the residual $\hat{e}_i$, as you defined it, is given by
$$\begin{array}{ccl}
\hat{e_i} & = & \boldsymbol{x}_i^T\hat\beta - y_i\\
& = & \boldsymbol{x}_i^T(X^T X)^{-1}X^TY - y_i\\
& = & \boldsymbol{x}_i^T(X^T X)^{-1}X^T(X\beta + \boldsymbol{\varepsilon}) - y_i\\
& = & \boldsymbol{x}_i^T(X^T X)^{-1}X^TX\beta + \boldsymbol{x}_i^T(X^T X)^{-1}X^T\boldsymbol{\varepsilon} - y_i\\
& = & \boldsymbol{x}_i^T\beta - y_i +\boldsymbol{x}_i^T(X^T X)^{-1}X^T\boldsymbol{\varepsilon}\\
& = & -\varepsilon_i + \boldsymbol{x}_i^T(X^T X)^{-1}X^T\boldsymbol{\varepsilon}\\
& = & (-b_i^T + \boldsymbol{x}_i^T(X^TX)^{-1}X^T)\boldsymbol\varepsilon
\end{array}$$
where $b_i$ is the vector of $\mathbb{R}^n$ made of zeros and a 1 at the $i-th$ position.
Now, as you know that $\varepsilon \sim\mathcal{N}(0, \sigma^2 I_n)$, using the property that for any full rank matrix $M$, if $Z \sim\mathcal{N}(\boldsymbol{\mu}, \Sigma)$, then $MZ\sim\mathcal{N}(M\boldsymbol{\mu}, M\Sigma M^T)$,
you get that $\hat{e}_i \sim{N}(0, s^2)$ where
$$\begin{array}{ccl}
s^2 & = & \sigma^2(-b_i^T + \boldsymbol{x}_i^T(X^TX)^{-1}X^T)(-b_i^T + \boldsymbol{x}_i^T(X^TX)^{-1}X^T)^T\\
& = & \sigma^2 (1 - h_{ii})
\end{array}$$
where $h_{ii} = \boldsymbol{x}_i^T(X^TX)\boldsymbol{x}_i$ is the leverage of $\boldsymbol{x}_i$, between 0 and 1.
From that, you can get the moments of the residuals using the moments of the normal distribution.
Getting the joint distribution of the vector of residuals $\hat{\boldsymbol{e}}$ is also possible since $\hat{\boldsymbol{e}} = (I - H)\boldsymbol{\varepsilon}$ where $H = X(X^TX)^{-1}X^T$ is the hat matrix: $\hat{\boldsymbol{e}}$ follows a singular multivariate normal distribution (singular since its variance matrix $(I - H)$ is singular).
Well, its a singular multinormal distribution, so not that tricky ...
Yes, you're right, it's not really tricky.. I edited the answer.
| common-pile/stackexchange_filtered |
Wrong syntax highlight for shell script in vim
I'm new to vim and shell script. I'm not sure if there is a real problem or it is just me not understanding vim or shell script, but I did search through the google and got no answer. Anyway, this is what I got when I doing shell script in vim. And I think the syntax highlight is not working correctly.
filename=$(basename $file)
Vim highlights the $( and ) in red colour.
BTW: I'm using gvim 8.0 on Mac and had YCM installed, if it is relevant.
Sorry, but why exactly you say it is not working? Seems to be working in the image
Hi @sidyll So I'm thinking that I do not having any syntax error in my code But vim did highlight some of my code in red (as shown in the image). Did you mean that I do having a syntax error? My script works fine on my labtop.
To me that's just the way your colorscheme does it :) have you tried another one?
I just checked syntax definition for shell, and in fact the sub commands have the highlight definition inside the Error group. They will thus be displayed formatted that way by default, unless you change your syntax or use a coloscheme less invasive in that particular highlight group. But nothing wrong with your syntax anyway, it's just the default.
This has to do with the behavior of Vim's shell syntax. It has three modes: posix shell, ksh, and bash. You are using bash syntax, but Vim is rendering it as posix shell (the default).
Here is a screenshot of 3 different versions of this code in Vim 8.0.
The top version is just the code you posted in your screenshot. By default, it is using posix shell mode, and you can see that the red highlights are present.
In the middle version, I have added #!/bin/sh to the beginning of the file. This is still in posix mode, and still has the red highlights.
At the bottom, you can see I switched to #!/bin/bash. This triggers the bash behavior, and now you can see the bash-specific syntax is no longer marked as an error.
The #! line is used to auto-detect the file type. However, if it is missing, it is still possible to force the mode, if you wish to.
:let b:is_bash=1
:set ft=sh
Note that the mode is set when the file is opened. So adding #!/bin/bash won't immediately fix the mode. You would need to save/exit the file, and then open it again, to switch to bash mode. (Or use the trick just above this paragraph.)
| common-pile/stackexchange_filtered |
HTML5 video tag not displaying mp4 video in Microsoft Edge - "This type of video file isn't supported"
I have a simple HTML5 video tag in a website.
<video id="myVideo" controls="controls">
<source src="MyVideoPath/MyVideoFileName.mp4" type="video/mp4" />
</video>
It plays the video fine when I use Chrome, Firefox and Internet Explorer, but on Edge the video is black and the text "This type of video file isn't supported" is displayed.
If I navigate directly to the video source on Edge then the video plays perfectly, so I don't think the video's media type is the problem.
What am I missing in my code? Is there some sort of library or plugin I need to reference to display mp4 videos on Edge?
for the video ... can you post a sample? it may be an encoding issue, also check that your server is giving the correct MIME type (can sometimes get funny about that). just as a note you only need controls as it's a boolean (if it's present, they're shown, if not, they don't appear).
@Offbeatmammal HTML5 in HTML serialization can use controls. HTML5 in XML serialization must use controls="controls". Given the use of /> closing tags, this appears to be a fragment of an XML serialization.
| common-pile/stackexchange_filtered |
Can someone provide a scenario where a prepared statement is beneficial for efficiency?
Not for sql injection protection. I am aware of that benefit, but as far as the compiled part and it being more efficient, I cannot find a scenario where it would benefit for efficiency. I was hoping for that here. Vague I know, but I don't know where to ask other than here. Thanks.
One can easily list that benefits of prepared statements
You get rid of compilation overhead
You get rid of the need to prepare an execution plan
Since not statement, but only parameters need to travel through wire, you gain bandwidth.
If you have one statement to work millions of times during a long time-span, all that items are important for efficiency. If it is easy to develop (like stored procedures), it is a win win situation, but...
I have once had to develop a code that directly connects to AS/400 system using "C with Embedded SQL" which you write sql in your C code, give it to the preprocessor to output compilable code and a binder file, then give binder file to the as/400 system to prepare statement. All because they refused to install ODBC support their to server.
It was a pain to write and test that code. It was working very slow, and changing anything would definitely break the system for sure. It was not efficient to write a code like this.
Efficiency depends on variables which varies depending on your point of view.
In my sample, AS/400 guys were happy since they kept they system efficient by not installing some cr.p software on it. Customer was happy, since their method of forcing developers to use inefficient methods to write code was efficient enough to keep it in timeline. It was efficient for network admin since only minimal data is transmitted over network (even no metadata). It was very inefficient for developer since it was time consuming and error-prone. But it was also efficient for same developer to get something that will "look good" on a resume.
You see now?
The scenario is simple: transaction processing.
As Edokan says, preparing a statement eliminates the overhead of compiling the SQL and creating the execution plan. In a more complex query, this overhead is minimal. However, if you are running 100 or 1000 transactions per second, then this overhead can interfere with efficiently using the database.
Of course, the query plan may not be the best, especially when the statistics on the underlying tables change. The characteristics at prepare-time are used to determine the best query plan. These may change over time, and a different query plan might become better. This is more of an issue for more complex queries. Since these typically take longer to run, so the compile overhead is less of an issue.
| common-pile/stackexchange_filtered |
Calculated Redoxpotential is too far away from experimental value
I calculated the redox potential with Gaussian for hydroquinone with different combinations of functional/basis sets always values like 5.4V (B3LYP/6-311G+(2d,p) and SMD model). The experimental value is about 1.1V according to [1], so I'm missing by a decent amount.
Has somebody an idea what I did wrong?
These are the energies I calculated:
SCFE (g) (molecule) = -382.81331295
SCFE (solv) (molecule) = -382.82970187
GibbsCorr (molecule) = 0.077174
SCFE (g) (species) = -382.53186782
SCFE (solv) (species) = -382.63171676
GibbsCorr (species) = 0.078470
and an example job file for the optimization of the charged species:
%rwf=bench_40_spec_b3lyp_tight.rwf
%NoSave
%chk=bench_40_spec_b3lyp_tight.chk
#p opt=(calcfc,tight,recalcfc=3) b3lyp/6-311+g(2d,p) nosymm scf=qc
040 Tight Opt Gas
1 2
C -0.68613672 -1.20444633 -0.00000200
C 0.69506215 -1.19541581 -0.00000235
C 1.39161904 0.00718044 0.00000031
C 0.68613843 1.20444943 -0.00000167
C -0.69505913 1.19541474 -0.00000053
C -1.39161802 -0.00718091 0.00000159
O -2.75490670 -0.05822072 -0.00000096
H -3.11159203 0.83776787 0.00004645
H -1.23719750 2.13172433 -0.00000924
H 1.23422725 2.13274296 -0.00001200
O 2.75490286 0.05821954 0.00000081
H 3.11158561 -0.83777105 0.00003365
H 1.23719782 -2.13172346 -0.00000066
H -1.23422866 -2.13274050 -0.00000041
I used the method linked in here:
Redox Method
References:
Neugebauer, H.; Bohle, F.; Bursch, M.; Hansen, A.; Grimme, S. Benchmark Study of Electrochemical Redox Potentials Calculated with Semiempirical and DFT Methods. J. Phys. Chem. A 2020, 124 (35), 7166–7176. DOI: 10.1021/acs.jpca.0c05052.
It would be helpful to know what you specifically you got for the potential using the energies in the question. One thing to note is the linked paper subtracts the potential for a reference electrode to obtain its results. I can't find in the paper what value that should have, but it may make up for most of the discrepancy. Wikipedia has an estimate of 4.44V for the absolute potential of the standard hydrogen electrode.
I got 5.4V, edited in the post.
Your reference paper says that it subtracts the "absolute potential of the reference electrode" from the calculated values. I can't get to the citation that explains what reference electrode they are referring to, but the most common is the Standard hydrogen electrode, which is estimated to have an absolute potential of $\pu{4.44V}$.
Subtracting this from the potential of $\pu{5.4V}$ that you calculated gives $\pu{0.96V}$. This is only off by ~$\pu{0.1V}$, which is well in line with the errors reported in the paper for DFT and semiempirical methods.
Thank you very much for your support! Do you got an idea why Grimme et al. subtract die reference electrode and the paper from yale university (linked in the other thread) do not need to be?
@Andrea I wonder why you clicked "accept" but didn't issue a vote to the question? See this.
@Andrea I think the tutorial is wrong. Ferrocene (the molecule considered) should have a potential of 0.4 V vs the standard hydrogen electrode (SHE). Even adding back in the absolute potential, it's much too small to match the 5.52 V they find. The experimental reference they mention doesn't seem to list the value of 5.3 V anywhere, just the 0.4 V against the SHE.
| common-pile/stackexchange_filtered |
Using session variables in php
I have 2 pages: index.php (where I input brand name in a textbox and on clicking submit I need to view the brands I added in drop down box in same page) and product page (where I can edit the brands I select in the index page).
I am not using database, instead I'm trying to store value in session variable. I need to know how I can use dynamic session variable so that each time a new brand would be added to drop down menu...
index.php
<body><div>
<form name="brand" method="post" action="brand_action.php">
Brand Name: <input type="text" name="brand" id="brand"><br /><br />
<input type="submit" value="Submit">
</form>
</div>
<div>
<?PHP
if(isset($_SESSION["bname"]))
{?>
<form name="add" action="product.php" method="post">
Brands :<select name="brand" id="brand">
<?PHP
$a=$_SESSION["bname"];
?>
<option value="<?PHP echo($a);?>"> <?PHP echo($a);?> </option>
</select>
<input type="submit" name="Edit" value="EDIT" />
</form>
<?PHP
}
?>
</div>
</body>
In the index_action.php page,I'm thinking to push each brand into an array and store in session variable and call it in index.php page and put it in drop down list.How can I do it?
Please show some code.
Yup, going to need a little code here to help ya out.
why don't you just do this: $_SESSION["brands"][]=$_POST["brand"]
Well you can make a session variable act as an array. Store all the brand names in that array, then loop through it.
Here's an example.
<?php
session_start();
if(!isset($_POST['brand']))
{
$_SESSION['bname'] = array();
}
else
{
$_SESSION['bname'][] = $_POST['brand'];
}
?>
<body><div>
<form name="brand" method="post" action="s.php">
Brand Name: <input type="text" name="brand" id="brand"><br /><br />
<input type="submit" value="Submit">
</form>
</div>
<div>
<?PHP
if(isset($_SESSION["bname"]))
{?>
<form name="add" action="product.php" method="post">
Brands :
<select name="brand" id="brand">
<?php
foreach($_SESSION['bname'] as $brand_name)
{
?>
<option value="<?PHP echo($brand_name);?>"> <?PHP echo($brand_name);?> </option>
<?php
}
?>
</select>
<input type="submit" name="Edit" value="EDIT" />
</form>
<?PHP
}
?>
</div>
</body>
Also remember, session_start should always be the first line of the page in which you need to use sessions.
Thanks..it works...Could you explain the code.......
Well we had to use a session variable as an array. If I defined it in a normal manner, then whenever the form is submitted, it will overwrite all the values of the session array. Therefore, in order to make $_SESSION['bname'] as array, I implemented above. Because only for one time $_POST['brand'] will not be set.
| common-pile/stackexchange_filtered |
finding a pair with given sum in BST
struct node
{
int val;
struct node *left, *right;
};
// Stack type
struct Stack
{
int size;
int top;
struct node* *array;
};
struct Stack* createStack(int size)
{
struct Stack* stack =
(struct Stack*) malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->array =
(struct node**) malloc(stack->size * sizeof(struct node*));
return stack;
}
What does this statement do?
stack->array =
(struct node**) malloc(stack->size * sizeof(struct node*));
What will be the memory representation of it?
Please see this discussion on why not to cast the return value of malloc() and family in C..
http://linux.die.net/man/3/malloc let us know what is unclear in it.
stack->array =
(struct node**) malloc(stack->size * sizeof(struct node*));
struct node** returns a pointer to a pointer (to the stack)
stack->size is the amount of items of the stack
sizeof(struct node*) is the size of a pointer to a node.
So it creates an array of pointers, where each pointer points to one element within the stack.
so i guess this wiil be like :-
The above statement allocates space for an array of struct node *, i.e. pointers to struct node.
Each pointer in this array can then point to an instance of struct node.
| common-pile/stackexchange_filtered |
How do you use approx() inside of mutate_at()?
I'm having issues getting approx() to work inside of a mutate_at(). I did manage to get what I want using a very long mutate() function, but for future reference I was wondering if there was a more graceful and less copy-pasting mutate_at() way to do this.
The overarching problem is merging a dataset with data from 1 year intervals to one with 3 year intervals, and interpolating years with no data in the dataset with 3 year intervals. There are missing values in between the years, and one year that requires some form of extrapolation.
library("tidyverse")
demodf <- data.frame(groupvar = letters[rep(1:15, each = 6)],
timevar = c(2000, 2003, 2006, 2009, 2012, 2015),
x1 = runif(n = 90, min = 0, max = 3),
x2 = runif(n = 90, min = -1, max = 4),
x3 = runif(n = 90, min = 1, max = 12),
x4 = runif(n = 90, min = 0, max = 30),
x5 = runif(n = 90, min = -2, max = 5),
x6 = runif(n = 90, min = 20, max = 50),
x7 = runif(n = 90, min = 1, max = 37),
x8 = runif(n = 90, min = 0.3, max = 0.5))
demotbl <- tbl_df(demodf)
masterdf <- data.frame(groupvar = letters[rep(1:15, each = 17)],
timevar = 2000:2016,
z1 = runif(n = 255, min = 0, max = 1E6))
mastertbl <- tbl_df(masterdf)
joineddemotbls <- mastertbl %>% left_join(demotbl, by = c("groupvar", "timevar"))
View(joineddemotbls)
joineddemotblswithinterpolation <- joineddemotbls %>% group_by(groupvar) %>%
mutate(x1i = approx(timevar, x1, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x2i = approx(timevar, x2, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x3i = approx(timevar, x3, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x4i = approx(timevar, x4, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x5i = approx(timevar, x5, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x6i = approx(timevar, x6, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x7i = approx(timevar, x7, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]],
x8i = approx(timevar, x8, timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]])
View(joineddemotblswithinterpolation)
# this is what I want
That works pretty well. But I've tried all these mutate_at() variants and have not gotten them to work. I am sure there is an error in the syntax somewhere...
joineddemotblswithinterpolation2 <- joineddemotblswithinterpolation %>% group_by(groupvar) %>%
mutate_at(vars(x1, x2, x3, x4, x5, x6, x7, x8), approx(timevar, ., timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]])
# error
joineddemotblswithinterpolation2 <- joineddemotblswithinterpolation %>% group_by(groupvar) %>%
mutate_at(vars(x1, x2, x3, x4, x5, x6, x7, x8), approxfun(timevar, ., timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]])
# error
joineddemotblswithinterpolation2 <- joineddemotblswithinterpolation %>% group_by(groupvar) %>%
mutate_at(vars(x1, x2, x3, x4, x5, x6, x7, x8), funs(approxfun(timevar, ., timevar, rule = 2, f = 0, ties = mean, method = "linear")[["y"]]))
# error
joineddemotblswithinterpolation2 <- joineddemotblswithinterpolation %>% group_by(groupvar) %>%
mutate_at(vars(x1, x2, x3, x4, x5, x6, x7, x8), funs(approxfun(timevar, ., rule = 2, f = 0, ties = mean, method = "linear")[["y"]]))
I even tried na.approx(), but also to no avail...
library("zoo")
joineddemotblswithinterpolation2 <- joineddemotblswithinterpolation %>% group_by(groupvar) %>%
mutate_at(vars(x1, x2, x3, x4, x5, x6, x7, x8), na.approx(., timevar, na.rm = FALSE))
I've kind of constructed these different trials from the following related questions:
Using approx in dplyr
Linear Interpolation using dplyr
Using approx() with groups in dplyr
linear interpolation with dplyr but skipping groups with all missing values
R: Interpolation of NAs by group
Thanks for any help!
You're very close. This works for me:
joineddemotblswithinterpolation <- joineddemotbls %>%
group_by(groupvar) %>%
mutate_at(vars(starts_with("x")), # easier than listing each column separately
funs("i" = approx(timevar, ., timevar, rule = 2, f = 0, ties = mean,
method = "linear")[["y"]]))
This will create columns x1_i, x2_i etc. with the interpolated values.
Beautiful! Thank you!
| common-pile/stackexchange_filtered |
jest mocking functions without passing as a callback
I have some code like:
module.exports = {
idCheck: function(errors) {
errors.some( (error) => {
if (error.parentSchema.regexp === '/^((?!\\bMyId\\b).)*$/i') {
this._recordError('IDCHECK');
}
});
}
};
I am trying to test it using jest with this:
const IDCheck = require(
'./IDCheck'
);
let errors = [
{
parentSchema: {
regexp: '/^((?!\\bMyId\\b).)*$/i'
}
}
];
describe('IDCheck', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('calls _recordError with IDCHECK', () => {
jest.spyOn(this, '_recordError');
IDCheck.idCheck(errors);
});
});
however, when running jest, I get
Cannot spy the _recordError property because it is not a function; undefined given instead
Is there a way of mocking, testing for _recordError() having been called, or not called and with the correct parameter, without passing _recordError through as a parameter?
I think it should be jest.spyOn(IDCheck, '_recordError')
Nope, that gives the same error.
A few things about this line: jest.spyOn(this, '_recordError');
this has to be IDCheck because there is no this in scope since you are using arrow functions that inherit this if previously set (which it isn't). You can console.log(this) right above the line to prove that point.
'_recordError' is not a method of IDCheck. spyOn checks the target's methods, not methods called within it. Now if _recordError is a method of IDCheck, then you should be ok.
Finally, you basically have to return the data you want in order to verify it. There's no real way to check what was passed unless you return it.
Here's a solution I came up with that does not include some fixes you'd have to implement to fix the potential workflow flaws.
const IDCheck = {
idCheck: function(errors) {
return errors.map(error => {
if (error.parentSchema.regexp === '/^((?!\\bMyId\\b).)*$/i') {
return this._recordError('IDCHECK')
}
})
},
_recordError: function(data) {
return data
}
}
let errors = [
{
parentSchema: {
regexp: '/^((?!\\bMyId\\b).)*$/i'
}
}
];
describe('IDCheck', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('calls _recordError with IDCHECK', () => {
const spy = jest.spyOn(IDCheck, '_recordError')
const check = IDCheck.idCheck(errors).includes('IDCHECK')
expect(spy).toHaveBeenCalled()
expect(check).toBe(true)
});
});
Cheers @ReyHaynes. Out of interest, i'm still fairly new to JS, so would you say the structure of my code is poor or that the tooling for testing is still up and coming?
| common-pile/stackexchange_filtered |
Can I ask a question about bicycle culture in the Southwest?
I am an avid bicyclist who is new to the Texas/Southwestern United States area. I am wondering if its okay to ask questions about bicycle culture in this forum?
I have tried to do so in the travel stack exchange forum, but I find that bicycle culture seems to be as heated as politics for some reason.
At the end of the day, I am just looking for a bicycle community in the Southwest similar to what you see in Philadelphia and Seattle and if anyone can help me figure out whether it is okay to ask it here, I would appreciate it.
Well its certainly on-topic as far as cycling content, but its also highly location-specific.
Assuming Southwest means nevada, arizona, utah, new mexico, etc, then my perception as an overseas foreigner is they're all highly car-focused societies. California's the odd one out because of the anti-pollution focus of local/state laws, which in theory should boost cycling.
tl:dr go on, ask. The worst case is no useful answers are forthcoming.
I don't think this is suitable for Stack Exchange at all.
It's too broad: Arizona, Colorado, Nevada, New Mexico and Utah between them cover an area about half the size of the European Union; add California and it gets another 20% bigger.
What is or is not a "bicycle community... similar to what you see in Philadelphia and Seattle" is purely a matter of opinion. As such, it's likely to generate discussion and argument.
It's inviting lists rather than answers.
Agree with the issue of what a 'bicycle community' actually is. Without a definition there can't be objective answers. OP may have better luck looking for published statistics on bicycle usage in different metro areas.
| common-pile/stackexchange_filtered |
Which is the custom, by-the-book way to get user local time / time zone? (Or: How might Google / Facebook do it?)
I know this has been asked here several times, but the 'by-the-book' custom way to do it still remains unclear to me.
I'm designing an app which requires knowing the exact user's local-time.
I got really confused while researching this:
Most experienced SO users recommend just asking the user for her timezone. Others recommend the Javascript timezone offset method. Another approach is to use geolocation.
Facebook posts and Gmail mails, for example, shows the exact local time, regarding DST and everything. I was never asked for my timezone by these applications. Which method might they use?
Or, among the above and other methods, which method is the custom, 'by the book' way to be able to use and store the user's local-time?
Asking for their timezone is a little weird, geolocation is the best as far as user experience. You can pick up their location, and therefore, timezone on page load within PHP.
In my opinion the best way is to ask the user to select their own timezone.
I always use geo-location to get the starting point, then ask the user to confirm which they require.
This allows the user the option of a quick, 'click to confirm' option, but still allows the user to change it if it isn't correct. Which is great for allowing for the fact that a user may be signing up/in from a location that isn't their own timezone, but they wish to se times/dates as though they were in their time zone.
This may not be the 'by the book' way, but I feel it gives the best user experience, which at the end of the day should always be the main priority!
I have explicitly told Google what my timezone is, because my computer and I move around a lot, and I actually want two timezones, not just one (for Google Calendar). So I like that option. I think attempting to default to some reasonable guess using geolocation or similar might be better than just always assuming US EST or whatever, but once you've done it, consider storing the result for future use until the user explicitly changes it. It could be disorienting if it changes just because the user plugged in to a network that has bad geolocation (these do exist).
| common-pile/stackexchange_filtered |
iPhone SDK Copy File to Main System
Many thanks to @fabkk2002 who helped me adjust the Helvetica font on my iPhone to fully support Indic glyphs and rendering on my iPhone for an app I am creating. This leaves me with another problem. Now that I have adjusted the font on my phone, how will my users get the full support for the Indic font as well? I do not want to require them to jailbreak their phones and install the font to get the most out of the app because the iPhone doesn't ship with the proper font. I was thinking something along the lines of putting the font in the resource bundle of my app and have it copied to /System/Library/Fonts/Cache folder on the first launch, but I do not think this is possible with iPhone SDK. Will I have to use undocumented APIs and hope that Apple overlooks it when they are reviewing my app? Are there any good alternatives such as fooling my app into thinking the font in my resource bundle is located /System/Library/Fonts/Cache? What would be the best way to do this (with or without Undocumented APIs)?
EDIT:
I was thinking something like this, except I doubt it will work.
NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"Helvetica" ofType:@"ttf"];
[[NSFileManager defaultManager] copyItemAtPath:fontPath toPath:@"/System/Library/Fonts/Cache/"];
Custom fonts are actually supported without any hacks. Take a look at this code sample.
Code like this will not work with my project. While it does work with unicode characters, the Indic unicode characters I am using do not render properly because the code doesn't support TrueType or AAT tables. I feel that if I got something working like I suggested above, it would work.
| common-pile/stackexchange_filtered |
Where are text files in my Xcode project?
I've created a simple program to write in a text file, and it seems as if it works. I just cannot find where to locate the text file it created in my Xcode project.
FILE *fptr;
fptr= fopen("testawesome.txt", "w");
fputs("I love programming!", fptr);
fclose(fptr);
return(0);
}
I believe the code is fine, I just can't find exactly where the text file is. When I search in finder for testawesome.txt, it just references my project and not the text I want it to create.
You haven't tested that the file was opened successfully; you should always do that.
See Change the working directory in Xcode
| common-pile/stackexchange_filtered |
How to make an undirected and unweighted graph in the shape of a grid in C++
I'm trying to implement a for loop to initialize a graph in the shape of a grid, including diagonals. Basically, I have an array that is initialized with values that I want to replicate in the graph. So I have a nested for-loop that has several if statements. The if statements are used to handle the special cases i.e element at index 1,1 only has 3 neighbors.
I know my graph function works because if I initialize it by hand, it doesn't seg fault and prints the proper BFS, however my loop seg faults. Please take a look:
Graph Class:
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s, int d)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
int trail[V];
for(int i = 0; i < V; i++){
visited[i] = false;
trail[i] = -1;
}
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
if(s == d){
break;
}
else
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
trail[*i] = s;
}
}
}
int x = d;
while(x != -1){
cout<<x<<endl;
x = trail[x];
}
}
In main program:
int num = 2;
int arr[num+1][num+1];
int x = 1;
for(int i = 1; i<=num; i++){
for(int j = 1; j<= num; j++){
arr[i][j] = x;
cout<<x<<" ";
x++;
}
cout<<endl;
}
int max = 2;
Graph g(max+1);
for(int row = 1; row <= max; row++){
for(int col = 1; col <= max; col++){
if(row == 1 && col == 1){
g.addEdge(arr[row][col],(arr[row][col] +1));
g.addEdge(arr[row][col],(arr[row][col] +max));
g.addEdge(arr[row][col],(arr[row][col] + max+1));
}
else if(row ==1 && col == max){
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]+max));
g.addEdge(arr[row][col],(arr[row][col]+max-1));
}
else if(row == max && col == max){
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]-max-1));
}
else if(row == max && col == 1){
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]-max+1));
g.addEdge(arr[row][col],(arr[row][col]+1));
}
else if(row == max){
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]+1));
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]-max-1));
g.addEdge(arr[row][col],(arr[row][col]-max+1));
}
else if(col == max){
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]+max));
g.addEdge(arr[row][col],(arr[row][col]-max-1));
g.addEdge(arr[row][col],(arr[row][col]+max-1));
}
else if(col == 1){
g.addEdge(arr[row][col],(arr[row][col]+1));
g.addEdge(arr[row][col],(arr[row][col]+max));
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]-max+1));
g.addEdge(arr[row][col],(arr[row][col]+max+1));
}
else if(row == 1){
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]+1));
g.addEdge(arr[row][col],(arr[row][col]+max));
g.addEdge(arr[row][col],(arr[row][col]+max-1));
g.addEdge(arr[row][col],(arr[row][col]+max+1));
}
else{
g.addEdge(arr[row][col],(arr[row][col]+1));
g.addEdge(arr[row][col],(arr[row][col]-1));
g.addEdge(arr[row][col],(arr[row][col]+max));
g.addEdge(arr[row][col],(arr[row][col]-max));
g.addEdge(arr[row][col],(arr[row][col]-max-1));
g.addEdge(arr[row][col],(arr[row][col]-max+1));
g.addEdge(arr[row][col],(arr[row][col]+max-1));
g.addEdge(arr[row][col],(arr[row][col]+max+1));
}
}
}
Note: I wanted my graph vertices to start at 1 but not at 0. This is why my matrix has an extra row and column in it. Also, my graph requires an edge to be added in both directions, so it would be 1--->0 and 0--->1.
It appears that your constructor only allocates N adjacency lists, but you then define N×N nodes. You call addEdge() with each of these nodes as its first argument, which when you get to node N+1, tries to write past the end of adj and causes a buffer overflow.
To catch this kind of bug in the future, you can define adj as a std::vector, which comes with bounds checking. This will do all the work of making it possible to add nodes for you, and also fix the memory leak caused by the absence of a destructor that deletes arr. If for some reason you can’t use std::vector or std::array, my advice would be to at least manually bounds-check with a line such as assert(v < V); in Graph::addEdge().
| common-pile/stackexchange_filtered |
C# UWP Live Charts Create CartesianChart dynamically in a Windows Runtime Application
I am trying to create a CartesianChart dynamically in a Windows Runtime Application.
The code:
CartesianChart ch = new CartesianChart
{
Series = new SeriesCollection
{
new LineSeries
{
Title = "",
Values = new ChartValues<double> { 1, 1, 2, 3 ,5 }
}
}
};
The error message:
The text associated with this error code could not be found.
Cannot deserialize XBF metadata type list as 'OrientationConverter' was not found in namespace 'LiveCharts.Uwp'. [Line: 0 Position: 0]
Can anyone give me an advice in this case, please?
| common-pile/stackexchange_filtered |
In Go, is it possible to perform type conversions on the multiple return values of a function?
type Node int
node, err := strconv.Atoi(num)
Foo(Node(node)) // Foo takes a Node, not an int
Is it possible to avoid the ugly "Node(node)" in the above example? Is there a more idiomatic way to force the compiler to consider node a Node and not an int?
Nothing really elegant. You could define an intermediate variable
n, err := strconv.Atoi(num)
node := Node(n)
or you could define a wrapper function
func parseNode(s string) Node {
n, err := strconv.Atoi(num)
return Node(n)
}
but I don't think there are any one-line tricks. The way you are doing it seems fine. There is still a little stuttering here and there in Go.
I think the wrapper function above would not compile b/c of unused err.
Right, but the original example isn't a complete working example either. There is obviously stuff left out both places.
No. Conversion converts an (convertible) expression. Return value of a function is a term (and thus possibly a convertible expression) iff the function has exactly one return value. Additional restrictions on the expression eligible for conversion can be found here.
| common-pile/stackexchange_filtered |
Solve the memory management problems by proving program correctness like with coq?
I just wanted to ask if it would be possible to construct a language with a type system that can solve the memory management problems (memory leaks, dangling pointers, double free(), etc.) by automatically trying to prove the correctness of any program with its types as propositions like with an integrated coq-like theorem prover (in the mindset of programs as proofs)?
Is there a fundamental logical problem to this approach (halting problem maybe?) or is it just unfeasible? Thanks for any answers and I'm sorry that I'm not so well-versed in this field, just want to know out of curiosity ;)
Yes, by never allowing programmers direct access to pointers. A similar thing is done in Linux with the ln command. Regular users cannot use it to link directories. Directories can only be made with the mkdir command. This prevents memory-management problems of the file system.
Yes, there has been a lot of research into languages that do compile-time memory management. Rust and its ownership model is the most high profile industry language in this area. You might always want to look into "linear types".
But is there a way to completely remove the responsibility from the programmer while solving the problem compile-time? As I have heard, fighting with the borrow checker in Rust can be quite exhausting. And linear type systems seem to me a bit limited, for example persistent data structures would be impossible.
| common-pile/stackexchange_filtered |
Can't Integrate youtube to fragment
youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
Unreachable statement:
public class TabFragment2 extends Fragment {
private FragmentActivity myContext;
YouTubePlayerSupportFragment youTubePlayerFragment;
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "xyz";
private static final int RECOVERY_DIALOG_REQUEST = 1;
@Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab_fragment2, container, false);
youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize("AIzaS", new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
YPlayer = youTubePlayer;
YPlayer.setFullscreen(true);
YPlayer.loadVideo("2zNSgSzhBfM");
YPlayer.play();
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
}
}
Hi sanchit. You won't ever get to the mentioned line of your onCreateView function because you are returning inflater.inflate(R.layout.fragment_tab_fragment2, container, false); right at the beginning. When you return something from a function, it exits the function.
change your code like below. You have return statement before everything, so it is saying unreachable code.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_fragment2, container, false);
youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize("AIzaS", new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
YPlayer = youTubePlayer;
YPlayer.setFullscreen(true);
YPlayer.loadVideo("2zNSgSzhBfM");
YPlayer.play();
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
}
return view;
}
Hope it helps!!! Just check these things while you code else these silly mistakes will take your valuable time ;)
| common-pile/stackexchange_filtered |
Access SQL by server name in different segment
I have 2 server, that is server A and server B and both are currently using SQL Server 2016.Server A is in 192.168.10.xxx network and I can connect to it via IP address from server B but not via server name because it is in different network.
And server B is in 192.168.2.xxx network and I also can connect to it via IP address from server A but not via server name because it is in different network.
I want to create a peer to peer replication for server A and server B.
But I can't, because to add a new node in the Configure Peer-To-Peer Topology it must specify a server name, not the IP address of the server.
This is the error that I get when specifying the IP address of the server when adding another peer node in configure peer-to-peer topology.
SQL Server replication requires the actual server name to make a connection to the server. Specify the actual server name, ''. (Replication.Utilities)
This is the error that I get when specifying the server name of the server when adding another peer node in configure peer-to-peer topology.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)
How do I solve this?
Try to use the same DNS for both servers or define both of the server names in the hosts files on both servers i.e edit C:\WINDOWS\SYSTEM32\DRIVERS\ETC\HOSTS on both servers and add two entries for both machines.
@AhmedSaeed What should I do and add in the host files on both servers? Sorry I'm new at this.
This might be helpfull:https://dba.stackexchange.com/questions/52662/is-replication-possible-on-two-different-domains
Add two lines, 192.168.10.xx serverAName and on the next line add 192.168.2.xx ServerBName. insure to put the correct IP of both servers on both.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.