INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Compressing files to to make iOS app smaller I recently completed a game that I uploaded to iTunes connect. It's currently in the app store but is a whopping 264mb. I didn't even realize how big it was until trying to download it on a device. I take it this is too large to be a successful app but there really weren't any more pictures than any other normal iOS game app, probably less. If I want to go about compressing them, what's the easiest way? Should I upload them one by one to Gimp or something of the sort or is there some sort of automatic file compressor for iOS apps? I know it's out on a limb but obviously would save a lot of time. Also, once that's done where can I check the size of the app? Thanks for the help.
You can use tools like ImageOptim to batch compress all your images without loosing quality: < For estimating the App Store size, check out this post: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, compression, image compression" }
Developing on a local Java server with Netbeans I've been developing Java with Netbeans and have been using the "Run" command on my project to initialize my testing. I'm using Windows 7. Is it possible for me to run a Java server isolated from Netbeans and use it for my testing so I can learn the basics of a Java server not tied to Netbeans? If so, what should I google?
**The simplest server to start with is Jetty** , as it's 100% java and embedded easily with no platform specific dependencies. To install jetty, you need only unzip the download. Once you run a simple jetty tutorial, **use netbeans to create a war file** \- and you can then easily deploy your web application in jetty by just dragging the war to the appropriate folder in jettys home directory. Now --- To learn about how java web servers work , you can read the terminal logs that jetty produces, which are quite informative** - you can watch as it decompresses and deploys your .war file, etc... And use any old java profilers to monitor its memory/cpu usage.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "java, java ee 6" }
Sending command on serial port using c# I have a little application that sends a command over a serial port and write the response in a label. If I send a ENTER character inputData = "\r\n\"; port.Write(Encoding.ASCII.GetBytes(inputData), 0, 1); the response is the last string that was generated by the device I communicate with. If I send something like inputData = "S1\r\n"; port.Write(Encoding.ASCII.GetBytes(inputData), 0, 1); the label stays empty. The second command is the one that I need to send and in Putty terminal works well. Is there a way to send the same thing via port.Write?
The Write method definition is void Write(byte[] buffer, int offset, int count); In your second example you are only sending the character 'S' - you are not sending the remainder of the string. The third parameter is the number of characters in the string to send (the second is the start offset). Maybe modify your code allong the lines of var buffer = Encoding.ASCII.GetBytes(inputData); port.Write(buffer, 0, buffer.Length); The fact the first example worked probably indicates that all you need to send is '\r' & the '\n' is not required.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, serial port" }
Count number of writes to different tables I have recently setup Continuous Archiving for Point-in-Time Recovery in a postgresql DB, but the archive is growing at an unexpectedly high pace (tens of gigabytes per day). The DB is a couple of GB, most of it static. It seems to me that we may have some part of the application which is writing a bit too aggressively to the database, possibly updating large number of rows frequently, causing needless diskload. Is there some way to either ask the DB, or to analyze the WAL files, to find out which tables most writes (row delete, add or updates) are made to, preferably counted in bytes? That would be a big help in figuring out the source of the disk load.
This information is available through the Statistics Collector. The information you are looking for is stored in pg_stat_bgwriter or pg_stat_database. Maybe you are also interested in the values from pg_stat_all_tables that shows how many tuples have been inserted, updated or deleted. Pay attention to the configuration properties listed in the section Statistics Collection Configuration All those views show values since the instances has been started or since the last time `pg_stat_reset()` has been called. If you want to monitor the change over time, you need to sample those views and store the values somewhere (e.g. a text file or just another table that has a timestamp to indicate when the sample was taken).
stackexchange-dba
{ "answer_score": 3, "question_score": 1, "tags": "postgresql, performance, disk space, postgresql 9.5, postgresql performance" }
Column total as an observation in a dataset in SAS I need a column a total as an observation. Input Dataset Output Dataset ------------- -------------- data input; Name Mark input name$ mark; a 10 datalines; b 20 a 10 c 30 b 20 Total 60 c 30 ; run; The below code which I wrote is working fine. data output; set input end=eof; tot + mark; if eof then do; output; name = 'Total'; mark = tot; output; end; else output; run; Please suggest if there is any better way of doing this.
Your code is fine in general, however the issue might be in terms of performance. If the input table is huge, you end up rewriting full table. I'd suggest something like this: proc sql; delete from input where name = 'Total'; create table total as select 'Total' as name length=8, sum(mark) as mark from input ; quit; proc append base=input data=total; run; Here you are reading full table but writing only a single row to existing table.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sas" }
the blue screen in android studio disappeared please help im new to android studio and from the two screens for layout the blue one on the left disappeared my API version is 30this is the picture from my window
I'm guessing what you're looking for is the `Blueprint` Design Surface. Your currently viewing the `Basic` Design Surface. You can toggle between `Basic`, `Blueprint` and both by either pressing the **B** key, or by clicking on the **Select Design Surface** button - it looks like a blue diamond stacked on-top of another blue diamond . (I've circled it in the image you provided) ![Select Design Surface Button](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "android studio" }
Javascript Regex to ignore first character in match I need to ignore a '.' at the start of my regular expression, and have been somewhat stumped. My current regex is: (?::)(\d{3}) Which matches the following: !Image here When I try to ignore the '.' with the following regex: ^.(\d{3}) I get this: !Picture here As it seems to be adding the extra character like '<', which is unwanted. How do I go about to ignore that extra character in front of the ':' ?
Use this alternation based regex: \.:\d{3}|:(\d{3}) And grab captured group #1 for your matches. ### RegEx Demo
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "javascript, regex" }
How can I get the upstream repository of a cloned repository? Say someone clones repository A which results in repository B and then I clone repository B, is there a way to determine what the upstream repository (i.e. repository A) is? I know that github shows the 'forked from blah/blah' but I'm not using github for this project. The reason I ask is that I'd like to get all the changes that the person made in a single diff file. In subversion I could just do `svn log --stop-on-copy` to get the first commit and then `svn diff -rXXXX:HEAD` where XXXX is the first revision of the branch to get a diff with all the changes. I know that branching and cloning aren't quite the same thing but I wanted to provide what I was after ultimately. Doing a diff on the upstream repo and the cloned repo seemed the way to go but I might be wrong. Thanks in advance.
Simply, no. The 'upstream' repository (if a repository even has a single upstream) is determined only by a repository's config settings and even these could in theory be inaccurate if the upstream maintainer just does explicit fetches from different repositories, ignoring the configured default. If you have shell (or file system) access to the remote repository then you can query the `config` file or output of `git config` (try remote.origin.url) but otherwise it's not part of the standard 'upload pack' protocol. Even without knowledge of the remote repository you may be able to figure out what commits a particular set of authors/commiters have made by using `git log --author` or `git log --committer` on the fetched branches.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "git" }
MarketingCloud MobilePush SDK 6.3.5 dependency cannot be resolved Our Android project is currently using the 6.3.4 SDK. However when trying to update to the latest version 6.3.5 we get an error: Could not find com.salesforce.marketingcloud:marketingcloudsdk:6.3.5. Searched in the following locations: - - - - - - Is it supposed to be available already?
You need to update your repo in your dependencies. See < for details. ![enter image description here](
stackexchange-salesforce
{ "answer_score": 1, "question_score": 1, "tags": "marketing cloud, mobilepush android" }
I can't understand some instructions in ARM: SBC, RSC I don't understand `SBC` and `RSC` ARM instructions I know that both deal with the carry flag (C) I think it makes sense adding the result with the carry (`ADC`) like: ADC r1, r2, r3 @ r1 = r2 + r3 + Carry But subtracting/reverse subtracting with the carry... I can't understand what is happening :( Can you guys give me an example using `SBC` and `RSC`?
Given two's complement, subtraction can just be transformed into addition: z = y - x = y + (-x) = y + ~x + 1 which makes it easier to consider how the carry flag is _set_ in that situation, i.e. by `subs`: z = 0 - 0 = 0 + ffffffff + 1 C:z = 1:00000000 // no borrow, C = 1 z = 0 - 1 = 0 + fffffffe + 1 C:z = 0:ffffffff // borrow, C = 0 Hence why the value of the C flag is nB ("not borrow"), so `sbc` as "subtract with carry" means "subtract with not borrow", or in other words: z = y + ~x + C // i.e. adc with the second operand inverted = y - (x - 1) - (~C + 1) = y - x - ~C
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "assembly, arm, instructions, carryflag" }
If I carry a lot of money from Germany to Spain, what can go wrong? Currently I have a bank account at Deutsche Bank with approximately 30k€ I have collected working and saving money. I want to move all this money to my Spanish bank account. I have already phoned them asking if I can make the transaction directly and they told me they will take 5% of the total money as commission or 1500€. After knowing this, I think I prefer to move my money by myself, so I will take 1 trip to Spain (if it's possible to do in one) with my money on hand and then put it in my Spanish bank account. **Question:** Do I need to pay extra taxes? Is there something I have not noticed that can go wrong doing this?
I'd worry about being robbed or losing the money en-route. Is it likely? Probably not. But wow, I wouldn't want to lose serious money in one shot. I have fond memories of the time I was serving as treasurer for a non-profit organization and I was taking $30,000 in contributions to the bank. As I walked across the parking lot with all that money in my brief case, I thought, I would really hate to be robbed right now. When I've moved long distances in the past, I've simply written myself a check from my old account and then deposited that amount to my new account. These days I presume I'd do an electronic transfer. I live in the US so I don't know what the conventions are in Europe, but around here, 5% would be an outrageous fee. I once paid $20 for an electronic transfer of around $3,000, and I considered that an excessive fee. I can understand the bank charging a few bucks, but. I'd check around if there are not other banks with more reasonable fees.
stackexchange-money
{ "answer_score": 10, "question_score": 6, "tags": "money transfer, european union, germany, spain" }
copy Linux server from one box to another > **Possible Duplicate:** > Clone a working Linux server We have a Linux CentOS server set up to server a php/mysql web application. We would like to move this to a new larger server. It appears the best way to do this is to run the CentOS setup on the new machine and then copy over certain configuration and application files. Is this best approach? Also, if so, what directories or files on the new box should not be over-written.
1. Install CentOS latest available (5.6) on new server 2. Compile Apache, php, mysql etc [make sure that all modules compiled in old server also in new server] 3. Copy all document root folders and files in same structure. 4. rsync all MySQL files or take dump and restore it in new server. [if your old server have MySQL 4.x then you should install same version of MySQL on new server too.] 5. Recreate Apache configuration files
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "linux, centos, hardware, migration" }
Is there a good reason for using AUROC on imbalanced dataset? So I just learned about AUROC. When I read this thread, it seems like AUROC is not a great metric for imbalanced dataset. One answer even says it shouldn't be used to compare models. However, I am confused because research papers use AUROC to test models for MIMIC-III code prediction, which is a highly imbalanced dataset. The papers doesn't clearly explain why they picked such metric. My questions are 1. Why do you think the authors picked AUROC? Is there an pro for using it that I am unaware of? 2. Should the SOTA model be MSMN(Highest AUROC) or RAC(Highest F1)? This is confusing because the site is sorted by AUROC on default.
The AUROC, better understood as the concordance probability between predicted and observed values, has no problem with highly imbalanced data other than having a higher standard error than when the outcomes are balanced and the total sample size stays the same. The problem with AUROC is that like other measures you mentioned it is not sensitive enough for comparing two models. For that one should use the gold standard (log-likelihood) or sensitive measures discussed here.
stackexchange-stats
{ "answer_score": 2, "question_score": 1, "tags": "machine learning, roc, metric" }
Math counterexamples site Just wanted to share the link to a mathematical counterexamples site that I develop: Math Counterexamples. Any idea for improvement is more than welcome. On the way the site looks like, on good ideas for counterexamples, on the way to split counterexamples between level on math... Or anything else!
Nice! It seems you have few geometry (counter)examples. Here is one: > There are 4-dimensional convex polytopes that cannot be realized with rational vertex coordinates: that is, the combinatorial structure can only be realized with one or more irrational vertex coordinates. In $\mathbb{R}^3$, however, every convex polyhedron's combinatorial type can be realized with rational coordinates. (But it is unknown if the rational coordinates can be chosen to be "small.") > Ziegler, Günter M. "Nonrational configurations, polytopes, and surfaces." _The Mathematical Intelligencer_. **30**.3 (2008): 36-42. * * * !TobleroneTorus * * *
stackexchange-matheducators
{ "answer_score": 2, "question_score": 7, "tags": "mathematical pedagogy" }
Don't have a bench for bodyweight back extensions, alternatives? I don't have bench where I can do bodyweight back extensions, nor the space to put one. What are alternatives to work out the lower back? I'm only aware of one - lying flat on the back, place on foot on bench or and raise lower back, works, hamstrings, glute and somewhat lower back.
There really is no need to use a bench for any of this. The "hanging" part of the back raise can be handled by dead lifts, good mornings, those type of exercise where you raise to an upright position against resistance. The only part of the exercise you describe that isn't worked can be worked satisfactorily simply by laying on your stomach, and raising your chest off of the ground, keeping your legs and hips flat on the floor. Another possibility, although space may be an issue, is to use a Swiss ball for the same motion. Work on balance and stability first, as the ball is more mobile than a bench.
stackexchange-fitness
{ "answer_score": 2, "question_score": 0, "tags": "bodyweight exercises, home exercise, lower back" }
Wondering about the Windows 7 serial number my laptop has, and its uses So that's the serial number of my pre-installed windows copy, I take it. But am I allowed to use it again when, say, I don't know, my system gets crippled by a sneaky virus? If I format my computer and install windows starter again from a USB drive (speculating. I've never format before, I suppose is completely possible) Is that serial number still valid? I'm talking about the number printed on the back of my laptop. I have an Acer Aspire One model D255.
Yes, that license will still be valid for use on the laptop it was sold on in the case of a clean install.
stackexchange-superuser
{ "answer_score": 3, "question_score": 1, "tags": "laptop, windows 7 backup" }
What is the correct way to measure DC power at the output of a boost converter in a Simulink simulation? I modeled a DCDC boost converter, and I would like to measure the power at the output of the converter, I do not understand much about simulation times, sampling, and this sort of thing, so I do not know how to properly evaluate the actual output power of that converter, but I think it's not just V * I. Could someone give me some light? The first method I used was to calculate Irms and Vrms and do the multiplication. The second method was to get the Vrms to squared and divide by the Output Resistor The method I used to calculate the average value of the power was to take the instantaneous value (just the multiplication of V and I) and go through the block "Mean" using as fundamental frequency 25kHz which is the switching frequency. Are any of these methods correct, all wrong, or is there any better way to do this in simulink? ![enter image description here](
> The method I used to calculate the average value of the power was to take the instantaneous value (just the multiplication of V and I) That's how digital power meters do it and then average the result using a low pass filter for instance. This works for both AC and DC circuits providing harmonic distortion does not cause aliasing artefacts. However, it is likely that the DC voltage will have very little ripple current so you can make a fair-to-reasonable estimate of average power by multiplying voltage by low-pass filtered current. RMS of voltage or RMS of current are irrelevant to measuring power unless pure sine waves are involved and you know the power factor BUT this technique applies to AC circuits and is pointless for DC circuits.
stackexchange-electronics
{ "answer_score": 1, "question_score": 2, "tags": "power, dc dc converter, matlab, simulink, power measurement" }
Does "adding a constant to the potential energy" imply "adding a total time derivative to the Lagrangian." I am trying to understand why Taylor says in his Classical Mechanics text, "we can always subtract a constant from the potential without effecting any physics." I assume "doesn't effect any physics" means the equations of motion are unaltered — as is the result of adding a total time derivative to a Lagrangian. How are the two statements related? Explicitly please.
Yes, indeed the equations of motion are unaltered; clearly we consider potentials of the form $V(\mathbf q)$, Hence, the only contribution to the Euler Lagrange equations done by the potential is in the term $\frac{\partial L}{\partial q}$, since a constant vanishes under a derivative; then adding a constant do not affect the equations of motion. More intuitively, it has to do with the fact that a force $\mathbf F$ acting on a particle due to a potential $V$ is given by $\mathbf F=\partial V/\partial q$, again, the first derivative does the trick. Another way to think about it is that the Energy of a system, is the sum $T+V$ as functions of $(q,\dot q, t)$ in an extremal of the action functional. So that if we added a constant to the potential (from the beginning), we would add it to this sum in the entire path $q(t)$. Hence, we "kinda" decide with how much energy the system starts, the actual rule that governs the dynamics is the conservation of the energy; not the initial energy.
stackexchange-physics
{ "answer_score": 2, "question_score": 2, "tags": "classical mechanics, lagrangian formalism, potential energy, conventions" }
How to not include NA observations in grouping when using group_by() followed by summarize() with dplyr? I have a dataframe of phone numbers, emails and names. Some emails are duplicated, with different name spellings. I don't really care about which name remains, so I am grouping by email, and summarizing to choose first observation of name and phone numbers. However, there are some missing email addresses, but I want to keep them from grouping together so that I can keep the unique phone numbers. Using a simplified example, my data is: data <- data.frame(x=c(1,2,3,4,5,5,5,6), y=c("a","b","c",NA,"d","d","d",NA)) data %>% group_by(y) %>% summarize(x=first(x)) I lose the number 6 when I do this. How do I keep the NAs from grouping together and being summarized?
Probably handle `NA`s separately and bind them to original data. library(dplyr) data %>% filter(!is.na(y)) %>% group_by(y) %>% summarize(x=first(x)) %>% bind_rows(data %>% filter(is.na(y))) # A tibble: 6 x 2 # y x # <fct> <dbl> #1 a 1 #2 b 2 #3 c 3 #4 d 5 #5 NA 4 #6 NA 6
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "r, dplyr, grouping" }
About reducible matrices I'm doing a work about Perron-Frobenius theorem, and I'm trying to give a proof of it. I'm stuck, because I found that an irreducible matrix can't have a row or a column of zeros. I understand that this is a property that primitive matrix have, but why an irreducible matrix verify this too? Thanks!
A matrix $A$ is reducible if there is a permutation matrix $P$ such that $$\tag{1} P^TAP=\begin{bmatrix}A_{11} & A_{12} \\\ 0 & A_{22}\end{bmatrix}. $$ If $A$ would have a zero row, then it could be permuted to $$ P^TAP=\begin{bmatrix}A_{11} & A_{12} \\\ 0 & 0_{1\times 1}\end{bmatrix}, $$ by some $P$, which is (1) with $A_{22}=0$. Similarly, if $A$ has a zero column, it can be permuted to $$ P^TAP=\begin{bmatrix}0_{1\times 1} & A_{12} \\\ 0 & A_{22}\end{bmatrix}, $$ which is (1) with $A_{11}=0$. Hence, if $A$ has a zero row/column, it is reducible. Reversing this implication shows that an irreducible matrix cannot have a zero row and/or column.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "matrices" }
Center align the items in the keystroke package I am using the keystroke package to create keyboard icons. However several of the items are not center aligned. For example, the single digit numbers are all right aligned which makes the button look odd. How do I fix this? MWE: \documentclass[12pt]{report} \usepackage{keystroke} \begin{document} \begin{itemize} \item \keystroke{0},\keystroke{1} ...\keystroke{9}: The digits 0 through to 9. \item \keystroke{+}: Addition \item \keystroke{$-$}: Subtraction \item \keystroke{$*$}: Multiplication \item \keystroke{$/$}: Division \end{itemize} \end{document}
Try this: \documentclass[12pt]{report} \usepackage{keystroke} \usepackage{xpatch} \makeatletter \xpatchcmd\suse@keystr@ke {\hbox to 0pt{\unhbox\suse@key\hss}} % \suse@key = \hbox{{\keystroke@font\strut#1}} % \@tempdimb = max(\wd\suse@key, \dp\suse@key) {\hbox to 0pt{\hbox to \@tempdimb{\hss\unhbox\suse@key\hss}\hss}} {}{\PatchFailed} \makeatother \begin{document} \begin{itemize} \item \keystroke{0},\keystroke{1} ...\keystroke{9}: The digits 0 through to 9. \item \keystroke{+}: Addition \item \keystroke{$-$}: Subtraction \item \keystroke{$*$}: Multiplication \item \keystroke{$/$}: Division \end{itemize} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 1, "question_score": 0, "tags": "alignment" }
Is this hint for exercise 9(b) on p.52 in section 7 in chapter 1 in "Topology 2nd Edition" by James R. Munkres right? I am reading "Topology 2nd Edition" by James R. Munkres. I am trying to solve Exercise 9(b) on p.52 in section 7 in chapter 1. Is the following hint right? I think $f$ doesn't satisfy (*). $f(3)\neq h(3)=h(4)^2-h(2)^2=f(4)^2-f(2)^2.$ $g(1)=h(1)$. $g(2)=h(2)$. $g(3)=-h(3)$. $g(n)=\sqrt{g(n-1)+[g(n-2)]^2}$ for $n\geq 4$. By the principle of recursive definition, there exists a function $g:\mathbb{Z}_{+}\to\mathbb{R}$ satisfying the above formula. Obviously, this $g$ satisfies (*). ![enter image description here](
The hint is poorly stated. The reformulation of part (a) is $h(n+1) = \sqrt{h(n) + [h(n-1)]^2}$, as I assume you've already found. But for $f$ the idea is that $$f(3) = -\sqrt{f(2) + [f(1)]^2} = -\sqrt 3\\\f(n+1) = \sqrt{f(n) + [f(n-1)]^2}, \quad n \ge 3$$ Unfortunately, he tried to abbreviate this too much, and it didn't come out right. Quite frankly, I'm not sure why he bothered with a hint. It seems obvious that the way to come up with other solutions to (*) is to take the opposite square root somewhere down the line.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "functions, solution verification, recurrence relations" }
Display all Unicode chars in TextView Is there any way to show all Unicode chars in my TextView, on my phone? I have tried special characters like '\u0279' and I get something like box (default char). Is this based on l10n and i18n settings?
tv=(TextView)findViewById(R.id.textView1); Typeface font= Typeface.createFromAsset(getAssets(), "TAU_BHON.TTF"); tv.setTypeface(font); Place the font that will support your language in the assets folder.In this case i have used TAU_BHON.TTF
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 14, "tags": "android, unicode, textview" }
Multiple text-alignments in QLabel I have a QGridLayout with QLabels in it that are displaying some values and the units to that values. For good readability I want the value to be left-aligned within the QLabel and the unit to be right-aligned. At first I wanted to do this with QtStyleSheets but the only way I found was to change the text-alignment of the whole widget like this: myLabel.setStyleSheet("QLabel {qproperty-alignment: AlignRight}") My second thought was to do it via HTML but there I also encountered several problems. Here is what I tried: myLabel.setText("<div align=\"left\">Value<\div><div align=\"right\">Unit<\div>") This does the right thing, after that the value is left-aligned and the unit right-aligned, but they are not on the same line anymore. Nevertheless it appears to me the more promising approach. Unluckily I am not very familiar with HTML. Can anybody help?
Or if you really just want go on with html in QLabel use table instead of div's. But @saeed is right, better use Qt Layouts and spacer between them. Example with HTML: myLabel.setText("<table width=\"100%\"><td width=\"50%\" align=\"left\">Value</td><td width=\"50%\" align=\"right\">Unit</td></table>");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, qt, pyqt, text alignment" }
Stellar token vs contract - is it the same? I've just learnt that Ethereum tokens are also smart contracts (and the opposite is not necessarily true): < < I'm not a dev, so until now I was understanding **tokens** as assets that can be exchanged, while **smart contracts** as executable mini-programs that could trigger the exchange of these assets (based on some rules defined in the mini-program itself). So this discovery is leaving me with a lot of questions... First, is that also the case for Stellar tokens? Tokens are also contracts? And what does it mean that in other blockchains, tokens are contracts? Was my understanding of 'token=asset' wrong?
I posted this also on reddit and got this first answer: > The short answer is no. Stellar tokens are not smart contracts. On stellar tokens are created by accounts and identified by the issuing account. On eth accounts create smart contracts that create tokens Then I got a much longer answer from a SDF member: > Tokens are directly issued on the Stellar network from an account whereas the Ethereum network requires a smart contract to create a token. So it's easier and simpler to created a token on Stellar. and also learnt the following: > Another key difference between SSCs and Ethereum smart contracts is that the conditions and logic of the smart contract are created separately from Stellar then submitted to the network as a transaction when the end conditions are met. As a participant in a Stellar smart contract you are not directly interacting with code on chain
stackexchange-stellar
{ "answer_score": 0, "question_score": 0, "tags": "assets, token, operations" }
Are re-initialized classes in the same memory location as the initial class? From this question Shortest and best way to "reinitialize"/clean a class instance The answer to "Shortest and best way to “reinitialize”/clean a class instance" is myUsedInstance = myClass(); Now my question is: Is it guaranteed that the memory address is the same after re-initializing? That is, if I have a pointer `myClass*` that points to `myUsedInstance`, will that pointer correctly point to the newly initialized object or is there anything I have to be careful of?
The assignment does not change the old object's identity, all pointers and references to it remain valid.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c++" }
Why is adjusted R-squared less than R-squared if adjusted R-squared predicts the model better? As far as I understand, $R^2$ explains how well the model predicts the observation. Adjusted $R^2$ is the one that takes into account more observations (or degrees of freedom). So, Adjusted $R^2$ predicts the model better? Then why is this less than $R^2$? It appears it should often be more.
$R^2$ shows the linear relationship between the independent variables and the dependent variable. It is defined as $1-\frac{SSE}{SSTO}$ which is the sum of squared errors divided by the total sum of squares. $SSTO = SSE + SSR$ which are the total error and total sum of the regression squares. As independent variables are added $SSR$ will continue to rise (and since $SSTO$ is fixed) $SSE$ will go down and $R^2$ will continually rise irrespective of how valuable the variables you added are. The Adjusted $R^2$ is attempting to account for statistical shrinkage. Models with tons of predictors tend to perform better in sample than when tested out of sample. The adjusted $R^2$ "penalizes" you for adding the extra predictor variables that don't improve the existing model. It can be helpful in model selection. Adjusted $R^2$ will equal $R^2$ for one predictor variable. As you add variables, it will be smaller than $R^2$.
stackexchange-stats
{ "answer_score": 32, "question_score": 15, "tags": "regression, r squared" }
Type overflow in project euler #5 I am trying to solve the project euler #5: > 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. > > What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Here is my code: open System let rec gcd a b = match b with | x when x = 0 -> a | _ -> gcd b (a % b) let lcm a b = (a * b) / (gcd a b) let result = Seq.fold lcm 1 [1..20] [<EntryPoint>] let main(args : string[]) = printfn "result = %d" result 0 It works fine with numbers [1..19], but I get the wrong result with numbers [1..20]. I was trying to find out the reason of error and find that: $ Seq.fold lcm 1 [1..19] 232792560 // right $ lcm 232792560 20 18044195 // wrong It looks like the type overflow. How can I fix the error?
The other solution is to redefine slightly the lcm function let lcm a b = let m = b / (gcd a b) in a * m;; Since you multiply by slightly smaller numbers, it won't overflow. Euler problems are also about mathematics :p
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "f#" }
How to check a single radio button using jquery/java script? I would like to check only one radio button but in my code both radio buttons get selected. Here is my code its in netsuite. <input value="<%=getCurrentAttribute('item','internalid')%>" type="radio" name="service_level" onclick="getAddonFromNetsuite(<%=getCurrentAttribute('item','internalid')%>, '<%=getCurrentAttribute('item','pricelevel5')%>');"><label for="radio-2-1"></label> <input value="INPUT" type="radio" id="radio-2-2" name="service_level_1" onclick="getAddonFromNetsuite(<%=getCurrentAttribute('item','internalid')%>, '<%=getCurrentAttribute('item','pricelevel5')%>');"/><label for="radio-2-2"></label> here is the link of the site <
Please make the "name" of the radios be same for all. <input value="<%=getCurrentAttribute('item','internalid')%>" type="radio" name="service_level" onclick="getAddonFromNetsuite(<%=getCurrentAttribute('item','internalid')%>, '<%=getCurrentAttribute('item','pricelevel5')%>');"><label for="radio-2-1"></label> <input value="INPUT" type="radio" id="radio-2-2" name="service_level" onclick="getAddonFromNetsuite(<%=getCurrentAttribute('item','internalid')%>, '<%=getCurrentAttribute('item','pricelevel5')%>');"/><label for="radio-2-2"></label>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, jquery, radio button, netsuite" }
Navigation in lightning out for LWC I have a LWC which navigates to records using NavigationMixin. When I use the same LWC in VisualForce page using lightning out, the navigation does not work. I there any way to make it work? I did research but didn't find any guidance. Please help. navigateToRecordViewPage(event) { this.record = event.detail.row; // View a custom object record. thisNavigationMixin.Navigate; }
First check if you are in lightning or classic. If in lightning, use navigation.mixin. If in classic, use window.location.assign(). if(document.referrer.indexOf(".lightning.force.com") > 0){ thisNavigationMixin.Navigate; }else{ window.location.assign('/'+this.record.id); }
stackexchange-salesforce
{ "answer_score": 1, "question_score": 1, "tags": "lightning web components, navigationmixin.navigate" }
Android Kotlin - set animation end / finish listener val anim = swipe.animate() .rotationBy((-30).toFloat()) .setDuration(1000) .translationX((-swipe.left).toFloat()) .setInterpolator(AccelerateDecelerateInterpolator()) anim.start() I need an animation finish listener, I tried: anim.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(p0: Animation?) { } override fun onAnimationRepeat(p0: Animation?) { } override fun onAnimationEnd(p0: Animation?) { } }) but get this error > Unresolved reference: setAnimationListener How to do this right?
**Root cause** In ViewPropertyAnimator class, there is no method named `setAnimationListener`. **Solution 1** anim.withEndAction { // Your code logic goes here. } **Solution 2** anim.setListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { // Your code logic goes here. } }) **Note:** Remember to cancel the anim if users leave the screen while animation. swipe.animate().cancel()
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "android, kotlin, android animation" }
Get image order by time android I have wallpaper application which have image saving function and we are displaying that images in my collection menu. I want display it as new saved first. There any chance to order images like that ? My codes for get images from data folder is like below. public void getImages() { File root = new File(Environment.getExternalStorageDirectory()+File.separator+"KaroShare/"); File[] images = root.listFiles(); arrayList.clear(); if(images!=null){ for(int i=0;i<images.length;i++) { if(images[i].getName().endsWith(".png") || images[i].getName().endsWith(".jpg") || images[i].getName().endsWith(".jpeg")) { String path = images[i].getAbsolutePath(); arrayList.add(path); } } } } Let me know if someone have idea to do it. Thanks a lot !
You can sort the files with currentFile.lastModified().
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android" }
How to display only cache memory images in ViewPager using Universal Image Loader Android? I want to display only those images that were loaded into cache memory once we downloaded from url using `Universal Image Loader` _**Example_** I have **15 URLS** to download image and display in`ViewPager`, but out of them only 5 were downloaded and i closed the app.. Now i don't have any internet connection to get all the other images from web, but app will show only 5 images and remaining pages will be blank.. Is is possible to get the list of only those images from `cache Memory`?? How can we restrict `ViewPager` from other blank pages? I have successfully implemented `Universal Image Loader`, but got stuck on these issues. Any idea/suggestion/sample would be appreciated.. Thanks
You can define whether image was cached on disc using disc cache: File cachedImage = imageLoader.getDiscCache().get(imageUrl); if (cachedImage.exists()) { /// image is cached } You can check every image URL, define which images are cached and configure ViewPager appropriately.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "android, android viewpager, universal image loader" }
Why is my Windows lock screen spamming me? I'm running the Windows 10 April 2018 Update with Cortana enabled. Suddenly this morning there is a small earth/globe icon on my lock screen with the words: "Watch. Play. Connect.". There is another one of these icons on the top left of my lock screen showing: "Check out the most intense plays of the hottest games.". When I click either of these icons, it opens up my browser to mixer.com. I have never used this service, don't stream games and don't play online games. I have not installed any software recently so am confused as to where this came from. I do have an Xbox One and a Windows Phone of which all are connected via the same Live account. I have "Windows spotlight" set as my background but thought that only gives a you nice new background picture every day? Any ideas where this spam is coming from?
Windows Spotlight puts ads on the lock screen. See How to Disable Ads on Your Windows 10 Lock Screen to get rid of them. It's (sort-of) documented: > Windows Spotlight is an option for the lock screen background that displays different background images **and occasionally offers suggestions on the lock screen.** If you have Windows 10 Pro, that page shows how to disable third-party content in Windows spotlight via Group Policy.
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "windows 10, lock screen, windows 10 v1803" }
Can a unique index be created in MySQL if the table has repeating values? For an existing table, is it permissible to create a unique on a column that might have repeating values?
No, it is not permissible. The following SQL: ALTER TABLE `table` ADD UNIQUE (`column`) Will generate the following error: > #1062 - Duplicate entry 'data' for key 'column' You can identify duplicates using: SELECT * FROM `table` GROUP BY `column` HAVING COUNT(`column`) > 1 After removing all of the duplicates, you can add the `UNIQUE` constraint.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "mysql, database" }
Check whether a SAS date is valid before using MDY()? Is there a way to check whether three variables `(month, day, year)` can actually build a `valid SAS date format` before handing those variables over to `MDY()` (maybe except checking all possible cases)? Right now I am dealing with a couple of thousand input variables and let SAS put them together - there are a lot of date variables which cannot work like `month=0, day=33, year=10 etc.` and I'd like to catch them. Otherwise I will get way too many `Notes` like NOTE: Invalid argument to function MDY(13,12,2014) which then eventually culminate in `Warnings` like WARNING: Limit set by ERRORS= option reached. Further errors of this type will not be printed. I really would like too prevent getting those `Warnings` and I thought the best way would be to actually check the validity of the date - any recommendations?
Use an INFORMAT instead, then you can use the ?? modifier to suppress errors. month=0; day=33; year=10; date = input(cats(put(year,z4.),put(month,z2.),put(day,z2.)),??yymmdd8.); SAS documentation: ? or ?? (Format Modifiers for Error Reporting)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sas" }
Linq - Get a list and sort it by a list of string values I have a list of guids as string: This is how i retrive my list of string guids: List<string> p0 = ctx.PrProjectRating.Select(k => k).GroupBy(g => new { g.PrPIdG }, (key, group) => new { sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG }).Select(t => t.pidG).ToList(); Now i have another list that contains a field called pidG but this list needs to be ordered by the list of guid strings above. How do i achiveve this. i tried: List<PProject> p = p.OrderBy(c => p0.Contains(c.PIdG)).ToList(); but still the list is not ordered by the string guids in the first list "p0"
You have to do join here List<string> p0 = ctx.PrProjectRating .Select(k => k) .GroupBy(g => new { g.PrPIdG }, (key, group) => new { sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG }) .Select(t => t.pidG).ToList(); var result = p0.Join(p, x => x, c => c.PIdG, (x, c) => c) .ToList()
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, linq" }
Separating family of seminorms covers a vector space Let $\mathcal{P}$ be a separating family of seminorms on a vector space $X$. Show that if $x\in X-\\{0\\}$ then $\exists p\in\mathcal{P}$ such that $p(x)\leq1$. Context: This is from theorem 1.37 in Rudin's FA, part of an attempt to prove that the collection of $V(p,n)\equiv\\{x\in X|p(x)<\frac{1}{n}\\}$'s is a subbasis for a topology on $X$. In order to show that I must show that the union of all these sets give $X$. However, that's where I get stuck: as $\mathcal{P}$ is separating, it is clear that for $x\neq0$ there is some $p\in\mathcal{P}$ such that $p(x)\neq0$. If $p(x)\leq1$ then we are finished as we can just pick any $n\in\mathbb{N}-\\{0\\}$. However, what to do if all $p\in\mathcal{P}$ have $p(x)>1$?
I think this is a subbasis for the basis of open sets at 0, not for the whole space. Note that in the case that X is a normed space, then $\\{\|\cdot\|\\}$ is a (trivial) separating family, but in general you do not get the whole topology from just the open balls around the origin.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "functional analysis, vector spaces" }
LINQ grouping/subquery to fill a hierarchy data strcuture I have a DataTable that queries out something like below usergroupid...userid......username 1.............1...........John 1.............2...........Lisa 2.............3...........Nathan 3.............4...........Tim What I'm trying to do is write a LINQ statement that will return an array of UserGroup instances. The UserGroup class has properties of UserGroupId and Users. Users is an array of User instances. The User class then has properties of UserId and UserName. Can filling such a hierarchy be done with a single LINQ statement and what would it look like? Thanks a million
Check this out, hope this helps var users = new[] { new {UserGroupId = 1, UserId = 1, UserName = "John"}, new {UserGroupId = 1, UserId = 2, UserName = "Lisa"}, new {UserGroupId = 2, UserId = 3, UserName = "Nathan"}, new {UserGroupId = 3, UserId = 4, UserName = "Tim"} }; var userGroups = from user in users group user by user.UserGroupId into userGroup select new { UserGroupId = userGroup.Key, Users = userGroup.ToList() }; foreach (var group in userGroups) { Console.WriteLine("{0} - {1}",group.UserGroupId, group.Users.Count); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "linq, data structures, grouping, hierarchy, subquery" }
How to map ":f" to "1<c-g>"? `:f[ile]` has similar feature as `<c-g>`. However, I want `:f` to print the full path of the current file which is `1<c-g>`'s job. The following config doesn't work: `nnoremap :f 1<c-g>`, the count 1 just ignored by vim and `:f` has nothing changed.
To map from command line to normal mode you can use: cmap f normal 1<c-g>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "vim, mapping, key bindings, ctrl" }
How to marshal JSON with bigints? I have a `json` that contains a field with a `bigint` `{"NETWORK_ID": 6000370005980500000071}` The format I have before marshaling is `map[string]interface{}` When I marshal it and print to console everything seems to be fine but this field actually creates problems due to its size in other mediums so I want to serialize it as a string. `UseNumber()` seems to be for this purpose but it's only for decoding I think. Is there any way that I can detect this kind of `bigint` number and make them serialize as strings?
You'll need to create a custom type that implements the json.Marshaler interface, and marshals to a string. Example: type MyBigInt big.Int func (i MyBigInt) MarshalJSON() ([]byte, error) { i2 := big.Int(i) return []byte(fmt.Sprintf(`"%s"`, i2.String()), nil } This will always marshal your custom type as a quoted decimal number.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "json, go, type conversion, biginteger" }
Ayuda con matriz en C# Estoy aprendiendo `C#` por mi cuenta y he intentando hacer una matriz a partir de otros `array` pero me dice lo siguiente: > A nested Array initializer is expected **Este es el código:** string[] a = {"pequeña","mediana","grande"}; string[] b = {"esbelto","mediano","gordo"}; string[] c = {"cortas","medianas","largas"}; string[,] poolfen = {a,b,c};
Debes definir una array de dos dimensiones(matriz) y asignarle los array ya creados: String[] a = new String[3] {"pequeña","mediana","grande"}; String[] b = new String[3] {"esbelto","mediano","gordo"}; String[] b = new String[3] {"cortas","medianas","largas"}; String[][] matriz = new String[][] { a , b , c }; Console.Write(matriz[1][2]); Salida: gordo
stackexchange-es_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, matrices" }
Independence of a random variable and its conditional expectation Let $(\Omega, \mathcal{F},\mathcal{P})$ be a probability space. Let $\mathcal{H} \subset \mathcal{F}$ be a sub $\sigma$-algebra, and let $X\in L^1(\Omega, \mathcal{F},\mathcal{P})$ be a random variable. Suppose that $\mathcal{H}$ is independent of $\sigma(\sigma(X),\mathcal{G})$. Then, I want to show that (1) $I_{H}$ and $I_{G}X$ are independent. (2) $I_{H}$ and $I_{G}E[X \mid \mathcal{G}]$ where $H \in \mathcal{H}, G \in \mathcal{G}$ and $E[X \mid \mathcal{G}]$ denotes the conditional expectatinon $X$ given $\mathcal{G}$. For (1), I know that $\sigma(I_{H}) = \\{\Omega,\emptyset,H,H^c\\}$, but I do not know what $\sigma(I_{G}X)$. Similarily, I could not characterize what $\sigma(I_{G}E[X \mid \mathcal{G}])$ other than saying that $\sigma(I_{G}E[X \mid \mathcal{G}]) = \\{ (I_{G}E[X \mid \mathcal{G}])^{-1}(B), \text{ where B is Borel} \\}$. How should I proceed?
**Hints:** 1. Both $1_G X$ and $1_G \mathbb{E}(X \mid \mathcal{G})$ are measurable with respect to $\sigma(\sigma(X),\mathcal{G})$. 2. Since $\mathcal{H}$ and $\sigma(\sigma(X),\mathcal{G})$ are, by assumption, independent, it follows from the first step that $1_H$ and $1_G X$ as well as $1_H$ and $1_G \mathbb{E}(X \mid \mathcal{G})$ are independent.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "probability, probability theory" }
Is $sp(4)$ a subalgebra of $su(5)$? Is $sp(4)$ a subalgebra of $su(5)$? And how can I prove/disprove this? I know already that it cannot be a regular maximal subgroup of $su(5)$ since the Dynkin diagram (which has two roots of unequal length) cannot be recovered from the (extended) dynkin diagram of $su(5)$. So, if it is a subalgebra, the cartan generators of $sp(4)$ is niet a subset of those of $su(5)$...
No, for dimension reasons. $\dim \mathfrak{sp}(4) = 4 \cdot 9 = 36$ but $\dim \mathfrak{su}(5) = 5^2 - 1 = 24$. The smallest $n$ such that $\mathfrak{sp}(4)$ could embed into $\mathfrak{su}(n)$ on the basis of dimension alone is $n = 7$.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "abstract algebra, lie groups, lie algebras" }
Controlling a headless torrent server via transmission I'm running transmission-daemon on a Raspberry Pi running headless Raspbian. I can SSH into it fine, and the FTP server on it runs without a hitch, but I can't use the terminal interface for Transmission to control it. Running: $ transmission-remote -m $ transmission-remote localhost -m $ sudo transmission-remote -m All give the following error: > Unexpected response: 401: Unauthorized User: deflate, gzip Any ideas? Or am I using the wrong command? I want to be able to see active torrents, add more, etc.
Transmission-daemon has a web interface. If you want a pure command line interface, use transmission-cli Otherwise if you want to use transmission-remote, you'll need to modify `/etc/transmission-daemon/settings.json` and modify this line - `"rpc-authentication-required": true,` and make the true a false
stackexchange-raspberrypi
{ "answer_score": 3, "question_score": 2, "tags": "raspbian, networking, ssh, p2p" }
Extracting listview item name I'm trying to extract the name of an item in my listview1. public string selectedClient; private void kickClientToolStripMenuItem_Click(object sender, EventArgs e) { selectedClient = Convert.ToString(listView1.SelectedItems[0]); MessageBox.Show(selectedClient); Chatserver.DisconnectClient("Hej"); } But when i do this, i get this messagebox: ListViewItem: Name. Instead of just Name. How should i do this? Thanks in advance
You need to use `Text` property of the `SelextedItems[]` collection **Note:** You don't need to convert the value into `String` as the `Text` property returns `String` Try This: selectedClient = listView1.SelectedItems[0].Text;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, listview" }
Concise way to find "key" difference between 2 dictionaries? I needed to compare 2 dictionaries to find the set of keys in one dictionary which was not in the other. I know that Python _set_ objects support: set3=set1-set2 but I can't do: dict3=dict1-dict2 or: missingKeys=dict1.keys()-dict2.keys() (I was a little surprised by the last point, because in Java the keys are a Set object.) One solution is: missingKeys=set(dict1.keys())-set(dict2.keys()) is there a better or more concise way to do this?
Maybe [x for x in dict1.keys() if x not in dict2.keys()]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 6, "tags": "python, dictionary, set, set difference" }
What is the difference between 'to be important _to_ smb' and 'to be important _for_ smb'? > I have read in LDCE for Advanced Learners (2009) that 'when you mean that you care about smth a lot, say that it is _important to_ you, not that it is _important for_ you' and for instance in Face2Face Elementary (2nd edition) they teach you to use to be important _to_ smb but I have come across on more than one occasion the exact same phrase with preposition _for_ in coursebooks. I wonder what it means and whether there are any shades of meaning in usage in these two prepositions in the expression above.
In this context **for** refers to a purpose and **to** refers to a personal valuation. > It is important for the crypto-photographer to remain absolutely quiet if he hopes to capture the Yeti's courtship ritual. > > It is important for you to bring enough supplies on this mission. > > These skis are the right size for you. > > Making lots of money was important to her. > > To her it all seemed awfully vague. > > For the crypto-photographer to capture the Yeti's courtship ritual, he must remain absolutely quiet. > > For you, these skis are the right size. Do you see how **you** as the "intended user" qualify as the skis' purpose?
stackexchange-ell
{ "answer_score": 2, "question_score": 1, "tags": "prepositions" }
Pronouns in this sentence Context: > > … Problem sentence: > … Who can't be healed anymore, the person talking or the person it is being said to?
With the help of the previous sentence you gave, I think it means that cannot heal the wounds of anymore. In the previous sentence, is talking about (her?) wounds. The wounds carry over to the next sentence, are the object of the transitive verb . The subject is , but that was clear from the sentence in question.
stackexchange-japanese
{ "answer_score": 1, "question_score": 1, "tags": "translation, transitivity" }
Isomorphic graphs derived from $K_{10,10}$ > How many subgraphs of $K_{10,10}$ exist that are isomorphic to the graph $G$ on the picture? I can think of $P(10,10)$ but I don't think that all of these cases are isomorphic with $G$ !graph G
If you consider each vertex as unique then: Pick any 3 vertices from the 10 and they will form a triangle. Then pick another 3 from the remaining 7 and they form a triangle then another 3 from the remaining 4 and they form a triangle then the remaining one is connected to all three triangles so you can form the graph G. Thus the answer is ${10}\choose{3}$${7}\choose{3}$${4}\choose{3}$$=16800$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "combinatorics, graph theory, bipartite graphs, graph isomorphism" }
problem with generating rand number between 0 and 1 using C language I am trying to generate some numbers with the rand() function like below: int main() { int i=0 for(i=0;i<20;i++) { printf("%f\n",rand_md()); } return 0; } float rand_md() { return (float)rand()/(RAND_MAX+1.0); } But when I run gcc rand.c, I get the error like below: rand.c: In function ‘main’: rand.c:21: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’ rand.c: At top level: rand.c:36: error: conflicting types for ‘rand_md’ rand.c:21: error: previous implicit declaration of ‘rand_md’ was here What's wrong with my code? Best Regards,
When you use a function without declaring it first, C will assume it returns an `int`. To fix this, you have to declare the method signature for `rand_md` before you call it in `main()`. Add something like this before `main` or in a header file: float rand_md();
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c" }
When are environment variables loaded by java virtual machine for a program I have a java program that I am writing that needs to use environment variables to find a policy file on start up of certain classes. However, the environment variable value will be **conditional** based on what the purpose is of the class that is being entered by the program. For that reason then I would like to basically load the environment variables on the fly. However, I am not sure if this is possible since I am not too positive when the environment variables that will be used by a java program's virtual machine are loaded, or if after the environment variables are loaded, they can be changed. When are the environment variables for a system loaded by a java virtual machine, and can those environment variables set in the virtual machine for the program ever be changed?
The typical approach "if" you really need to set environment variables, is to code this logic in a wrapper script before launching the JVM (e.g. *.sh, *.cmd) You can then set the environment variables accordingly using `export` (linux) or `set` windows, etc.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, environment variables" }
Math Formula for updating values dynamically I have a problem that I want to calculate the food calories depending on the size. I would explain. Users would be able to enter food calories. for example lets say he enters the sugar he saids 1/2 sugar = 50 calories. I want to be able to update teh sugar if the user updates that food for example if another user goes to that item and change the quantity to 1 sugar it should automatically update to 100 calories. So far i have const calories = (quantity / DatabaseCalories) * DatabaseCalories ; thats not working.
If I understood it seems to be very simple. All you need to do is to store the base value, divide it by the new input and multiply the result by the base calories. For example: baseValue = 0.5 baseCalories = 50 newInput = 1 newValue = (newInput / baseValue) * baseCalories newValue = (1 / 0.5) * 50 newValue = 100
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
¿Es posible definir una política para nombrar restricciones en Spring JPA? Se que es posible nombrar las `Foreing Keys` y también definir manualmente las restricciones, pero ¿No habrá alguna forma de definir una política de nomenclatura para cada tipo de restricción y evitar así los identificadores aleatorios que genera por defecto Spring? **_e.g._** para una restricción de tipo `UNIQUE`, Spring genera el siguiente nombre: `UK_ob8kqyqqgmefl0aco34akdtpe` pero no se si sea posible definir de alguna forma el siguiente patrón: `AK_TABLE_ATTRIBUTE` para que Spring lo utilice cada que genere ese tipo de restricciones. Lo anterior mas que nada para estandarizar las restricciones y facilitar su mantenimiento.
Como comentas, existe `@javax.persistence.ForeignKey`: @OneToOne() @JoinColumn(name="vehicle_id", referencedColumnName="vehicleId", foreignKey=@ForeignKey(name = "Fk_userdetails_vehicle")) public Vehicle getVehicle() { return vehicle; } Pero si quieres es cambiar la extrategia de nombres en general, he encontrado esto:org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy Esta clase te permite definir el nombre de los elementos de tu base de datos, desde el nombre de las tablas, columnas hasta las foreign keys. Realmente es una extensión de la implementación de hibernate:
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "spring, spring boot, hibernate, jpa, spring mvc" }
Show that there are two Abelian groups of order $108$ that have exactly one subgroup of order $3$ Show that there are two Abelian groups of order $108$ that have exactly one subgroup of order 3$3$ **Attempt:** Since $108=2^2 .3^3$ , Hence the possible finite abelian groups of order $108$ will be isomorphic to $Z_{108},~~ Z_2 \oplus Z_{54},~~ Z_3 \oplus Z_{36},~~ Z_3 \oplus Z_3\oplus Z_{12},~~Z_{18} \oplus Z_6,~~ Z_6 \oplus Z_6 \oplus Z_3$ Now, since $Z_{108}$ is a cyclic group, it will have only one subgroup of order $3$. (a) Now, how do we check and confirm that the remaining groups have only one subgroup of order $3$? (b) Since, none of the groups : $Z_2 \oplus Z_{54},~~ Z_3 \oplus Z_{36},~~ Z_3 \oplus Z_3\oplus Z_{12},~~Z_{18} \oplus Z_6,~~ Z_6 \oplus Z_6 \oplus Z_3$ are cyclic, how can we be sure that there cannot exist other **non cyclic subgroups of order $3$** in addition to cyclic subgroups of order $3$ in each of these groups? Thank you for you help.
To address your second question, all subgroups of order $3$ regardless of what group we are in will be cyclic since all groups of prime order are cyclic. My hint to you for the first question is the following: Consider the direct product of two groups $G_1 \times G_2$. For some $a \in G_1$ and $b \in G_2$, the order of $(a, b) \in G_1 \times G_2$ will be $lcm(|a|, |b|)$, where $|a|$ denotes the order of $a$ as an element of $G_1$, and likewise for $b$. Of course, you might want to take some time out and prove this fact.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "abstract algebra, group theory" }
Шаблон структуры с произвольным числом полей Возможно ли в C++ создать шаблон структуры с переменным числом полей? При этом число и тип полей задавались бы аргументом шаблона типа typename enumName.
Можно с помощью массива, если это вам подходит: template<class T,int N> struct S { T arr[N]; } ; S<char,5> s={{'a','b','c','d','e'}}; S<int,5> i={{1,2,3,4,5}};
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, c++11" }
Let $x,y \in \ell^2$, show that $||x-y||_{{\ell}^\infty} \leq ||x-y||_{{\ell}^2}$ > Let $x,y \in \ell^2$, show that $||x-y||_{{\ell}^\infty} \leq ||x-y||_{{\ell}^2}$ Note $||x-y||_{{\ell}^\infty} = \sup_{1 \leq i < \infty} |x_i-y_i|$ and $||x-y||_{{\ell}^2} = \left(\sum_{i=1}^\infty (x_i-y_i)^2 \right)^{1/2}$ Let $d=\sup_{1 \leq i < \infty} |x_i-y_i|$ $d^2=\left( \sup_{1 \leq i < \infty} |x_i-y_i| \right)^2$ $=\sup_{1 \leq i < \infty} |x_i-y_i|^2$ $=\sup_{1 \leq i < \infty} (x_i-y_i)^2$ $\leq \sum_{i=1}^\infty (x_i-y_i)^2$ Take square root on both sides and we get the desired inequality. Can I argue that the supremum is always less than or equal than the sum of the terms? I feel like I am missing something here. I would like a hint or a nudge in the right direction.
Hint : $$|x_i|\leq\left(\sum_{j=1}^{\infty}|x_j|^2\right)^{1/2} $$ for all $ i\in \mathbb N $. So $$\sup_{i\in\mathbb N} |x_i|\leq\,?$$ (Recall that supremum is the lowest upper bound.)
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "real analysis, proof verification" }
How would someone move the active links content to position top.. by default problem is, it automatically scrolls to the end of the page. the only things by default that should be scrolled down is the container - section 3. < <script> $(document).ready(function(){ var target = $("#section3"); $('panel').animate({ scrollTop: target.offset().top - 100 }, 700); window.location.hash = "#" + "section3"; }); </script> i have also tried: $('.container').scrollTop($('.content').find('.active').position().top );
The problem is that you are changing the Browser address hash to #section3. window.location.hash = "#" + "section3"; By default the browser will change the scrollTop value of the page to the top value of this `id`. JSFiddle demo without the hash change.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, html, css" }
If the mouse over check I want to check mouseover and mouse leave status and execute some function if the mouse is over element or is out. I tried something like this, but it didn't work. if($('#someid').is(':hover')){ DO STUFF OVER }else{ DO STUFF ELSE }
I'd suggest: $('#someid').hover( function(){ // do stuff when mouseover }, function(){ // do stuff on mouseout. }); Reference: * `hover()`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "jquery" }
What are some types and/or terms in system-f that cannot be expressed in Hindley Milner I remember reading somewhere that Hindley Milner was a restriction on system-f. If that is the case, could someone please provide me with some terms that can be typed in system-f but not in HM.
Anything involving higher-ranked (i.e. "first-class") polymorphism. For example: lambda (f : forall A. A -> A). (f Int 1, f String "hello") This function would have the type `(forall A. A -> A) -> Int * String`, which is not expressible in HM, where all polymorphic type schemes must be in "prenex" form (i.e. the quantifier may only occur on the outside, never nested).
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 10, "tags": "types, type inference, lambda calculus, hindley milner" }
¿Cómo parar el responsive de la pantalla en un tamaño específico? Soy novato en CSS, estoy utilizando Bootstrap 4, mi duda es ¿cómo parar el responsive de la pantalla en un tamaño especifico? Cada vez que se hace más pequeña la pantalla cada vez se va encojiendo todo y queda mas apretado, ¿cómo logro que en un tamaño especifico deje de tratar de adaptarse a la pantalla del dispositivo? Es como que si la pantalla se volviera un `overflow: auto;` y se pudiera recorrer la web arrastrando el mouse y para la adaptabilidad a la pantalla del dispositivo. No se si me explico... De antemano gracias por sus respuestas!
No estoy seguro de entender lo que dices de "parar" pero si lo que quieres, es que llegado unas dimensiones, no siga ajustandose, utiliza las llamadas MediaQuery. Son asi: <style> @media (max-width: 600px) { .facet_sidebar { display: none; } } </style> Con esto, lo que puedes hacer, es poner min-width:400px y cuando llegue al numero de px, dejara de ejecutarse el codigo. Te dejo el enlace para que puedas ver mas ejemplos. <
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "html, css, bootstrap 4, responsive, mediaqueries" }
Google Analytics discrepancy - excluding IP address Friday the 22nd of november we've gotten over the course of 2 hours two different conversion amounts in Google Data studio (=> pulled data from Google Analytics). At 15.00 pm we hit 22 conversions. Some time later at 17.00 pm we hit 9 conversions. At 14.45pm the website (< went down. So not willing to corrupt our data a test IP address was excluded from Google Analytics. With that being said it seems strange that the conversion amount changed during that time window due to an exclusion of 1 IP Address. So I am wondering: 1. Can an IP exclusion change previously acquired conversions in a short time window? 2. Perhaps Google Data studio pulled wrong data due to a bug from 14pm to 17pm 3. Another reason? Thanks for helping.
In Google Analytics the data can be considered stable after 48 hours (within that time they can be reworked). If you have converted on the same day that you applied the IP filter (which excludes the network from which you made the conversion) you must consider, i.e., that after midnight Analytics reprocesses the data of the day and therefore applies the filter to the whole day just ended (even if you added the filter only in the afternoon).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google analytics, google data studio" }
Checking stderr of check_call command and rerunning the command based am sure there is a better way to write the below code...below are the issues am running into with my current code, please provide any inputs you may have 1. I want to check the stderr of below command and re-run it based on the error message 2. Error mesage looks like "error: Cannot delete the branch "alphanumeric string" which you are currently on,am trying to match like below but running into error import subprocess def main(): change="205739" proc = subprocess.Popen(['git', 'branch', '-d', change], stderr=subprocess.PIPE) out, error = proc.communicate() if error.startswith("error: Cannot delete the branch"): subprocess.check_call(['git', 'branch', '-d', change]) if __name__ == '__main__': main()
You really want to avoid using `shell=True`, split it out into a list instead and you'll save yourself having to use interpolation to boot. To test for equality, use `==`; `=` is for assignment only which is not allowed in a `if` statement. You need to use `.Popen()` if you wanted to check for `stderr` output: import subprocess def main(): change="205739" proc = subprocess.Popen(['git', 'branch', '-d', change], stderr=subprocess.PIPE) out, error = proc.communicate() if error.startswith("error: Cannot delete the branch"): subprocess.check_call(['git', 'branch', '-d', change])
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, python 2.7" }
Can a from __future__ import ... guarantee Python 2 and 3 compatibility? I'm not interested in warming up the "Python 2 or Python 3?" questions (even though the most recent one I found is over one year old), but I stumbled upon this claim: > You can write the Python 3 code under Python 2 if your file begins with the line: > > > from __future__ import absolute_import, division, generators, unicode_literals, print_function, nested_scopes, with_statement > > > With that line in place, your code will work with either Python 2 or Python 3. There may be rare cases in which it doesn't work, but I have not found any, Is this true? Is this single line enough to make sure the code you write will run on both Python 2.x (>=2.5 I assume) and 3.x (assuming the modules imported are available in both)?
"It depends" **No:** Adding these imports to your Python 2 code will not make it run under Python 3. **Yes:** With these imports in place you can write code that runs under both Python 2 and Python 3. **But** : Then again, you can do that without those imports as well, and several of them, such as `unicode_literals` have turned out to simply not be helpful. `generators` and `with_statement` have nothing to do with Python 2 to Python 3 at all, those are features added in versions of Python 2. So in conclusion, these imports are a bit of a red herring, and the statement is more wrong than right. **However,** that doesn't mean writing code that runs under both Python 2 and Python 3 is impossible, or even necessarily very hard. See < for more info.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 12, "tags": "python, python 3.x, python 2.x" }
How to add animated icon to contentView of download notification? I know I could have animated download icon in status bar when downloading a file by using the default android resource `android.R.drawable.stat_sys_download`. My question is how to have this animated icon in the contentView of download notification? Like when you are downloading a file with Chrome. ![animated icon in notification contentView]( I attempted to display the resourse using ImageView but it does not support animated icons and the icon was displayed like an ordinary icon with no animations.
I found the solution. You should use notification styling. Icon is one of the major components in the notification which android sets its style. So in addition to use `android.R.drawable.stat_sys_download` as icon resource, you should use `.setStyle` even if you have custom notification layout. mBuilder = new NotificationCompat.Builder(context, channelID) .setCustomContentView(collapsedView) .setColor(context.getResources().getColor(R.color.colorPrimary)) .setSmallIcon(android.R.drawable.stat_sys_download) .setOngoing(true) .setStyle(new NotificationCompat.DecoratedCustomViewStyle()) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setPriority(NotificationCompat.PRIORITY_LOW);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, android notifications" }
Emacs: Insert tab instead of spaces For several reasons I prefer to configure my editor to insert spaces when `TAB` is pressed. But recently I discovered that tabs should remain as tabs in make files. How do I insert tab (`\t`, not `" "`) without reconfiguring editors each time I need to write make files? I use the following editors: Emacs, Kate, gedit, and the Visual Studio editor.
Emacs' Makefile mode takes care of where to insert tabs and spaces as long as you press the right keys at the right places. Either that, or I missed some details in the question.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 31, "tags": "emacs, makefile, text editor" }
Azure Table Storage - Data Lake File - SLOW response time when fired for fetching single row Select Statement through USQL Data from Transaction Database table is pulled into Data Lake, around half million records with around 20 columns, in Data Lake it is in JSON format. Through Logic Apps, via Python -> U-SQL function, firing U-SQL statement to read particular row, response is slow, looking for improving performance.
There are couple of reason for the slowness when compare to local execution 1\. Cluster environment is not as same as local. On cluster you have only 2 cores and 6GB of memory. Also we restrict operator to use no more than 512MB of RAM per operator. None of this issue happens on local side of the world. 2\. There is an marshaling overhead and then creating dataframe when going form usql operator to python extension and via versa once you are done with the python execution 3\. We need to also create an environment on the container which will be executing python code which includes copying the python run time We are going to address 2 and 3 limitation in upcoming release in Jan 2018.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "azure, azure data lake, azure logic apps" }
Is it possible to exclude parts of your model using Html.EditorFor? Should be pretty simple question here. I have @Html.EditorFor(model=>model.Training) I dont want to show some parts. Is there a way for me to exclude some from showing?
[ScaffoldColumn(false)] public string SomeProperty {get; set;} That should do the trick!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, asp.net mvc" }
PHP Image comparsion analysis I am looking to store the fingerprint / image for 1 million images, so that upon upload it will shoot a % of how similar the image compared to other matches in the database. Similar to < and < but for my own personal site. I do not want to submit the images to tineye using their submission process. What information should be saved? How should I save it? Any good PHP libraries that do what I want already? I would like to keep it PHP only, but I think the processing power may need to be outsourced by an application and then PHP can process the output. I am running Debian Linux. For storage, I was going to store just the information in MySQL but I think it may inefficient given 1 million images.
I decided to go for this PHP solution: < Even though it's a little outdated and didn't quite work with a cropped image, it was able to identify small edits, color changes, and some resizes. It also comes with example PHP code (albeit buggy)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, image processing, imagemagick" }
Code to print in the Qgis console the values ​of the attribute table that are selected in the shapefile I found a code that prints all data that a shapefile has in the attribute table in the qgis console. But i wanted to have a code that just printed the data that i select in the shapefile. Can someone help me? I'll leave here the code that prints all the data. lyr = iface.activeLayer() features = lyr.getFeatures() featList = [] selected_features = layer.selectedFeatures() for feat in features: featList.append(feat.attributes()) featList.sort() for f in featList: print f
You almost have it... just loop over `selected_features` and indent the code properly: lyr = iface.activeLayer() selected_features = lyr.selectedFeatures() featList = [] for feat in selected_features: featList.append(feat.attributes()) featList.sort() for f in featList: print f
stackexchange-gis
{ "answer_score": 4, "question_score": 1, "tags": "pyqgis, qgis python console" }
Ubuntu 16.04, how can I share an unmounted disk/partition with windows machines in same lan? I created a raid 1 mirror from two physically attached disks and partitioned and formatted the newly formed raid 1 drive. My question is: Can I share this raid 1 drive in my local lan with other windows machines in WORKGROUP without having to mount the raid 1 drive in my linux server itself and how would I do that? Thanks
In order to use the files, a partition must be mounted by some software. You can mount the partition locally and then share the files and directories using samba (see this answer for a graphical setup). It is also possible to share the partition on the network, and then mount it remotely, for instance using iSCSI. In any case, the partition will be mounted either locally or remotely.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "16.04, mount, samba, raid, sharing" }
ampersand not passing through url On my site www.gibberize.com if you type in the word "and" in the top textarea, the character "&" will appear in the second textarea. The problem is that the "tweet it" link will then append the second textarea's text to a url and proceed to the link, but because it is an ampersand it will break the text. Any solutions?
Use PHP's `urlencode()` function.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, url, ampersand" }
Putting 了 in both parts of separable verbs: is it mandatory? My sentence is > **Can I put at the end of sentence? Or is it mandatory to put between both parts of (a separable verb)?**
is not grammatical. means 'started', means 'have finished class', You cannot "Started to have finished class" A grammatical sentence should be (I attend classes in the morning) --> (I have attended classes in the morning) And yes, you can insert between the verb and noun in any separable verb to indicate it is completed action Example: (read book) --> (have read book) (eat meal) --> (have eaten meal) (skip classes) --> (have skipped classes)
stackexchange-chinese
{ "answer_score": 2, "question_score": 1, "tags": "sentence structure" }
ionic 3 App restarts rather than resumes I have created ionic App with two pages , from Page1 if i navigate to Page2 .On press of hardware back button navigates back to Page1 , and again hardware back the app goes to background . If the App is opened from background the splash screen is reloaded and the app relaunches . How to stop relaunching the app ?
I have used plugin < to minimize the app In app.component.ts import { AppMinimize } from '@ionic-native/app-minimize'; import { App, Platform } from 'ionic-angular'; constructor(platform: Platform,public appMinimize: AppMinimize, public app: App){ platform.ready().then(() => { platform.registerBackButtonAction(() => { let nav = app.getActiveNavs()[0]; let activeView = nav.getActive(); if (activeView.name === "Page1") { /** minimize the app in background **/ this.appMinimize.minimize(); } else { nav.pop(); } }); }); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, cordova, ionic framework, ionic3" }
how to use increment function in laravel **i am using DB to store values in database.** **i have "course fees" column i what to "increment" the "course_fees" value in column.** **for example** DB::table('student')->where('registration_id','=', $request->registration_id)->increment(['course_fees' =>$request->course_fees]); **this code increment the inserted value** **how can i modified below code for increment "course_fees" value like above** DB::table('student')->where('registration_id','=', $request->registration_id)->update(['payment_date' => $request->payment_date,'balance_fees' => $request->balance_fees,'course_fees' =>$request->course_fees]);
`increment()`/`decrement()` can take 3 parameters: `$column, $amount, $extra`. `$column` is the field that you want to increment `$amount` is by how much you want to increment the field by `$extra` is an array of attributes that you also want to update in the query. If you don't pass an amount the default for `$amount` is 1. * * * To achieve what you're after you could do: DB::table('student') ->where('registration_id', $request->registration_id) ->increment('course_fees', $request->course_fees, [ 'payment_date' => $request->payment_date, 'balance_fees' => $request->balance_fees, ]);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "laravel, laravel 5, laravel 5.6, laravel query builder" }
Getting "Animal" class into "Dog" class - values I have an `Animal` base class and a `Dog` that inherits from. class Dog: Animal I have a service which returns an Animal, I don't control it. Is there a way to get a `Dog` object from the `Animal`, but with the Animal's values without manually copying the animal values to Dog ?
No, you have to write code which will describe how `Dog` can be created from `Animal`. You can do this as additional constructor: public Dog(Animal source) { // copy value // (...) } With that you can just say: var dog = new Dog(myAnimalReceivedFromService);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, inheritance" }
I have loose screws - how can I tell a drywall screw apart from a wood screw? Say I have a bunch of screws. Say they are all flat (countersunk) head, phillips drive. They can be different shank/root diameter, with or without a smooth shank, different thread coarseness, color, etc. They all have a pointy end, about the same angle of point with maybe a small difference in how far from the point the threading ends. They are all magnetic. **Exhibit A:** ![enter image description here]( I know screw #1 is a decking screw and I know that screw #7 is drywall, because that's what the packages said. #6 is brass-color and #8 is gray (and rust), the others being the color they look to be. Wood screws will generally have a smooth shank at the top, being wood screws, but some (like #9 I think) don't. And a lot of drywall screws are black. I have a lot of loose screws. How can I determine the types of screws?
Drywall screws have a “bugle head”. Flat head wood screws have a “tapered head”. This may help: <
stackexchange-diy
{ "answer_score": 2, "question_score": 2, "tags": "screws, fastener" }
Matplotlib suptitle prints over old title I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: self.ui.canvas1.figure.suptitle(title) where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for the fact that when I run this code again later, it just prints the new text on top of the old, resulting in a gargeled, unreadable title. How do you replace the old `suptitle` of a figure, instead of just printing over? Thanks, Tyler
`figure.suptitle` returns a `matplotlib.text.Text` instance. You can save it and set the new title: txt = fig.suptitle('A test title') txt.set_text('A better title') plt.draw()
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 13, "tags": "python, matplotlib" }
How can I install Ubuntu with APT (not Snappy) on the Raspberry Pi 2? < lists only a Snappy Ubuntu Core image for the Noobs OS installer. Is it possible to install a traditional Ubuntu OS, featuring apt-get together with the standard repositories (so not Snappy Ubuntu), on the Raspberry Pi 2? Is a Noobs image for this in the works?
User leo submitted a great answer as a comment, I am reposting it here for convenience: > There is also a community image here, with all instructions on what you might want to install/configure as well
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 3, "tags": "system installation, raspberrypi, ubuntu core" }
Pull text from .txt file and display php I am trying to create some canvases which pulls some text from a .txt file. My .txt contains on every line name, surname, gender and role separated by space. I want to create a new canvas for each row from my .txt file. This is how i thought to extract the values from my file: $source = fopen('datas.txt', 'r') or die("Problem open file"); while (($data = fgets($source, 1000, " ")) !== FALSE) { $name = $data[0]; $surname = $data[1]; $gender = $data[2]; $role = $data[3]; } fclose($source); But i don't really know how to put them in a canvas. Can i make a loop or something to create a canvas for each row? I want some suggestions if someone can help me.
Use the data with a function <script type="text/javascript"> function canvasSmth( i ) { var canvas = document.getElementById('mycanvas'); var drawtext = canvas.getContext('2d'); drawtext.font = "30px Arial"; drawtext.fillText(i,10,50); } </script> $source = fopen('datas.txt', 'r') or die("Problem open file"); while (($data = fgets($source, 1000, " ")) !== FALSE) { $name = $data[0]; $surname = $data[1]; $gender = $data[2]; $role = $data[3]; echo '<script type="text/javascript"> canvasSmth( <?php echo $name ; ?> )'; } fclose($source);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "php, html, canvas" }
Python regex partial extract I want to find all data enclosed in `[[ ]]` these brackets. > [[aaaaa]] -> aaaaa My python code (using re library) was la = re.findall(r'\[\[(.*?)\]\]', fa.read()) What if I want to extract only 'a' from `[[a|b]]` Any concise regular expression for this task? ( extract data before `|` ) Or should I use additional if statement?
You can try: r'\[\[([^\]|]*)(?=.*\]\])' `([^\]|]*)` will match until a `|` or `]` is found. And `(?=.*\]\])` is a lookahead to ensure that `]]` is matched on RHS of match. **Testing:** >>> re.search( r'\[\[([^\]|]*)(?=.*\]\])', '[[aaa|bbb]]' ).group(1) 'aaa' >>> re.search( r'\[\[([^\]|]*)(?=.*\]\])', '[[aaabbb]]' ).group(1) 'aaabbb'
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "python, regex, extract, partial" }
Should I do online transaction [WannaCry Ramsomeware] Can I do online transaction safely without getting affected by WannaCry Ramsomeware? If I do, then how would I be affected? The site I'm trying is **Amazon**.
There is no relation between you doing online transactions and Wannacry infections. Wannacry spreads through file shares, not via the browser. How do malware like WannaCry infect new computers even if someone on those computers does not click a link or visit a website? (Reddit)
stackexchange-superuser
{ "answer_score": 5, "question_score": -2, "tags": "wannacrypt, ransomware" }
Best jquery form wizard for a rails app I need a multistep registration form wizard for my rails app.. I know theres lots of established jquery solutions out there, anyone have an opinion on the best?
Try this video tutorial from railscasts.com * < Also look at: * Turn any webform into a powerful wizard with jQuery (FormToWizard plugin) * Demo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "jquery, ruby on rails" }
Optional Type (_all) in NEST - Elasticsearch I Nest, how do you produce this request: GET demo_covariant/_all/2
client.Get<dynamic>(2, g => g .Index("demo_covariant") .Type("_all") ); Change `dynamic` to whatever type is expected (`dynamic` will work, will be a Json.NET `JObject`). The client supports search to return covariant types. Covariance is not supported for responses that return a single type.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "elasticsearch, nest" }
Xcode iPhone SDK - Check if UIImageView did fail to load image How do i check if the UIImageView did fail to load the image ? I have a UIImageView loading an image from URL like so: [MyImageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@" but if the image for some reason is not available i want to load an alternative image. How would i approach this problem ? Can i add some kind of observer ? Alternatively can i check when the ImageView did finish loading the image to check if the image is nil ? Thanks !
You are making a synchronous request on main thread and not even checking error conditions like if it fails or network connection times out. You can use this instead: [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@" queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error){ if(error) { // Error Downloading image data } else { [MyImageView setImage:[UIImage imageWithData:data]]; } }]; Using Asychronous url load using NSURLConnection. When connection has finished downloading data or error occured it notifies via connection handler block.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "xcode, uiimageview, ios5" }
JQuery load multiple url's and return only one deferred at the end I've a array of url's. I like to load each of them and append the content to the element. var myStrArray = [" " " //Initialize local deferred for myStrArray var myDeferredArray = []; for (var i = 0; i < myStrArray; i++) { myDeferredArray[i] = $.Deferred(); } for (var i = 0; i < myStrArray.length; i++) { $(element).load(myStrArray, function() { doSomething(); myDeferredArray[i].resolve(); }); } return myDeferredArray as single deferred
to get a single deferred $.when.apply(null, deferreds);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, ajax, jquery deferred" }
Favorite server OS and source control system for small project I am starting a small project with one other developer and need to setup a dedicated system to house our version control and any other short-term needs the project may have. Requirements for the server are: * Free/open source OS. * Must provide source control. * Must run all the time. That's it. So I know there are about a thousand Linux-based server distros around that can accomplish this, but looking for success stories from anyone who has managed their own server(s) for a small project. Which did you find easiest, most flexible, most powerful, etc? Side question: favorite source control system and why?
I have a dedicated Ubuntu server using GIT for version control. Managing private repositories with gitosis. And it's been great. > Manage git repositories, provide access to them over SSH, with tight access control and not needing shell accounts. > > gitosis aims to make hosting git repos easier and safer. It manages multiple repositories under one user account, using SSH keys to identify users. End users do not need shell accounts on the server, they will talk to one shared account that will not let them run arbitrary commands. It's robust, damn fast, and reliable.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "linux, version control, operating system" }
Rql `or` not work while involving non-exists field version: 1.15.2 r.db('test') .table('form') .filter(r.row('yyy').eq('aaa').or(r.row('id').eq('aaa'))) .limit(10) Why this query cannot match a document where `id` is `aaa` but without field `yyy`
There is special handling for non-existing fields (`default: false`) so I guess it is best to rewrite the query to not call `.eq()` on a missing field. You could either check `id` first: .filter(r.row('id').eq('aaa').or(r.row('yyy').eq('aaa'))) or maybe by setting the default behavior directly on the operation with missing fields: .filter(r.row('yyy').eq('aaa').default(false).or(r.row('id').eq('aaa'))) BTW: an update to this answer. After reporting a documentation bug for RethinkDB it turns out, this is already mentioned in a troubleshooting guide: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "rethinkdb" }
Fingerprint Matching - generated Pattern, dont know how to compare - code attached I have generated fingerprint pattern using following project: < But, I don't know how to match two image patterns. I want to compare patterns, not images. Please go through above code and help me.
One way is to use co-efficient of correlation,basically an fingerprint would be an image ,so you can use some image improvement algorithms and then apply co-efficient of correlation(which is the degree of similarity between two matrix and basically an image is an matrix of pixels)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, pattern matching, fingerprint" }
Using Redis with magento 1.9 I have a magento setup where I am using one box for apache server and one as mysql server. I want to install redis in this installation. I am not sure how I can achieve that. My questions are: 1. On which box should I install Redis? 2. Is there any step by step tutorial for such setup? As i am new to this. 3. How can I configure magento to use redis server? Thanks in advance.
Since you are only using 1 frontend server, I would set it up on that as it will be faster and take additional load off the database network connection. 1.9 has the Cm_RedisSession module included in the codebase and it's a doddle to setup, take a look here for step by step instructions; <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "magento, redis" }
Batch: Receive output from arduino from Serial port to CMD (Windows 7) I have an Arduino where I would like to send an command to the command prompt. My solution to the problem would be to make a batch program that listen to the serial port and then runs the command, but I do not know how to do this. Any suggestions?
If you need a console application you can write a console application in, e.g., C# with Visual Studio and start the application via CMD. The application itself, can listen and print out all incoming serial data. I would recommend you to use the bidirectional serial connection library, called CmdMessenger. The usage is quite straightforward and there are several examples and documentation resources on the web. I think you can easily adapt the examples for your application scenario.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "windows, batch file, serial port" }
Copy current text and change it I have lots of URLs in an spreadsheet, I need upload it in the following format: It is currently like this: I need it like this: , I know i can just use find & replace to replace _ with - but how can i copy the same url next to the exisiting one? I'm using Openoffice Calc Thanks
The only difference between the two solutions is the delimiter used for the concatenate and substitute statements i.e. ";" vs ",". **Openoffice Solution:** =CONCATENATE(A1;", ";SUBSTITUTE(A1;"_";"-")) Result !enter image description here **Excel Solution:** =CONCATENATE(A1,", ",SUBSTITUTE(A1,"_","-")) Result !enter image description here > I know i can just use find & replace to replace _ with - but how can i copy the same url next to the exisiting one? In the end, you could hide the original column and leave the custom column.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "excel, openoffice calc" }
How does the Json response know/remembers who requested it? For instance, say I'm trying to communicate with another app that randomizes any string. If **user1** sends a Json request and then **user2** also sends a Json request, how does the Json responses know which user to associate itself with?
This is handled at the network layer between the client and the server unless user 1 and 2 are sharing the same client.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "json" }
Loss function in GradientBoostingRegressor Scikit Learn GradientBoostingRegressor: ![Scikit Learn GradientBoostingRegressor]( I was looking at the scikit-Learn documentation for GradientBoostingRegressor. Here it says that we can use 'ls' as a loss function which is least squares regression. But I am confused since least squares regression is a method to minimize the SSE loss function. So shouldn't they mention SSE here?
It would seem that you are over-interpreting what is essentially just convenience shorthand names for the model arguments, and not formal terminology; here, " _‘ls’ refers to least squares regression_ " should be interpreted as " _'ls' is the loss function used in least-squares regression_ ". Formally you do have a point of course - `sse` would be a more appropriate naming convention here; discussions about such naming conventions are not uncommon among the community, see for example the thread loss function name consistency in gradient boosting (which BTW was resolved here). And you would be most welcome opening a relevant issue for the convention used here.
stackexchange-datascience
{ "answer_score": 1, "question_score": 1, "tags": "machine learning, scikit learn, loss function, terminology, gbm" }
How can I uninstall Ruby on Rails on Mac OS X? I am following a tutorial about Ruby on Rails, and the tutorial got updated to a new version of Rails, so I can't follow it anymore because I have an older version. I would like to start new and uninstall Ruby on Rails and any related software on my Mac OS X 10.5.8, and follow it from ground up. If anyone would be willing to help me uninstall Ruby and Ruby on Rails, it would be much appreciated.
Download RVM or RBENV and upgrade to the latest Ruby (2.3.0 at this point). Don't touch your system Ruby.
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 16, "tags": "ruby on rails, ruby, macos" }
Emblem gestures Another puzzle in the spirit of the Density™ puzzle. Just monochrome this time I'm afraid. Enjoy! ![enter image description here]( **Final answer: (3, 4, 5)**
Answer: > Fun With Flags Building on the same reasoning as per @Belhenix: > Semaphore alphabet spells "Sheldon Cooper Presents", and as a TBBT watcher this is immediately recognizable as the introduction to his ridiculous video series, "Fun With Flags" - which also fits with the semaphore flags used.
stackexchange-puzzling
{ "answer_score": 7, "question_score": 6, "tags": "enigmatic puzzle, visual" }
How do I calculate days elapsed since given time I'm trying to calculate how many days elapsed from date. When I do `=DAYS(TODAY();C3)` I get 1903-06-04, but I'm expecting number of days.
Excel stores dates as a number where the integer portion is the date (starting at 1/1/1900) and the fractional portion is the time. `DAYS()` returns an integer, but if the cell is formatted as a date it will display a (probably very old) date. Changing the cell format to General or Number resolves the issue.
stackexchange-superuser
{ "answer_score": 3, "question_score": 2, "tags": "microsoft excel" }
Is the absolute value of the difference a kernel? In particular is $$ k(x_i,x_j)=|x_i-x_j|, \quad x_i,x_j\in \mathbb{R}$$ a valid kernel?
Indeed it is **not** a kernel. Consider the dataset $\mathcal D = \\{0,1\\}$. The gram matrix of $k(x_i,x_j)=|x_i-x_j|$ is given by $$ K := \begin{bmatrix} k(x_1,x_1)& k(x_1,x_2) \\\ k(x_2,x_1)&k(x_2,x_2) \end{bmatrix}= \begin{bmatrix} 0& 1 \\\ 1&0 \end{bmatrix} $$ Solving for its eigenvalues, we get: $$ \begin{vmatrix} -\lambda & 1 \\\ 1&-\lambda \end{vmatrix}=0 \implies \lambda=\pm 1\not \geq 0 $$ Thus its is not positive semi definite and the kernel is **not** valid.
stackexchange-stats
{ "answer_score": 7, "question_score": 4, "tags": "machine learning, svm, kernel trick" }
Visual Studio 2010 Html Formatting option for client attributes is disabled Recently I noticed that my vs2010 was auto lower casing my html attributes. This does not go very well with the use of dojo since `onclick` != `onClick` and `dojo.query([Attribute])` != `dojo.query([attribute])`. Now I've fooled with the VS options before and went straight to Tools > Options > Text Editor > HTML > Formatting to set client attributes to as entered. Well these two options are disabled. I've disabled all my extensions and addins as best as I know how and it is still unaffected. Searches are not returning anything helpful. What is causing these drop downs to disable? !the problem
If you go to Tools|Options|Text Editor|HTML|Validation, your Target markup is probably set to XHTML or some markup where you have no choice. Set it to something like HTML5 (not XML) and those options will light up again.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, visual studio 2010, dojo, formatting" }
0.8.42/Error with Dates there themes to be a problem with reading null dates on Entities. (could not find out if actually only for null values or in general till now) This method seems to be the problem (not sure): (breeze.debug.js, l. 610) function isDate(o) { return classof(o) === "date" && !isNaN(o.getTime()); } o does not have a method `getTime()` here. I could not track the problem down any further. Due to promises stepping through the code does not work well. * _EDIT: *_ I updated from 0.8.34, where it is still working
Ok, this was a bug involving local entity queries for null dates. It has been fixed in v 0.84.3 and is now available here. Thanks Sascha!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "breeze" }